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

MODEL({
  name: 'PositionedViewTrait',
  properties: [
    { model_: 'FloatProperty', name: 'x',      units: 'px', defaultValue: 0 },
    { model_: 'FloatProperty', name: 'y',      units: 'px', defaultValue: 0 },
    { model_: 'FloatProperty', name: 'z',      units: 'px', defaultValue: 0 },
    { model_: 'IntProperty', name: 'width',  units: 'px', defaultValue: 100 },
    { model_: 'IntProperty', name: 'height', units: 'px', defaultValue: 100 },
    { model_: 'IntProperty', name: 'preferredWidth', units: 'px', defaultValue: 100 },
    { model_: 'IntProperty', name: 'preferredHeight', units: 'px', defaultValue: 100 }
  ]
});

MODEL({
  name: 'PositionedDOMViewTrait',
  traits: ['PositionedViewTrait'],
  methods: {
    toHTML: function() {
      return '
' +
        this.toInnerHTML() +
        '
';
    },
    layoutStyle: function() {
      return ' style="' +
        '-webkit-transform:' + this.transform() +
        ';width:' + this.styleWidth() +
        ';height:' + this.styleHeight() +
        ';position:absolute;"';
    },
    initHTML: function() {
      this.SUPER();
      var self = this;
      this.X.dynamic(function() { self.x; self.y; self.z; },
                     this.position);
      this.X.dynamic(function() { self.width; self.height; },
                     this.resize);
      this.$.style.position = 'absolute';
      this.position();
      this.resize();
    },
    transform: function() {
      return 'translate3d(' +
        this.x + 'px,' +
        this.y + 'px,' +
        this.z + 'px)';
    },
    styleWidth: function() {
      return this.width + 'px';
    },
    styleHeight: function() {
      return this.height + 'px';
    }
  },
  listeners: [
    {
      name: 'position',
      code: function() {
        if ( ! this.$ ) return;
        this.$.style.webkitTransform = this.transform();
      }
    },
    {
      name: 'resize',
      code: function() {
        if ( ! this.$ ) return;
        this.$.style.width  = this.styleWidth();
        this.$.style.height = this.styleHeight();
      }
    }
  ]
});

MODEL({
  name: 'Window',
  properties: [
    { model_: 'IntProperty', name: 'width' },
    { model_: 'IntProperty', name: 'height' },
    {
      name: 'window',
      postSet: function(o, w) {
        o && o.removeEventListener('resize', this.onResize);
        w.addEventListener('resize', this.onResize);
        this.onResize();
      },
      hidden: true
    },
    {
      name: 'view',
      type: 'View',
      postSet: function(old, v) {
        var self = this;
        v.x = 0;
        v.y = 0;
        this.X.dynamic(function() { self.width; self.height; },
                       function() {
                         v.width = self.width;
                         v.height = self.height;
                       });
        var s = this.window.document.body.style;
        s.padding = 0;
        s.margin = 0;
        s.border = 0;
        this.window.document.body.insertAdjacentHTML('beforeend', v.toHTML());
        v.initHTML();
      }
    }
  ],
  listeners: [
    {
      name: 'onResize',
      code: function() {
        this.height = this.window.innerHeight;
        this.width  = this.window.innerWidth;
      }
    }
  ]
});

MODEL({
  name: 'Point',
  properties: [
    { model_: 'IntProperty', name: 'x' },
    { model_: 'IntProperty', name: 'y' }
  ]
});

MODEL({
  name: 'FloatingView',
  extendsModel: 'View',
  traits: ['PositionedDOMViewTrait'],
  properties: [
    { name: 'view' },
    { name: 'width',  defaultValue: 300 },
    { name: 'height', defaultValue: 300 }
  ],
  templates: [
    function toInnerHTML() {/* %%view */}
  ]
});

MODEL({
  name: 'ViewSlider',
  traits: ['PositionedDOMViewTrait'],
  extendsModel: 'View',
  properties: [
    {
      name: 'view'
    },
    {
      name: 'incomingView'
    },
    {
      model_: 'StringEnumProperty',
      name: 'direction',
      choices: ['horizontal', 'vertical'],
      defaultValue: 'horizontal'
    },
    {
      model_: 'BooleanProperty',
      name: 'reverse',
      defaultValue: false
    },
    {
      model_: 'FloatProperty',
      name: 'slideAmount',
      defaultValue: 0
    },
    'latch'
  ],
  methods: {
    init: function() {
      this.SUPER();
      var self = this;
      this.X.dynamic(function() { self.width; self.height; self.direction; self.slideAmount; self.reverse },
                     this.layout);
    },
    toHTML: function() {
      this.children = [];
      return this.SUPER();
    },
    initHTML: function() {
      this.layout();
      this.SUPER();
    },
    setView: function(view) {
      if ( this.view ) {
        this.$.removeChild(this.view.$);
      }
      this.view = view;
      this.layout();
      this.$.insertAdjacentHTML('beforeend', view.toHTML());
      view.initHTML();
    },
    slideView: function(view, opt_interp, opt_time) {
      if ( ! this.$ ) return;

      if ( this.latch ) {
        this.latch();
        this.latch = '';
      }

      this.incomingView = view;
      this.layout();
      this.$.insertAdjacentHTML('beforeend', view.toHTML());
      view.initHTML();

      opt_interp = opt_interp || Movement.easeOut(1);
      opt_time = opt_time || 300;

      var self = this;

      var fn = function() {
        self.slideAmount = 1.0;
      };

      this.latch = Movement.animate(opt_time, fn, opt_interp, function() {
        if ( self.view ) self.$.removeChild(self.view.$);
        self.view = view;
        self.incomingView = '';
        self.latch = '';
        self.slideAmount = 0;
      })();
    }
  },
  templates: [
    function toInnerHTML() {/* <%= this.view %> */}
  ],
  listeners: [
    {
      name: 'layout',
      code: function() {
        this.view.width = this.width;
        this.view.height = this.height;

        if ( this.incomingView ) {
          this.incomingView.width = this.width;
          this.incomingView.height = this.height;
        }

        var r = 1;
        if ( this.reverse ) r = -1;

        if ( this.direction === 'horizontal' ) {
          this.view.x = -(r * this.slideAmount * this.width);
          this.view.y = 0;
          if ( this.incomingView ) {
            this.incomingView.x = r * this.width - (r * this.slideAmount * this.width);
            this.incomingView.y = 0;
          }
        } else {
          this.view.x = 0;
          this.view.y = -(r * this.slideAmount * this.height);
          if ( this.incomingView ) {
            this.incomingView.x = 0;
            this.incomingView.y = r * this.height - (r * this.slideAmount * this.height);
          }
        }
      }
    }
  ]
});

MODEL({
  name: 'OverlaySlider',
  traits: ['PositionedDOMViewTrait'],
  extendsModel: 'View',
  properties: [
    {
      name: 'view',
      postSet: function(old, v) {
        if ( this.$ ) { this.updateHTML(); }
      }
    },
    { model_: 'FloatProperty', name: 'slideAmount', defaultValue: 0 }
  ],
  methods: {
    init: function() {
      this.SUPER();
      var self = this;
      this.X.dynamic(function() { self.width; self.height; self.slideAmount; }, this.layout);
    },
    updateHTML: function() {
      this.children = [];
      this.layout();
      this.SUPER();
    },
    initHTML: function() {
      debugger;
      this.SUPER();
    }
  },
  templates: [
    function toInnerHTML() {/*
      <% this.on('click', this.onClick, this.id + '-slider'); %>
      <div id="<%= this.id %>-slider" class="overlay-slider">
 %%view */},
    function CSS() {/*
      .overlay-slider {
        position: absolute;
        background: black;
      }

      * {
        transform-style: preserve-3d;
        -webkit-transform-style: preserve-3d;
      }
    */}
  ],
  listeners: [
    {
      name: 'onClick',
      code: function() {
        this.publish(['click']);
      }
    },
    {
      name: 'layout',
      code: function() {
        var width = Math.min(this.view.preferredWidth,
                             this.width);

        if ( this.$ ) {
          var overlay = this.X.$(this.id + '-slider');
          overlay.style.webkitTransform = 'translate3d(0,0,0px)';
          overlay.style.width = this.width + 'px';
          overlay.style.height = this.height + 'px';
          overlay.style.opacity = this.slideAmount * 0.4;
        }

        if ( this.view ) {
          this.view.width = width;
          this.view.height = this.height;
          this.view.x = -((1 - this.slideAmount) * width);
          this.view.y = 0;
          this.view.z = 1;
        }
      }
    }
  ]
});

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

MODEL({
  name: 'PositionedViewTrait',
  properties: [
    { model_: 'FloatProperty', name: 'x',      units: 'px', defaultValue: 0 },
    { model_: 'FloatProperty', name: 'y',      units: 'px', defaultValue: 0 },
    { model_: 'FloatProperty', name: 'z',      units: 'px', defaultValue: 0 },
    { model_: 'IntProperty', name: 'width',  units: 'px', defaultValue: 100 },
    { model_: 'IntProperty', name: 'height', units: 'px', defaultValue: 100 },
    { model_: 'IntProperty', name: 'preferredWidth', units: 'px', defaultValue: 100 },
    { model_: 'IntProperty', name: 'preferredHeight', units: 'px', defaultValue: 100 }
  ]
});

MODEL({
  name: 'PositionedDOMViewTrait',
  traits: ['PositionedViewTrait'],
  methods: {
    toHTML: function() {
      return '
' +
        this.toInnerHTML() +
        '
';
    },
    layoutStyle: function() {
      return ' style="' +
        '-webkit-transform:' + this.transform() +
        ';width:' + this.styleWidth() +
        ';height:' + this.styleHeight() +
        ';position:absolute;"';
    },
    initHTML: function() {
      this.SUPER();
      var self = this;
      this.X.dynamic(function() { self.x; self.y; self.z; },
                     this.position);
      this.X.dynamic(function() { self.width; self.height; },
                     this.resize);
      this.$.style.position = 'absolute';
      this.position();
      this.resize();
    },
    transform: function() {
      return 'translate3d(' +
        this.x + 'px,' +
        this.y + 'px,' +
        this.z + 'px)';
    },
    styleWidth: function() {
      return this.width + 'px';
    },
    styleHeight: function() {
      return this.height + 'px';
    }
  },
  listeners: [
    {
      name: 'position',
      code: function() {
        if ( ! this.$ ) return;
        this.$.style.webkitTransform = this.transform();
      }
    },
    {
      name: 'resize',
      code: function() {
        if ( ! this.$ ) return;
        this.$.style.width  = this.styleWidth();
        this.$.style.height = this.styleHeight();
      }
    }
  ]
});

MODEL({
  name: 'Window',
  properties: [
    { model_: 'IntProperty', name: 'width' },
    { model_: 'IntProperty', name: 'height' },
    {
      name: 'window',
      postSet: function(o, w) {
        o && o.removeEventListener('resize', this.onResize);
        w.addEventListener('resize', this.onResize);
        this.onResize();
      },
      hidden: true
    },
    {
      name: 'view',
      type: 'View',
      postSet: function(old, v) {
        var self = this;
        v.x = 0;
        v.y = 0;
        this.X.dynamic(function() { self.width; self.height; },
                       function() {
                         v.width = self.width;
                         v.height = self.height;
                       });
        var s = this.window.document.body.style;
        s.padding = 0;
        s.margin = 0;
        s.border = 0;
        this.window.document.body.insertAdjacentHTML('beforeend', v.toHTML());
        v.initHTML();
      }
    }
  ],
  listeners: [
    {
      name: 'onResize',
      code: function() {
        this.height = this.window.innerHeight;
        this.width  = this.window.innerWidth;
      }
    }
  ]
});

MODEL({
  name: 'Point',
  properties: [
    { model_: 'IntProperty', name: 'x' },
    { model_: 'IntProperty', name: 'y' }
  ]
});

MODEL({
  name: 'FloatingView',
  extendsModel: 'View',
  traits: ['PositionedDOMViewTrait'],
  properties: [
    { name: 'view' },
    { name: 'width',  defaultValue: 300 },
    { name: 'height', defaultValue: 300 }
  ],
  templates: [
    function toInnerHTML() {/* %%view */}
  ]
});

MODEL({
  name: 'ViewSlider',
  traits: ['PositionedDOMViewTrait'],
  extendsModel: 'View',
  properties: [
    {
      name: 'view'
    },
    {
      name: 'incomingView'
    },
    {
      model_: 'StringEnumProperty',
      name: 'direction',
      choices: ['horizontal', 'vertical'],
      defaultValue: 'horizontal'
    },
    {
      model_: 'BooleanProperty',
      name: 'reverse',
      defaultValue: false
    },
    {
      model_: 'FloatProperty',
      name: 'slideAmount',
      defaultValue: 0
    },
    'latch'
  ],
  methods: {
    init: function() {
      this.SUPER();
      var self = this;
      this.X.dynamic(function() { self.width; self.height; self.direction; self.slideAmount; self.reverse },
                     this.layout);
    },
    toHTML: function() {
      this.children = [];
      return this.SUPER();
    },
    initHTML: function() {
      this.layout();
      this.SUPER();
    },
    setView: function(view) {
      if ( this.view ) {
        this.$.removeChild(this.view.$);
      }
      this.view = view;
      this.layout();
      this.$.insertAdjacentHTML('beforeend', view.toHTML());
      view.initHTML();
    },
    slideView: function(view, opt_interp, opt_time) {
      if ( ! this.$ ) return;

      if ( this.latch ) {
        this.latch();
        this.latch = '';
      }

      this.incomingView = view;
      this.layout();
      this.$.insertAdjacentHTML('beforeend', view.toHTML());
      view.initHTML();

      opt_interp = opt_interp || Movement.easeOut(1);
      opt_time = opt_time || 300;

      var self = this;

      var fn = function() {
        self.slideAmount = 1.0;
      };

      this.latch = Movement.animate(opt_time, fn, opt_interp, function() {
        if ( self.view ) self.$.removeChild(self.view.$);
        self.view = view;
        self.incomingView = '';
        self.latch = '';
        self.slideAmount = 0;
      })();
    }
  },
  templates: [
    function toInnerHTML() {/* <%= this.view %> */}
  ],
  listeners: [
    {
      name: 'layout',
      code: function() {
        this.view.width = this.width;
        this.view.height = this.height;

        if ( this.incomingView ) {
          this.incomingView.width = this.width;
          this.incomingView.height = this.height;
        }

        var r = 1;
        if ( this.reverse ) r = -1;

        if ( this.direction === 'horizontal' ) {
          this.view.x = -(r * this.slideAmount * this.width);
          this.view.y = 0;
          if ( this.incomingView ) {
            this.incomingView.x = r * this.width - (r * this.slideAmount * this.width);
            this.incomingView.y = 0;
          }
        } else {
          this.view.x = 0;
          this.view.y = -(r * this.slideAmount * this.height);
          if ( this.incomingView ) {
            this.incomingView.x = 0;
            this.incomingView.y = r * this.height - (r * this.slideAmount * this.height);
          }
        }
      }
    }
  ]
});

MODEL({
  name: 'OverlaySlider',
  traits: ['PositionedDOMViewTrait'],
  extendsModel: 'View',
  properties: [
    {
      name: 'view',
      postSet: function(old, v) {
        if ( this.$ ) { this.updateHTML(); }
      }
    },
    { model_: 'FloatProperty', name: 'slideAmount', defaultValue: 0 }
  ],
  methods: {
    init: function() {
      this.SUPER();
      var self = this;
      this.X.dynamic(function() { self.width; self.height; self.slideAmount; }, this.layout);
    },
    updateHTML: function() {
      this.children = [];
      this.layout();
      this.SUPER();
    }
  },
  templates: [
    function toInnerHTML() {/*
      <% this.on('click', this.onClick, this.id + '-slider'); %>
      <div id="<%= this.id %>-slider" class="overlay-slider">
 %%view */},
    function CSS() {/*
      .overlay-slider {
        position: absolute;
        background: black;
      }

      * {
        transform-style: preserve-3d;
        -webkit-transform-style: preserve-3d;
      }
    */}
  ],
  listeners: [
    {
      name: 'onClick',
      code: function() {
        this.publish(['click']);
      }
    },
    {
      name: 'layout',
      code: function() {
        var width = Math.min(this.view.preferredWidth,
                             this.width);

        if ( this.$ ) {
          var overlay = this.X.$(this.id + '-slider');
          overlay.style.webkitTransform = 'translate3d(0,0,0px)';
          overlay.style.width = this.width + 'px';
          overlay.style.height = this.height + 'px';
          overlay.style.opacity = this.slideAmount * 0.4;
        }

        if ( this.view ) {
          this.view.width = width;
          this.view.height = this.height;
          this.view.x = -((1 - this.slideAmount) * width);
          this.view.y = 0;
          this.view.z = 1;
        }
      }
    }
  ]
});

<|endoftext|>


<commit_before>var PeerServer = require('peer').PeerServer;
var server = new PeerServer({port: 9000, path: '/', allow_discovery: true});

var log = function() {
  var message = Array.prototype.slice.call(arguments).join(' ');
  console.log(new Date().toISOString(), message);
}

log('Hello. This is Scholar Ninja server.');

var networkCheckers = {};
var lastSeens = {}

var config = {
  maxNoHelloTime: 60000,
  networkCheckInterval: 30000
}

var networkCheck = function (id) {
  console.log('Network check', id);
  // Remove peer if they haven't contacted in server in 1 minute.
  if(lastSeens.id < Date.now() - config.maxNoHelloTime) {
    try {
      if(server._clients.peerjs[id]) {
        server._clients.peerjs[id].socket.close();
      }
      server._removePeer(id, 'peerjs');
    }
    catch(e) {
      log(e)
    }
  }
}

server.on('connection', function(id) {
  log('Connected:', id );
  lastSeens.id = Date.now();
  // Check if node is accessible every minute
  server._clients.peerjs[id].socket.on('message', function(data) {
    if(JSON.parse(data).type === 'HELLO') {
      console.log('Peer', id, 'says HELLO.');
      lastSeens.id = Date.now();
    }
  });
  networkCheckers.id = setInterval(networkCheck, config.networkCheckInterval, id);
  logNumberOfPeers();
});

server.on('disconnect', function(id) {
  log('Disconnected:', id );
  clearInterval(networkCheckers.id);
  logNumberOfPeers();
});

// Log number of peers
var logNumberOfPeers = function () {
  if (server._clients['peerjs']) {
    var numberOfPeers = Object.keys(server._clients['peerjs']).length
    log('Current number of peers:', numberOfPeers);
  }
};

// Log peer listings
server._app.pre(function(req, res, next) {
  log('IP', req.connection.remoteAddress, 'requested', req.path());
  return next();
});

// Simple HTTP endpoint for Chord peers
// Returns array of peer ids, e.g. ['peer1','peer2']
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*'
  });
  if(server._clients.peerjs) {
    res.end(JSON.stringify(Object.keys(server._clients.peerjs)));
  } else {
    res.end(JSON.stringify([]));
  }
}).listen(9001);
<commit_msg>Now on port 9002, with a longer network check interval.<commit_after>var PeerServer = require('peer').PeerServer;
var server = new PeerServer({port: 9002, path: '/', allow_discovery: true});

var log = function() {
  var message = Array.prototype.slice.call(arguments).join(' ');
  console.log(new Date().toISOString(), message);
}

log('Hello. This is Scholar Ninja server.');

var networkCheckers = {};
var lastSeens = {}

var config = {
  maxNoHelloTime: 60000,
  networkCheckInterval: 55000
}

var networkCheck = function (id) {
  console.log('Network check', id);
  // Remove peer if they haven't contacted in server in 1 minute.
  if(lastSeens.id < Date.now() - config.maxNoHelloTime) {
    try {
      if(server._clients.peerjs[id]) {
        server._clients.peerjs[id].socket.close();
      }
      server._removePeer(id, 'peerjs');
    }
    catch(e) {
      log(e)
    }
  }
}

server.on('connection', function(id) {
  log('Connected:', id );
  lastSeens.id = Date.now();
  // Check if node is accessible every minute
  server._clients.peerjs[id].socket.on('message', function(data) {
    if(JSON.parse(data).type === 'HELLO') {
      console.log('Peer', id, 'says HELLO.');
      lastSeens.id = Date.now();
    }
  });
  networkCheckers.id = setInterval(networkCheck, config.networkCheckInterval, id);
  logNumberOfPeers();
});

server.on('disconnect', function(id) {
  log('Disconnected:', id );
  clearInterval(networkCheckers.id);
  logNumberOfPeers();
});

// Log number of peers
var logNumberOfPeers = function () {
  if (server._clients['peerjs']) {
    var numberOfPeers = Object.keys(server._clients['peerjs']).length
    log('Current number of peers:', numberOfPeers);
  }
};

// Log peer listings
server._app.pre(function(req, res, next) {
  log('IP', req.connection.remoteAddress, 'requested', req.path());
  return next();
});

// Simple HTTP endpoint for Chord peers
// Returns array of peer ids, e.g. ['peer1','peer2']
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*'
  });
  if(server._clients.peerjs) {
    res.end(JSON.stringify(Object.keys(server._clients.peerjs)));
  } else {
    res.end(JSON.stringify([]));
  }
}).listen(9001);
<|endoftext|>


<commit_before>const test = require('tape')

const proxyquire = require('proxyquire').noCallThru()
test.only('should require without connecting to azure', t => {
  const azureStorage = proxyquire('../../azureStorage.js', {'azure': {createBlobService: () => Promise.resolve()}})
  t.plan(1)
  t.ok(azureStorage)
})
<commit_msg>run all tests<commit_after>const test = require('tape')

const proxyquire = require('proxyquire').noCallThru()
test('should require without connecting to azure', t => {
  const azureStorage = proxyquire('../../azureStorage.js', {'azure': {createBlobService: () => Promise.resolve()}})
  t.plan(1)
  t.ok(azureStorage)
})
<|endoftext|>


<commit_before>define(['jquery', 'appearanceUtils'], function($, utils) {
   return {
      navbar: "#restore-buttons",
      page_indicator_box: "#global-indicators",
      page_indicators: {
         pull_count: function(pulls, node) {
            node.text(pulls.length + " open pulls");
            node.wrapInner('');
         }
      },
      // Global filters
      // where
      selector: function(pull) {
         return pull.state == 'open';
      },
      // order by
      sort: function(pull) {
         return pull.created_at;
      },
      // Allows custom modifications of each pull's display
      adjust: function(pull, node) {
         // If the pull is over 30 days old...
         if (Date.now() - (new Date(pull.created_at)) > 2590000000 ) {
            // Mark it in red
            $(node).addClass('bg-warning');
         }
      },
      // Functions to stick status information in indicators at the bottom of each pull
      indicators: {
         cr_remaining: function cr_remaining(pull, node) {
            var required = pull.status.cr_req;
            var completed = pull.status.CR.length;

            var text = $('
CR ' + completed + '/' + required + '
');

            node.append(text);

            if (completed >= required) {
               text.addClass('text-success');
            }

            pull.status.CR.forEach(function(signature) {
               var user = signature.data.user;
               node.append(utils.getAvatarDOMNode(user.login, user.id));
            });
         },
         qa_remaining: function qa_remaining(pull, node) {
            var required = pull.status.qa_req;
            var completed = pull.status.QA.length;

            var text = $('
QA ' + completed + '/' + required + '
');

            node.append(text);

            if (completed >= required) {
               text.addClass('text-success');
            }

            pull.status.QA.forEach(function(signature) {
               var user = signature.data.user;
               node.append(utils.getAvatarDOMNode(user.login, user.id));
            });
         },
         status: function status(pull, node) {
            if (pull.status.commit_status) {
            var commit_status = pull.status.commit_status.data;
               var title = commit_status.description;
               var url   = commit_status.target_url;
               var state = commit_status.state;

               var link = $('');
               node.append(link);
               link.tooltip();
               switch(commit_status.state) {
                  case 'pending':
                  link.append('');
                  break;
                  case 'success':
                  link.append('');
                  break;
                  case 'error':
                  link.append('');
                  break;
                  case 'failure':
                  link.append('');
                  break;
               }
            }
         },
         user_icon: function user_icon(pull, node) {
            if (pull.is_mine()) {
               node.append('');
            }
         }
      },
      columns: [
         {
            title: "CI Unsuccessful",
            id: "ciUnsuccessful",
            selector: function(pull) {
               return pull.build_status() != 'success' && !pull.dev_blocked();
            },
            sort: function(pull) {
               var score = 0;
               if (pull.is_mine()) {
                  score -= 15;
               }

               score -= pull.status.CR.length * 1;
               score -= pull.status.QA.length * 2;

               if (!pull.status.commit_status) {
                  score += 15;
               }

               return score;
            },
            triggers: {
               onCreate: function(blob, container) {
                  blob.removeClass('panel-default').addClass('panel-primary');
               },
               onUpdate: function(blob, container) {
                  utils.hideIfEmpty(container, blob, '.pull');
               }
            },
            shrinkToButton: true
         },
         {
            title: "deploy_blocked Pulls",
            id: "deployBlockPulls",
            selector: function(pull) {
               return pull.deploy_blocked() && !pull.dev_blocked() &&
                !pull.build_failed();
            },
            adjust: function(pull, node) {
               node.addClass('list-group-item-danger');
            },
            triggers: {
               onCreate: function(blob, container) {
                  blob.removeClass('panel-default').addClass('panel-primary');
               },
               onUpdate: function(blob, container) {
                  utils.hideIfEmpty(container, blob, '.pull');
               }
            },
            shrinkToButton: true
         },
         {
            title: "Ready Pulls",
            id: "readyPulls",
            selector: function(pull) {
               return pull.status.ready && !pull.dev_blocked() &&
               !pull.deploy_blocked() && pull.build_status() == 'success';
            },
            adjust: function(pull, node) {
               node.addClass('list-group-item-success');
            },
            triggers: {
               onCreate: function(blob, container) {
                  blob.removeClass('panel-default').addClass('panel-primary');
               },
               onUpdate: function(blob, container) {
                  utils.hideIfEmpty(container, blob, '.pull');
               }
            },
            shrinkToButton: true
         },
         {
            title: "dev_blocked Pulls",
            id: "blockPulls",
            selector: function(pull) {
               return pull.dev_blocked() ||
                (pull.cr_done() && pull.build_failed());
            },
            sort: function(pull) {
               return pull.is_mine() ? 0 : 1;
            }
         },
         {
            title: "CR Pulls",
            id: "crPulls",
            selector: function(pull) {
               return !pull.cr_done() && !pull.dev_blocked();
            },
            sort: function(pull) {
               if (pull.is_mine()) {
                  return 3;
               } else if (pull.qa_done() && pull.build_status() == 'success') {
                  return 0;
               } else if (pull.qa_done()) {
                  return 1;
               } else {
                  return 2;
               }
            },
            indicators: {
               cr_remaining: function(pull, node) {
                  var required = pull.status.cr_req;
                  var remaining = required - pull.status.CR.length;
               }
            }
         },
         {
            title: "QA Pulls",
            id: "qaPulls",
            selector: function(pull) {
               var isHotfix = /^hotfix/.test(pull.head.ref);
               var numCRs = pull.status.CR.length;

               return !pull.qa_done() && !pull.dev_blocked() &&
                (numCRs > 0 || isHotfix) && !pull.build_failed();
            },
            sort: function(pull) {
               if (pull.is_mine()) {
                  return 4;
               } else if (pull.cr_done() && pull.build_status() == 'success') {
                  return 0;
               } else if (pull.build_status() == 'success') {
                  return 1;
               } else if (pull.cr_done()) {
                  return 2;
               } else {
                  return 3;
               }
            },
            indicators: {
               qa_remaining: function(pull, node) {
                  var required = pull.status.qa_req;
                  var remaining = required - pull.status.QA.length;
               }
            }

         }
      ]
   };
});
<commit_msg>Make == into ===<commit_after>define(['jquery', 'appearanceUtils'], function($, utils) {
   return {
      navbar: "#restore-buttons",
      page_indicator_box: "#global-indicators",
      page_indicators: {
         pull_count: function(pulls, node) {
            node.text(pulls.length + " open pulls");
            node.wrapInner('');
         }
      },
      // Global filters
      // where
      selector: function(pull) {
         return pull.state === 'open';
      },
      // order by
      sort: function(pull) {
         return pull.created_at;
      },
      // Allows custom modifications of each pull's display
      adjust: function(pull, node) {
         // If the pull is over 30 days old...
         if (Date.now() - (new Date(pull.created_at)) > 2590000000 ) {
            // Mark it in red
            $(node).addClass('bg-warning');
         }
      },
      // Functions to stick status information in indicators at the bottom of each pull
      indicators: {
         cr_remaining: function cr_remaining(pull, node) {
            var required = pull.status.cr_req;
            var completed = pull.status.CR.length;

            var text = $('
CR ' + completed + '/' + required + '
');

            node.append(text);

            if (completed >= required) {
               text.addClass('text-success');
            }

            pull.status.CR.forEach(function(signature) {
               var user = signature.data.user;
               node.append(utils.getAvatarDOMNode(user.login, user.id));
            });
         },
         qa_remaining: function qa_remaining(pull, node) {
            var required = pull.status.qa_req;
            var completed = pull.status.QA.length;

            var text = $('
QA ' + completed + '/' + required + '
');

            node.append(text);

            if (completed >= required) {
               text.addClass('text-success');
            }

            pull.status.QA.forEach(function(signature) {
               var user = signature.data.user;
               node.append(utils.getAvatarDOMNode(user.login, user.id));
            });
         },
         status: function status(pull, node) {
            if (pull.status.commit_status) {
            var commit_status = pull.status.commit_status.data;
               var title = commit_status.description;
               var url   = commit_status.target_url;
               var state = commit_status.state;

               var link = $('');
               node.append(link);
               link.tooltip();
               switch(commit_status.state) {
                  case 'pending':
                  link.append('');
                  break;
                  case 'success':
                  link.append('');
                  break;
                  case 'error':
                  link.append('');
                  break;
                  case 'failure':
                  link.append('');
                  break;
               }
            }
         },
         user_icon: function user_icon(pull, node) {
            if (pull.is_mine()) {
               node.append('');
            }
         }
      },
      columns: [
         {
            title: "CI Unsuccessful",
            id: "ciUnsuccessful",
            selector: function(pull) {
               return pull.build_status() != 'success' && !pull.dev_blocked();
            },
            sort: function(pull) {
               var score = 0;
               if (pull.is_mine()) {
                  score -= 15;
               }

               score -= pull.status.CR.length * 1;
               score -= pull.status.QA.length * 2;

               if (!pull.status.commit_status) {
                  score += 15;
               }

               return score;
            },
            triggers: {
               onCreate: function(blob, container) {
                  blob.removeClass('panel-default').addClass('panel-primary');
               },
               onUpdate: function(blob, container) {
                  utils.hideIfEmpty(container, blob, '.pull');
               }
            },
            shrinkToButton: true
         },
         {
            title: "deploy_blocked Pulls",
            id: "deployBlockPulls",
            selector: function(pull) {
               return pull.deploy_blocked() && !pull.dev_blocked() &&
                !pull.build_failed();
            },
            adjust: function(pull, node) {
               node.addClass('list-group-item-danger');
            },
            triggers: {
               onCreate: function(blob, container) {
                  blob.removeClass('panel-default').addClass('panel-primary');
               },
               onUpdate: function(blob, container) {
                  utils.hideIfEmpty(container, blob, '.pull');
               }
            },
            shrinkToButton: true
         },
         {
            title: "Ready Pulls",
            id: "readyPulls",
            selector: function(pull) {
               return pull.status.ready && !pull.dev_blocked() &&
               !pull.deploy_blocked() && pull.build_status() === 'success';
            },
            adjust: function(pull, node) {
               node.addClass('list-group-item-success');
            },
            triggers: {
               onCreate: function(blob, container) {
                  blob.removeClass('panel-default').addClass('panel-primary');
               },
               onUpdate: function(blob, container) {
                  utils.hideIfEmpty(container, blob, '.pull');
               }
            },
            shrinkToButton: true
         },
         {
            title: "dev_blocked Pulls",
            id: "blockPulls",
            selector: function(pull) {
               return pull.dev_blocked() ||
                (pull.cr_done() && pull.build_failed());
            },
            sort: function(pull) {
               return pull.is_mine() ? 0 : 1;
            }
         },
         {
            title: "CR Pulls",
            id: "crPulls",
            selector: function(pull) {
               return !pull.cr_done() && !pull.dev_blocked();
            },
            sort: function(pull) {
               if (pull.is_mine()) {
                  return 3;
               } else if (pull.qa_done() && pull.build_status() === 'success') {
                  return 0;
               } else if (pull.qa_done()) {
                  return 1;
               } else {
                  return 2;
               }
            },
            indicators: {
               cr_remaining: function(pull, node) {
                  var required = pull.status.cr_req;
                  var remaining = required - pull.status.CR.length;
               }
            }
         },
         {
            title: "QA Pulls",
            id: "qaPulls",
            selector: function(pull) {
               var isHotfix = /^hotfix/.test(pull.head.ref);
               var numCRs = pull.status.CR.length;

               return !pull.qa_done() && !pull.dev_blocked() &&
                (numCRs > 0 || isHotfix) && !pull.build_failed();
            },
            sort: function(pull) {
               if (pull.is_mine()) {
                  return 4;
               } else if (pull.cr_done() && pull.build_status() === 'success') {
                  return 0;
               } else if (pull.build_status() === 'success') {
                  return 1;
               } else if (pull.cr_done()) {
                  return 2;
               } else {
                  return 3;
               }
            },
            indicators: {
               qa_remaining: function(pull, node) {
                  var required = pull.status.qa_req;
                  var remaining = required - pull.status.QA.length;
               }
            }

         }
      ]
   };
});
<|endoftext|>


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

var events = require('events');
var fs = require('fs');
var util = require('util');
var path = require('path');

var async = require('async');
var log = require('logmagic').local('dreadnot');
var mkdirp = require('mkdirp');

var sprintf = require('./util/sprintf');

var errors = require('./errors');
var Stack = require('./stack').Stack;

function Dreadnot(config, stackdir) {
  log.info('using config', config);
  this.config = config;
  this.stackdir = stackdir;
  this._stacks = {};
  this.locks = {};
  this.emitter = new events.EventEmitter();
  this.warning = '';
  this.queue = async.queue(function(task, callback) {
    task(callback);
  }, 1);
}

Dreadnot.prototype._getStack = function(name) {
  if (!this._stacks[name]) {
    this._stacks[name] = new Stack(name, this, this.config);
  }

  return this._stacks[name];
};

Dreadnot.prototype.emit = function(id, data) {
  this.emitter.emit(id, data);
};

Dreadnot.prototype.lock = function(names, deployment, callback) {
  var i;

  // Check for conflicting locks
  for (i = 0; i < names.length; i++) {
    if (this.locks[names[i]]) {
      return new errors.StackLockedError(this.locks[names[i]]);
    }
  }

  // Set requested locks
  for (i = 0; i < names.length; i++) {
    this.locks[names[i]] = deployment;
  }

  return null;
};

Dreadnot.prototype.unlock = function(names) {
  var i;

  for (i = 0; i < names.length; i++) {
    delete this.locks[names[i]];
  }
};

Dreadnot.prototype.setWarning = function(user, text, callback) {
  var self = this;

  this.queue.push(function(callback) {
    fs.writeFile(path.join(self.config.data_root, 'warning.txt'), text, function(err) {
      if (!err) {
        self.warning = text;
        if (text) {
          log.warnf('warning set to "${text}"', {
            text: text
          });
        } else {
          log.info('warning cleared');
        }
      }
      callback(err);
    });
  }, callback);
};

Dreadnot.prototype.getStack = function(name, callback) {
  var stack = this._stacks[name];
  if (!stack) {
    callback(new errors.NotFoundError('Stack not found'));
  } else {
    callback(null, stack);
  }
};

Dreadnot.prototype.init = function(callback) {
  var self = this,
      stackNames = Object.keys(this.config.stacks);

  async.series([
    mkdirp.bind(null, self.config.data_root, 493),

    function(callback) {
      fs.readFile(path.join(self.config.data_root, 'warning.txt'), 'utf8', function(err, text) {
        if (err && err.code !== 'ENOENT') {
          callback(err);
        } else {
          self.warning = err ? '' : text.replace(/^\s+|\s+$/g, '');
          if (self.warning) {
            log.warnf('warning set to "${text}"', {
              text: self.warning
            });
          } else {
            log.info('no warning set');
          }
          callback();
        }
      });
    },

    function(callback) {
      async.forEach(stackNames, function(stackName, callback) {
        self._getStack(stackName).init(callback);
      }, callback);
    }
  ], callback);
};

Dreadnot.prototype.getName = function() {
  return this.config.name;
};

Dreadnot.prototype.getSummary = function(callback) {
  callback(null, {name: this.config.env});
};

Dreadnot.prototype.getDetails = function(callback) {
  var self = this,
      stackNames = Object.keys(this.config.stacks);

  async.map(stackNames, function(stackName, callback) {
    self._getStack(stackName).getDetails(callback);
  },

  function(err, summaries) {
    callback(err, {
      name: self.config.env,
      stacks: summaries
    });
  });
};

Dreadnot.prototype.runningStatus = function(callback) {
  var self = this,
      stackNames = Object.keys(this.config.stacks);

  async.map(stackNames, function(stackName, callback) {
    self._getStack(stackName).runningStatus(callback);
  }, callback);
};

exports.Dreadnot = Dreadnot;
<commit_msg>Emit an event when a warning has been set or removed.<commit_after>/*
 *  Copyright 2011 Rackspace
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

var events = require('events');
var fs = require('fs');
var util = require('util');
var path = require('path');

var async = require('async');
var log = require('logmagic').local('dreadnot');
var mkdirp = require('mkdirp');

var sprintf = require('./util/sprintf');

var errors = require('./errors');
var Stack = require('./stack').Stack;

function Dreadnot(config, stackdir) {
  log.info('using config', config);
  this.config = config;
  this.stackdir = stackdir;
  this._stacks = {};
  this.locks = {};
  this.emitter = new events.EventEmitter();
  this.warning = '';
  this.queue = async.queue(function(task, callback) {
    task(callback);
  }, 1);
}

Dreadnot.prototype._getStack = function(name) {
  if (!this._stacks[name]) {
    this._stacks[name] = new Stack(name, this, this.config);
  }

  return this._stacks[name];
};

Dreadnot.prototype.emit = function(id, data) {
  this.emitter.emit(id, data);
};

Dreadnot.prototype.lock = function(names, deployment, callback) {
  var i;

  // Check for conflicting locks
  for (i = 0; i < names.length; i++) {
    if (this.locks[names[i]]) {
      return new errors.StackLockedError(this.locks[names[i]]);
    }
  }

  // Set requested locks
  for (i = 0; i < names.length; i++) {
    this.locks[names[i]] = deployment;
  }

  return null;
};

Dreadnot.prototype.unlock = function(names) {
  var i;

  for (i = 0; i < names.length; i++) {
    delete this.locks[names[i]];
  }
};

Dreadnot.prototype.setWarning = function(user, text, callback) {
  var self = this;

  this.queue.push(function(callback) {
    fs.writeFile(path.join(self.config.data_root, 'warning.txt'), text, function(err) {
      if (!err) {
        self.warning = text;
        if (text) {
          log.warnf('warning set to "${text}"', {
            text: text
          });

          self.emitter.emit('warning_set', {'text': text, 'username': user.name});
        } else {
          log.info('warning cleared');

          self.emitter.emit('warning_removed', {'text': text, 'username': user.name});
        }
      }
      callback(err);
    });
  }, callback);
};

Dreadnot.prototype.getStack = function(name, callback) {
  var stack = this._stacks[name];
  if (!stack) {
    callback(new errors.NotFoundError('Stack not found'));
  } else {
    callback(null, stack);
  }
};

Dreadnot.prototype.init = function(callback) {
  var self = this,
      stackNames = Object.keys(this.config.stacks);

  async.series([
    mkdirp.bind(null, self.config.data_root, 493),

    function(callback) {
      fs.readFile(path.join(self.config.data_root, 'warning.txt'), 'utf8', function(err, text) {
        if (err && err.code !== 'ENOENT') {
          callback(err);
        } else {
          self.warning = err ? '' : text.replace(/^\s+|\s+$/g, '');
          if (self.warning) {
            log.warnf('warning set to "${text}"', {
              text: self.warning
            });
          } else {
            log.info('no warning set');
          }
          callback();
        }
      });
    },

    function(callback) {
      async.forEach(stackNames, function(stackName, callback) {
        self._getStack(stackName).init(callback);
      }, callback);
    }
  ], callback);
};

Dreadnot.prototype.getName = function() {
  return this.config.name;
};

Dreadnot.prototype.getSummary = function(callback) {
  callback(null, {name: this.config.env});
};

Dreadnot.prototype.getDetails = function(callback) {
  var self = this,
      stackNames = Object.keys(this.config.stacks);

  async.map(stackNames, function(stackName, callback) {
    self._getStack(stackName).getDetails(callback);
  },

  function(err, summaries) {
    callback(err, {
      name: self.config.env,
      stacks: summaries
    });
  });
};

Dreadnot.prototype.runningStatus = function(callback) {
  var self = this,
      stackNames = Object.keys(this.config.stacks);

  async.map(stackNames, function(stackName, callback) {
    self._getStack(stackName).runningStatus(callback);
  }, callback);
};

exports.Dreadnot = Dreadnot;
<|endoftext|>


<commit_before>'use strict';

var mongoose = require('mongoose'),
    errorHandler = require('./errors.server.controller'),
    _ = require('lodash');

exports.customQuery = function(req, res) {
    var EntityName = mongoose.model(req.body.EntityName[0]),
        projectionArray = req.body.Projection,
        MatchField =  req.body.MatchField,
        aggregateField = {},
        projection = {},
        i, len;

        aggregateField[MatchField] = {$regex: req.body.SearchText, $options: 'i'};

        for(i = 0, len = projectionArray.length; i < len; i += 1) {
            projection[projectionArray[i]] = 1;
        }
        EntityName.aggregate([
            {$match: aggregateField},
            {$match: {group: req.user.group}},
            {$project: projection}
        ],function (err, articles) {
                if (err) {
                    return res.status(400).send({
                        message: errorHandler.getErrorMessage(err)
                    });
                }
                res.json(articles);
        });
};
<commit_msg>#33, autocomplete limits added<commit_after>'use strict';

var mongoose = require('mongoose'),
    errorHandler = require('./errors.server.controller'),
    _ = require('lodash');

exports.customQuery = function(req, res) {
    var EntityName = mongoose.model(req.body.EntityName[0]),
        projectionArray = req.body.Projection,
        MatchField =  req.body.MatchField,
        aggregateField = {},
        projection = {},
        skip = req.body.skip || 0,
        take = req.body.take || 10,
        i, len;

        aggregateField[MatchField] = {$regex: req.body.SearchText, $options: 'i'};

        for(i = 0, len = projectionArray.length; i < len; i += 1) {
            projection[projectionArray[i]] = 1;
        }
        EntityName.aggregate([
            {$match: aggregateField},
            {$match: {group: req.user.group}},
            {$project: projection},
            {$skip : skip },
            {$limit : take },
        ],function (err, articles) {
                if (err) {
                    return res.status(400).send({
                        message: errorHandler.getErrorMessage(err)
                    });
                }
                res.json(articles);
        });
};
<|endoftext|>


<commit_before>/**
 * Created by Priyam on 3/9/16.
 */
$('.form').find('input, textarea').on('keyup blur focus', function (e) {

    var $this = $(this),
        label = $this.prev('label');

    if (e.type === 'keyup') {
        if ($this.val() === '') {
            label.removeClass('active highlight');
        } else {
            label.addClass('active highlight');
        }
    } else if (e.type === 'blur') {
        if( $this.val() === '' ) {
            label.removeClass('active highlight');
        } else {
            label.removeClass('highlight');
        }
    } else if (e.type === 'focus') {

        if( $this.val() === '' ) {
            label.removeClass('highlight');
        }
        else if( $this.val() !== '' ) {
            label.addClass('highlight');
        }
    }

});

$('.tab a').on('click', function (e) {

    e.preventDefault();

    $(this).parent().addClass('active');
    $(this).parent().siblings().removeClass('active');

    target = $(this).attr('href');

    $('.tab-content > div').not(target).hide();

    $(target).fadeIn(600);

});

$( "#signup form" ).submit(function( event ) {

    var data = {};
    data["fname"] = $( "input:first" ).val();
    data["lname"] = $( "#lname" ).val();
    data["email"] = $("#email").val();
    data["pass"] = $("#pass").val();
    var data1 = JSON.stringify(data);
    $.ajax(
        {
            url: base+"data/sign_up_user/",
            data: {abcd:data1},
            type: "POST",
            success: function(data, status)
            {

                alert(data);
            },
            error: function(xhr, desc, err)
            {
                console.log(xhr);
                console.log(desc);
                console.log(err);
            }
        }
    )
});
$( "#login form" ).submit(function( event ) {

    var data = {};

    data["email"] = $("#login-email").val();
    data["pass"] = $("#login-pass").val();
    var data1 = JSON.stringify(data);
    $.ajax(
        {
            url: base+"data/user_login/",
            data: {abcd:data1},
            type: "POST",
            success: function(data, status)
            {
                if(data === "success"){
                    redirect("")
                }
            },
            error: function(xhr, desc, err)
            {
                console.log(xhr);
                console.log(desc);
                console.log(err);
            }
        }
    )
});

<commit_msg>current_value<commit_after>/**
 * Created by Priyam on 3/9/16.
 */
$('.form').find('input, textarea').on('keyup blur focus', function (e) {

    var $this = $(this),
        label = $this.prev('label');

    if (e.type === 'keyup') {
        if ($this.val() === '') {
            label.removeClass('active highlight');
        } else {
            label.addClass('active highlight');
        }
    } else if (e.type === 'blur') {
        if( $this.val() === '' ) {
            label.removeClass('active highlight');
        } else {
            label.removeClass('highlight');
        }
    } else if (e.type === 'focus') {

        if( $this.val() === '' ) {
            label.removeClass('highlight');
        }
        else if( $this.val() !== '' ) {
            label.addClass('highlight');
        }
    }

});

$('.tab a').on('click', function (e) {

    e.preventDefault();

    $(this).parent().addClass('active');
    $(this).parent().siblings().removeClass('active');

    target = $(this).attr('href');

    $('.tab-content > div').not(target).hide();

    $(target).fadeIn(600);

});

$( "#signup form" ).submit(function( event ) {

    var data = {};
    data["fname"] = $( "input:first" ).val();
    data["lname"] = $( "#lname" ).val();
    data["email"] = $("#email").val();
    data["pass"] = $("#pass").val();
    var data1 = JSON.stringify(data);
    //$.ajax(
    //    {
    //        url: base+"data/sign_up_user/",
    //        data: {abcd:data1},
    //        type: "POST",
    //        success: function(data, status)
    //        {
    //
    //            alert(data);
    //        },
    //        error: function(xhr, desc, err)
    //        {
    //            console.log(xhr);
    //            console.log(desc);
    //            console.log(err);
    //        }
    //    }
    //)
    $.post( base+"data/sign_up_user/", { abcd: data1 })
        .done(function( data ) {
            alert( "Data Loaded: " + data );
        });
});
$( "#login form" ).submit(function( event ) {

    var data = {};

    data["email"] = $("#login-email").val();
    data["pass"] = $("#login-pass").val();
    var data1 = JSON.stringify(data);
    $.ajax(
        {
            url: base+"data/user_login/",
            data: {abcd:data1},
            type: "POST",
            success: function(data, status)
            {
                if(data === "success"){
                    redirect("")
                }
            },
            error: function(xhr, desc, err)
            {
                console.log(xhr);
                console.log(desc);
                console.log(err);
            }
        }
    )
});

<|endoftext|>


<commit_before>import Parchment from 'parchment';
import Emitter from '../../../core/emitter';
import Selection, { Range } from '../../../core/selection';
import Cursor from '../../../blots/cursor';
import Scroll from '../../../blots/scroll';

describe('Scroll', function() {
  it('initialize empty document', function() {
    let scroll = this.initialize(Scroll, '');
    expect(scroll.domNode).toEqualHTML('

');
  });

  it('api change', function() {
    let scroll = this.initialize(Scroll, '
Hello World!
');
    spyOn(scroll.emitter, 'emit').and.callThrough();
    scroll.insertAt(5, '!');
    expect(scroll.emitter.emit).toHaveBeenCalledWith(Emitter.events.SCROLL_OPTIMIZE, jasmine.any(Array));
  });

  it('user change', function(done) {
    let scroll = this.initialize(Scroll, '
Hello World!
');
    spyOn(scroll.emitter, 'emit').and.callThrough();
    scroll.domNode.firstChild.appendChild(document.createTextNode('!'));
    setTimeout(function() {
      expect(scroll.emitter.emit).toHaveBeenCalledWith(Emitter.events.SCROLL_OPTIMIZE, jasmine.any(Array));
      expect(scroll.emitter.emit).toHaveBeenCalledWith(Emitter.events.SCROLL_UPDATE, Emitter.sources.USER, jasmine.any(Array));
      done();
    }, 1);
  });

  it('whitelist', function() {
    let scroll = Parchment.create('scroll', { emitter: new Emitter(), whitelist: ['bold'] });
    scroll.insertAt(0, 'Hello World!');
    scroll.formatAt(0, 5, 'bold', true);
    scroll.formatAt(6, 5, 'italic', true);
    expect(scroll.domNode.firstChild).toEqualHTML('Hello World!');
  });

  describe('leaf()', function() {
    it('text', function() {
      let scroll = this.initialize(Scroll, '
Tests
');
      let [leaf, offset] = scroll.leaf(2);
      expect(leaf.value()).toEqual('Tests');
      expect(offset).toEqual(2);
    });

    it('precise', function() {
      let scroll = this.initialize(Scroll, '
0<s>1</s>2<s>3</s>4
');
      let [leaf, offset] = scroll.leaf(3);
      expect(leaf.value()).toEqual('2');
      expect(offset).toEqual(1);
    });

    it('newline', function() {
      let scroll = this.initialize(Scroll, '
0123

5678
');
      let [leaf, offset] = scroll.leaf(4);
      expect(leaf.value()).toEqual('0123');
      expect(offset).toEqual(4);
    });

    it('cursor', function() {
      let selection = this.initialize(Selection, '
012
');
      selection.setRange(new Range(2));
      selection.format('strike', true);
      let [leaf, offset] = selection.scroll.leaf(2);
      expect(leaf instanceof Cursor).toBe(true);
      expect(offset).toEqual(0);
    });

    it('beyond document', function() {
      let scroll = this.initialize(Scroll, '
Test
');
      let [leaf, offset] = scroll.leaf(10);
      expect(leaf).toEqual(null);
      expect(offset).toEqual(-1);
    });
  });
});
<commit_msg>fix tests<commit_after>import Parchment from 'parchment';
import Emitter from '../../../core/emitter';
import Selection, { Range } from '../../../core/selection';
import Cursor from '../../../blots/cursor';
import Scroll from '../../../blots/scroll';

describe('Scroll', function() {
  it('initialize empty document', function() {
    let scroll = this.initialize(Scroll, '');
    expect(scroll.domNode).toEqualHTML('

');
  });

  it('api change', function() {
    let scroll = this.initialize(Scroll, '
Hello World!
');
    spyOn(scroll.emitter, 'emit').and.callThrough();
    scroll.insertAt(5, '!');
    expect(scroll.emitter.emit).toHaveBeenCalledWith(Emitter.events.SCROLL_OPTIMIZE, jasmine.any(Array), jasmine.any(Object));
  });

  it('user change', function(done) {
    let scroll = this.initialize(Scroll, '
Hello World!
');
    spyOn(scroll.emitter, 'emit').and.callThrough();
    scroll.domNode.firstChild.appendChild(document.createTextNode('!'));
    setTimeout(function() {
      expect(scroll.emitter.emit).toHaveBeenCalledWith(Emitter.events.SCROLL_OPTIMIZE, jasmine.any(Array), jasmine.any(Object));
      expect(scroll.emitter.emit).toHaveBeenCalledWith(Emitter.events.SCROLL_UPDATE, Emitter.sources.USER, jasmine.any(Array));
      done();
    }, 1);
  });

  it('whitelist', function() {
    let scroll = Parchment.create('scroll', { emitter: new Emitter(), whitelist: ['bold'] });
    scroll.insertAt(0, 'Hello World!');
    scroll.formatAt(0, 5, 'bold', true);
    scroll.formatAt(6, 5, 'italic', true);
    expect(scroll.domNode.firstChild).toEqualHTML('Hello World!');
  });

  describe('leaf()', function() {
    it('text', function() {
      let scroll = this.initialize(Scroll, '
Tests
');
      let [leaf, offset] = scroll.leaf(2);
      expect(leaf.value()).toEqual('Tests');
      expect(offset).toEqual(2);
    });

    it('precise', function() {
      let scroll = this.initialize(Scroll, '
0<s>1</s>2<s>3</s>4
');
      let [leaf, offset] = scroll.leaf(3);
      expect(leaf.value()).toEqual('2');
      expect(offset).toEqual(1);
    });

    it('newline', function() {
      let scroll = this.initialize(Scroll, '
0123

5678
');
      let [leaf, offset] = scroll.leaf(4);
      expect(leaf.value()).toEqual('0123');
      expect(offset).toEqual(4);
    });

    it('cursor', function() {
      let selection = this.initialize(Selection, '
012
');
      selection.setRange(new Range(2));
      selection.format('strike', true);
      let [leaf, offset] = selection.scroll.leaf(2);
      expect(leaf instanceof Cursor).toBe(true);
      expect(offset).toEqual(0);
    });

    it('beyond document', function() {
      let scroll = this.initialize(Scroll, '
Test
');
      let [leaf, offset] = scroll.leaf(10);
      expect(leaf).toEqual(null);
      expect(offset).toEqual(-1);
    });
  });
});
<|endoftext|>


<commit_before>var my_accountws = (function(){

    "use strict";
    var currType, isPaymentAgent;

    var init = function(){
        $("#welcome").hide();
      $("#VRT_topup_link").hide();
      $("#authenticate_button").hide();
      $("#welcome_text").hide();
      BinarySocket.send({"balance": 1, "req_id": 1 });
    };

    var getBalance = function(response){
      var str , bal ;
      if(response.echo_req.req_id){
        if("error" in response) {
              if("message" in response.error) {
                  console.log(response.error.message);
              }
              return false;
          }
        else{
          currType = response.balance.currency;
          bal =  response.balance.balance;
          var isReal = !(/VRT/.test($.cookie('loginid')));
          if(parseInt(response.req_id,10) === 1){
            if(!isReal){
                str = "You're currently logged in to your virtual money account ";
                $("#welcome").show();
                $("#welcome").text(text.localize("Welcome!"));
                $("#welcome_text").show();
                $("#welcome_text .clientid").text("("+ $.cookie('loginid') +").");
                $("#welcome_text").html(text.localize(str)+$("#welcome_text").html());
                $("#cashier-portfolio").removeClass('invisible');
                      $("#profit-statement").removeClass('invisible');
                      if(bal<1000){
                    str = "Deposit %1 virtual money into your account ";
                    $("#VRT_topup_link").show();
                    $("#VRT_topup_link a").text(text.localize(str).replace("%1",currType + " 10000 "));
                }
                BinarySocket.send({"get_settings": 1, "req_id":3});
            }
            else{
               BinarySocket.send({"get_settings": 1, "req_id":4});
            }
            BinarySocket.send({"get_account_status": 1, "req_id":2});
          }

        }
      }

    };

    var showAuthenticate = function(response){
        var status;
        if("error" in response){
            if("message" in response.error) {
              console.log(response.error.message);
          }
            return false;
        }
        else{
            status = response.get_account_status[0];
            if(status === "unwelcome"){
                $("#authenticate_button").show();
                $("#authenticate_button").removeClass("invisible");
                $("#authenticate_button span").text(text.localize("Authenticate your account"));
            }
        }
    };

    var getLandingCompany = function(response){
        var country_code;
        if("error" in response){
            if("message" in response.error) {
              console.log(response.error.message);
          }
            return false;
        }
        else{
            country_code = response.get_settings.country_code;
            BinarySocket.send({"landing_company": country_code, "req_id":4});
        }
    };

    var showWelcomeText = function(response){
        var landing_company, str;
        if("error" in response){
            if("message" in response.error) {
              console.log(response.error.message);
          }
            return false;
        }
        else{
            if(/MLT/.test($.cookie('loginid'))){
                landing_company = response.landing_company.gaming_company.name;
            }
            else{
                landing_company = response.landing_company.financial_company.name;
            }
            str = "You're currently logged in to your real money account with %1 ";
            $("#welcome").show();
            $("#welcome").text(text.localize("Welcome!"));
            $("#welcome_text").show();
            $("#welcome_text .clientid").text(" ("+ $.cookie('loginid') +").");
            $("#welcome_text").html(text.localize(str).replace("%1", landing_company) + $("#welcome_text").html());
            $("#cashier-portfolio").removeClass('invisible');
            $("#profit-statement").removeClass('invisible');
            if(isPaymentAgent)
                $("#payment_agent").removeClass('invisible');
            showNoticeMsg();
        }
    };

    var showNoticeMsg = function(){
        var loginid_list = $.cookie('loginid_list');
        var res = loginid_list.split("+");
        if(res.length == "2" &&(/MLT/.test(res[0]) || /MLT/.test(res[1]))){
            $("#investment_message").removeClass("invisible");
        }
    };

    var addGTMDataLayer = function(response){
        if("error" in response){
            if("message" in response.error) {
              console.log(response.error.message);
          }
            return false;
        }
        else{
            if(page.url.param('login') || page.url.param('newaccounttype')){
                var oldUrl = window.location.href;
                var newUrl = oldUrl.replace(/(login=true&|newaccounttype=real&|newaccounttype=virtual&)/gi, "");
                var title = document.title;
                var age = parseInt((moment(str).unix()-response.get_settings.date_of_birth)/31557600);
                var name = TUser.get().fullname.split(' ');
                var data = {};
                var affiliateToken = $.cookie('affiliate_tracking');
                if (affiliateToken) {
                    dataLayer.push({'bom_affiliate_token': affiliateToken});
                }
                data['bom_country'] = response.get_settings.country;
                data['bom_email'] = TUser.get().email;
                data['language'] = page.url.param("l");
                data['pageTitle'] = title;
                data['url'] = oldUrl;
                data['visitorID'] = TUser.get().loginid;
                data['bom_today'] = Math.floor(Date.now() / 1000);

                if(response.req_id === 4){
                    data['bom_age'] = age;
                    data['bom_firstname'] = name[1];
                    data['bom_lastname'] = name[2];
                    data['bom_phone'] = response.get_settings.phone;
                }

                if(page.url.param('newaccounttype'))
                    data['event'] = 'new_account';
                else
                    data['event'] = 'log_in';

                dataLayer.push(data);
                window.history.replaceState("My Account", title, newUrl);
            }
        }
    };

    var checkPaymentAgent = function(response){
        if("error" in response){
            if("message" in response.error) {
              console.log(response.error.message);
          }
            return false;
        }
        else{
            isPaymentAgent = response.get_settings.is_authenticated_payment_agent;
        }
    };

    var apiResponse = function(response){
      var type = response.msg_type;
      if(type === "balance" || (type === "error" && "balance" in response.echo_req))
        {
            getBalance(response);
        }
        if(type === "get_account_status" || (type === "error" && "get_account_status" in response.echo_req)){
            showAuthenticate(response);
        }
        if(type === "get_settings" && response.req_id === 3 || (type === "error" && "get_settings" in response.echo_req)){
            addGTMDataLayer(response);
        }
        if(type === "get_settings" && response.req_id === 4 || (type === "error" && "get_settings" in response.echo_req)){
            getLandingCompany(response);
            checkPaymentAgent(response);
            addGTMDataLayer(response);
        }
        if(type === "landing_company" || (type === "error" && "landing_company" in response.echo_req)){
            showWelcomeText(response);
        }
    };

    var checkDisabledAccount = function(){
        var divOne = text.localize('
Your %1 account is unavailable. For any questions please contact Customer Support.
').replace('%2', page.url.url_for('contact')),
            divTwo = text.localize('
Your %1 accounts are unavailable. For any questions please contact Customer Support.
').replace('%2', page.url.url_for('contact'));
        var loginidArry = page.user.loginid_array,
            disabledAccount = [];
        for (var i = 0; i < loginidArry.length; i++) {
            if (loginidArry[i].disabled === true && loginidArry[i].real === true) {
                disabledAccount.push(loginidArry[i].id);
            }
        }
        if (disabledAccount.length === 1) {
            $(divOne.replace('%1', disabledAccount.toString())).insertAfter('.clientid');
        } else if (disabledAccount.length > 1) {
            $(divTwo.replace('%1', disabledAccount.join(', '))).insertAfter('.clientid');
        }
    };

    return {
      init : init,
      checkDisabledAccount : checkDisabledAccount,
      apiResponse : apiResponse

    };

})();

pjax_config_page("user/my_accountws", function() {
    return {
        onLoad: function() {
          if (!getCookieItem('login')) {
                window.location.href = page.url.url_for('login');
                return;
            }
          BinarySocket.init({
                onmessage: function(msg){
                    var response = JSON.parse(msg.data);
                    if (response) {
                        my_accountws.apiResponse(response);

                    }
                }
            });
            Content.populate();
            my_accountws.init();
            my_accountws.checkDisabledAccount();
        }
    };
});
<commit_msg>Create required cookies in front-end<commit_after>var my_accountws = (function(){

    "use strict";
    var currType, isPaymentAgent;

    var init = function(){
      $("#welcome").hide();
      $("#VRT_topup_link").hide();
      $("#authenticate_button").hide();
      $("#welcome_text").hide();
      BinarySocket.send({"balance": 1, "req_id": 1 });
      BinarySocket.send({"payout_currencies": 1});
    };

    var getBalance = function(response){
      var str, bal;
      if(response.echo_req.req_id) {
        if("error" in response) {
            if("message" in response.error) {
                console.log(response.error.message);
            }
            return false;
        }
        else {
          currType = response.balance.currency;
          bal = response.balance.balance;
          var isReal = !(/VRT/.test($.cookie('loginid')));
          if(parseInt(response.req_id,10) === 1){
            if(!isReal){
                str = "You're currently logged in to your virtual money account ";
                $("#welcome").show();
                $("#welcome").text(text.localize("Welcome!"));
                $("#welcome_text").show();
                $("#welcome_text .clientid").text("("+ $.cookie('loginid') +").");
                $("#welcome_text").html(text.localize(str)+$("#welcome_text").html());
                $("#cashier-portfolio").removeClass('invisible');
                $("#profit-statement").removeClass('invisible');
                if(bal<1000){
                    str = "Deposit %1 virtual money into your account ";
                    $("#VRT_topup_link").show();
                    $("#VRT_topup_link a").text(text.localize(str).replace("%1",currType + " 10000 "));
                }
                BinarySocket.send({"get_settings": 1, "req_id":3});
            }
            else{
               BinarySocket.send({"get_settings": 1, "req_id":4});
            }
            BinarySocket.send({"get_account_status": 1, "req_id":2});
          }
        }
      }
    };

    var showAuthenticate = function(response){
        var status;
        if("error" in response){
            if("message" in response.error) {
              console.log(response.error.message);
            }
            return false;
        }
        else{
            status = response.get_account_status[0];
            if(status === "unwelcome"){
                $("#authenticate_button").show();
                $("#authenticate_button").removeClass("invisible");
                $("#authenticate_button span").text(text.localize("Authenticate your account"));
            }
        }
    };

    var getLandingCompany = function(response){
        var country_code;
        if("error" in response){
            if("message" in response.error) {
              console.log(response.error.message);
          }
            return false;
        }
        else{
            country_code = response.get_settings.country_code;
            BinarySocket.send({"landing_company": country_code, "req_id":4});
        }
    };

    var showWelcomeText = function(response){
        var landing_company, str;
        if("error" in response){
            if("message" in response.error) {
              console.log(response.error.message);
          }
            return false;
        }
        else{
            var allowed_markets = [];
            if(response.landing_company.hasOwnProperty('gaming_company')){
                landing_company = response.landing_company.gaming_company.name;
                allowed_markets = response.landing_company.gaming_company.legal_allowed_markets;
            }
            else{
                landing_company = response.landing_company.financial_company.name;
                allowed_markets = response.landing_company.financial_company.legal_allowed_markets;
            }
            if(allowed_markets.length > 0) {
                setCookie('allowed_markets', allowed_markets.join(','));
            }

            str = "You're currently logged in to your real money account with %1 ";
            $("#welcome").show();
            $("#welcome").text(text.localize("Welcome!"));
            $("#welcome_text").show();
            $("#welcome_text .clientid").text(" ("+ $.cookie('loginid') +").");
            $("#welcome_text").html(text.localize(str).replace("%1", landing_company) + $("#welcome_text").html());
            $("#cashier-portfolio").removeClass('invisible');
            $("#profit-statement").removeClass('invisible');
            if(isPaymentAgent) {
                $("#payment_agent").removeClass('invisible');
            }
            showNoticeMsg();
        }
    };

    var showNoticeMsg = function(){
        var loginid_list = $.cookie('loginid_list');
        var res = loginid_list.split("+");
        if(res.length == "2" &&(/MLT/.test(res[0]) || /MLT/.test(res[1]))){
            $("#investment_message").removeClass("invisible");
        }
    };

    var addGTMDataLayer = function(response){
        if("error" in response){
            if("message" in response.error) {
              console.log(response.error.message);
          }
            return false;
        }
        else{
            if(page.url.param('login') || page.url.param('newaccounttype')){
                var oldUrl = window.location.href;
                var newUrl = oldUrl.replace(/(login=true&|newaccounttype=real&|newaccounttype=virtual&)/gi, "");
                var title = document.title;
                var age = parseInt((moment(str).unix()-response.get_settings.date_of_birth)/31557600);
                var name = TUser.get().fullname.split(' ');
                var data = {};
                var affiliateToken = $.cookie('affiliate_tracking');
                if (affiliateToken) {
                    dataLayer.push({'bom_affiliate_token': affiliateToken});
                }
                data['bom_country'] = response.get_settings.country;
                data['bom_email'] = TUser.get().email;
                data['language'] = page.url.param("l");
                data['pageTitle'] = title;
                data['url'] = oldUrl;
                data['visitorID'] = TUser.get().loginid;
                data['bom_today'] = Math.floor(Date.now() / 1000);

                if(response.req_id === 4){
                    data['bom_age'] = age;
                    data['bom_firstname'] = name[1];
                    data['bom_lastname'] = name[2];
                    data['bom_phone'] = response.get_settings.phone;
                }

                if(page.url.param('newaccounttype'))
                    data['event'] = 'new_account';
                else
                    data['event'] = 'log_in';

                dataLayer.push(data);
                window.history.replaceState("My Account", title, newUrl);
            }
        }
    };

    var checkPaymentAgent = function(response){
        if("error" in response){
            if("message" in response.error) {
              console.log(response.error.message);
          }
            return false;
        }
        else{
            isPaymentAgent = response.get_settings.is_authenticated_payment_agent;
        }
    };

    var apiResponse = function(response){
        var type = response.msg_type;
        if(type === "balance" || (type === "error" && "balance" in response.echo_req)) {
            getBalance(response);
        }
        else if(type === "get_account_status" || (type === "error" && "get_account_status" in response.echo_req)){
            showAuthenticate(response);
        }
        else if(type === "get_settings" || (type === "error" && "get_settings" in response.echo_req)){
            if(response.req_id === 4) {
                checkPaymentAgent(response);
            }
            getLandingCompany(response);
            addGTMDataLayer(response);
        }
        else if(type === "landing_company" || (type === "error" && "landing_company" in response.echo_req)){
            showWelcomeText(response);
        }
        else if(type === "payout_currencies" || (type === "error" && "payout_currencies" in response.echo_req)){
            getPayoutCurrencies(response);
        }
    };

    var checkDisabledAccount = function(){
        var divOne = text.localize('
Your %1 account is unavailable. For any questions please contact Customer Support.
').replace('%2', page.url.url_for('contact')),
            divTwo = text.localize('
Your %1 accounts are unavailable. For any questions please contact Customer Support.
').replace('%2', page.url.url_for('contact'));
        var loginidArry = page.user.loginid_array,
            disabledAccount = [];
        for (var i = 0; i < loginidArry.length; i++) {
            if (loginidArry[i].disabled === true && loginidArry[i].real === true) {
                disabledAccount.push(loginidArry[i].id);
            }
        }
        if (disabledAccount.length === 1) {
            $(divOne.replace('%1', disabledAccount.toString())).insertAfter('.clientid');
        } else if (disabledAccount.length > 1) {
            $(divTwo.replace('%1', disabledAccount.join(', '))).insertAfter('.clientid');
        }
    };

    var getPayoutCurrencies = function (response) {
        if(response.hasOwnProperty('error')) {
            return;
        }

        var currencies = {'client.currencies': response.payout_currencies};
        setCookie('settings', JSON.stringify(currencies));
    };

    var setCookie = function (name, value) {
        $.cookie(name, value, {
            expires : new Date('Thu, 1 Jan 2037 12:00:00 GMT'),
            path    : '/',
            domain  : '.' + document.domain.split('.').slice(-2).join('.')
        });
    };

    return {
      init : init,
      checkDisabledAccount : checkDisabledAccount,
      apiResponse : apiResponse
    };
})();

pjax_config_page("user/my_accountws", function() {
    return {
        onLoad: function() {
            if (!getCookieItem('login')) {
                window.location.href = page.url.url_for('login');
                return;
            }
            BinarySocket.init({
                onmessage: function(msg){
                    var response = JSON.parse(msg.data);
                    if (response) {
                        my_accountws.apiResponse(response);

                    }
                }
            });
            Content.populate();
            my_accountws.init();
            my_accountws.checkDisabledAccount();
        }
    };
});
<|endoftext|>


<commit_before>module.exports = function(options) {
  return function(deck) {
    options = options || {};

    var control = options.control || local;
    var port = options.port || 9999;
    var url = options.url || (location.protocol === 'https' ? 'wss' : 'ws')
      + '://' + (location.hostname || 'localhost');

    var path = options.path ? options.path : '';
    url += ':' + port + '/' + path;

    function local(origin) {
      var parse = document.createElement('a');
      parse.href = origin;
      var hostname = parse.hostname;
      return {
        local: hostname === 'localhost' || hostname === '127.0.0.1'
      }
    }

    var socket = new WebSocket(url);

    var unhitch = options.unhitch || 81;
    var unhitched = false;

    function synch() {
      var synchronizing = synch.ronizing;
      synch.ronizing = false;
      return synchronizing;
    }

    document.addEventListener('keydown', function(e) {
      if (e.which === unhitch) {
        unhitched = !unhitched;
      }
    });

    deck.on('activate', function (e) {
      if (socket.readyState !== 1) {return;}
      if (synch()) {return;}
      if (!control(url, socket).local) {return;}
      socket.send(e.index);
    });

    socket.onmessage = function (e) {
      if (unhitched) {return;}
      synch.ronizing = true;
      deck.slide(+e.data);
    };
  };
};
<commit_msg>fix ssl check<commit_after>module.exports = function(options) {
  return function(deck) {
    options = options || {};

    var control = options.control || local;
    var port = options.port || 9999;
    var url = options.url || (/https/.test(location.protocol) ? 'wss' : 'ws')
      + '://' + (location.hostname || 'localhost');

    var path = options.path ? options.path : '';
    url += ':' + port + '/' + path;

    function local(origin) {
      var parse = document.createElement('a');
      parse.href = origin;
      var hostname = parse.hostname;
      return {
        local: hostname === 'localhost' || hostname === '127.0.0.1'
      }
    }

    var socket = new WebSocket(url);

    var unhitch = options.unhitch || 81;
    var unhitched = false;

    function synch() {
      var synchronizing = synch.ronizing;
      synch.ronizing = false;
      return synchronizing;
    }

    document.addEventListener('keydown', function(e) {
      if (e.which === unhitch) {
        unhitched = !unhitched;
      }
    });

    deck.on('activate', function (e) {
      if (socket.readyState !== 1) {return;}
      if (synch()) {return;}
      if (!control(url, socket).local) {return;}
      socket.send(e.index);
    });

    socket.onmessage = function (e) {
      if (unhitched) {return;}
      synch.ronizing = true;
      deck.slide(+e.data);
    };
  };
};
<|endoftext|>


<commit_before>var refParser = require('./parse-references');
var webidlExtractor = require('./extract-webidl');
var loadSpecification = require('./util').loadSpecification;
var webidlParser = require('./parse-webidl');
var fetch = require('node-fetch');
var fs = require('fs');

/**
 * Extracts the title of the loaded document
 */
function titleExtractor(window) {
    return window.document.querySelector("title").textContent;
}

/**
 * Return the given URL along with the W3C shortname for that specification
 *
 * @function
 * @private
 * @param {String} url The URL to enrich
 * @return {{url: String, shortname: String} The beginning of a spec description
 *   structure that contains the URL along with the shortname, when possible
 */
function getShortname(url) {
    var res = { url };
    if (!url.match(/www.w3.org\/TR\//)) {
        return res;
    }
    if (url.match(/TR\/[0-9]+\//)) {
        // dated version
        var statusShortname = url.split('/')[5];
        res.shortname = statusShortname.split('-').slice(1, -1).join('-');
        return res;
    }
    // latest version
    res.shortname = url.split('/')[4];
    return res;
}

/**
 * Enrich the spec description with the URL of the latest editor's draft,
 * and with the title of the specification, provided that the specification
 * is a W3C spec.
 *
 * @function
 * @param {Object} spec Spec description structure (only the URL is useful)
 * @return {Objec} The same structure, enriched with the URL of the latest
 *   draft when one is found
 */
function getSpecFromW3CApi(spec) {
    var shortname = spec.shortname;
    var config = require('./config.json');
    var authParam = '?apikey=' + config.w3cApiKey;
    if (!shortname) {
        return spec;
    }
    var bogusEditorDraft = ['webmessaging', 'eventsource', 'webstorage', 'progress-events'];
    var unparseableEditorDraft = ['image-capture', 'requestidlecallback', 'performance-timeline-2'];
    if ((bogusEditorDraft.indexOf(shortname) !== -1)
        || (unparseableEditorDraft.indexOf(shortname) !== -1)) {
        spec.latest = 'http://www.w3.org/TR/' + shortname;
        return spec;
    }
    return fetch('https://api.w3.org/specifications/' + shortname + authParam)
        .then(r =>  r.json())
        .then(s => fetch(s._links['latest-version'].href + authParam))
        .then(r => r.json())
        .then(s => {
            spec.latest = (s['editor-draft'] ? s['editor-draft'] : s.uri);
            return spec;
        })
        .catch(e => {
            spec.latest = 'http://www.w3.org/TR/' + shortname;
            return spec;
        });
}

/**
 * Given a list of URLs, create a list of specification descriptions
 *
 * The description will include the URL of the spec, its shortname if possible,
 * the URL of the latest version, and the title of the spec for W3C specs
 *
 * @function
 * @param {Array(String)} list The list of specification URLs
 * @return {Promise<Array(Object)} The promise to get a list of spec
 *  descriptions.
 */
function createInitialSpecDescriptions(list) {
    return Promise.all(list.map(getShortname).map(getSpecFromW3CApi));
}

/**
 * Main method that crawls the list of specification URLs and return a structure
 * that full describes its title, URLs, references, and IDL definitions.
 *
 * @function
 * @param {Array(String)} speclist List of URLs to parse
 * @return {Promise<Array(Object)} The promise to get an array of complete
 *   specification descriptions
 */
function crawlList(speclist) {
    function getRefAndIdl(spec) {
        var url = spec.latest ? spec.latest : spec.url;
        return loadSpecification(url).then(
            dom => Promise.all([
                spec,
                titleExtractor(dom),
                refParser.extract(dom).catch(err => err),
                webidlExtractor.extract(dom).then(idl => webidlParser.parse(idl)).catch(err => err),
                dom
                    ]))
            .then(res => {
                res[4].close();
                var spec = res[0];
                spec.title = spec.title ? spec.title : res[1];
                spec.refs = res[2];
                spec.idl = res[3];
                return spec;
            });
    }

    return createInitialSpecDescriptions(speclist)
        .then(list => Promise.all(list.map(getRefAndIdl)));
}

/**
 * Append the resulting data to the given file
 *
 * @function
 * @param {Array(Object)} data The list of specification structures to save
 * @param {String} path The path to the file to save
 * @return {Promise<void>} The promise to have saved the data
 */
function saveResults(data, path) {
    return new Promise((resolve, reject) => {
        fs.readFile(path, function(err, content) {
            if (err) return reject(err);
            var existingdata = [];
            try {
                existingdata = JSON.parse(content);
            } catch (e) {}
            var newdata = existingdata.concat(data);
            fs.writeFile(path, JSON.stringify(newdata, null, 2),
                         err => { if (err) return reject(err); resolve();});
        });
    });
}

/**
 * Processes a chunk of the initial list and move on the next chunk afterwards
 *
 * Note that we can probably drop this processing now that memory issues have
 * been solved.
 *
 * @function
 * @private
 */
function processChunk(list, remain, resultsPath, chunkSize) {
    return crawlList(list)
        .then(data => saveResults(data, resultsPath))
        .then(() => {
            if (remain.length) {
                return processChunk(remain.splice(0, chunkSize), remain, resultsPath, chunkSize);
            }
        });
}

/**************************************************
Export the crawlList method for use as module
**************************************************/
module.exports.crawlList = crawlList;

/**************************************************
Code run if the code is run as a stand-alone module
**************************************************/
if (require.main === module) {
    var speclistPath = process.argv[2];
    var resultsPath = process.argv[3];
    if (!speclistPath || !resultsPath) {
        console.error("Required filename parameter missing");
        process.exit(2);
    }
    var speclist;
    try {
        speclist = require(speclistPath);
    } catch(e) {
        console.error("Impossible to read " + speclistPath + ": " + e);
        process.exit(3);
    }
    try {
        fs.writeFileSync(resultsPath, "");
    } catch (e) {
        console.error("Impossible to write to " + resultsPath + ": " + e);
        process.exit(3);
    }
    // splitting list to avoid memory exhaustion
    var chunkSize = 80;
    var sublist = speclist.splice(0, chunkSize);
    processChunk(sublist, speclist, resultsPath, chunkSize)
        .then(function (data) {
            console.log("Finished");
        })
        .catch(function (err) {
            console.error(err);
            process.exit(64);
        });
}
<commit_msg>Trim crawled title to avoid carriage return characters<commit_after>var refParser = require('./parse-references');
var webidlExtractor = require('./extract-webidl');
var loadSpecification = require('./util').loadSpecification;
var webidlParser = require('./parse-webidl');
var fetch = require('node-fetch');
var fs = require('fs');

/**
 * Extracts the title of the loaded document
 */
function titleExtractor(window) {
    return window.document.querySelector("title").textContent.trim();
}

/**
 * Return the given URL along with the W3C shortname for that specification
 *
 * @function
 * @private
 * @param {String} url The URL to enrich
 * @return {{url: String, shortname: String} The beginning of a spec description
 *   structure that contains the URL along with the shortname, when possible
 */
function getShortname(url) {
    var res = { url };
    if (!url.match(/www.w3.org\/TR\//)) {
        return res;
    }
    if (url.match(/TR\/[0-9]+\//)) {
        // dated version
        var statusShortname = url.split('/')[5];
        res.shortname = statusShortname.split('-').slice(1, -1).join('-');
        return res;
    }
    // latest version
    res.shortname = url.split('/')[4];
    return res;
}

/**
 * Enrich the spec description with the URL of the latest editor's draft,
 * and with the title of the specification, provided that the specification
 * is a W3C spec.
 *
 * @function
 * @param {Object} spec Spec description structure (only the URL is useful)
 * @return {Objec} The same structure, enriched with the URL of the latest
 *   draft when one is found
 */
function getSpecFromW3CApi(spec) {
    var shortname = spec.shortname;
    var config = require('./config.json');
    var authParam = '?apikey=' + config.w3cApiKey;
    if (!shortname) {
        return spec;
    }
    var bogusEditorDraft = ['webmessaging', 'eventsource', 'webstorage', 'progress-events'];
    var unparseableEditorDraft = ['image-capture', 'requestidlecallback', 'performance-timeline-2'];
    if ((bogusEditorDraft.indexOf(shortname) !== -1)
        || (unparseableEditorDraft.indexOf(shortname) !== -1)) {
        spec.latest = 'http://www.w3.org/TR/' + shortname;
        return spec;
    }
    return fetch('https://api.w3.org/specifications/' + shortname + authParam)
        .then(r =>  r.json())
        .then(s => fetch(s._links['latest-version'].href + authParam))
        .then(r => r.json())
        .then(s => {
            spec.latest = (s['editor-draft'] ? s['editor-draft'] : s.uri);
            return spec;
        })
        .catch(e => {
            spec.latest = 'http://www.w3.org/TR/' + shortname;
            return spec;
        });
}

/**
 * Given a list of URLs, create a list of specification descriptions
 *
 * The description will include the URL of the spec, its shortname if possible,
 * the URL of the latest version, and the title of the spec for W3C specs
 *
 * @function
 * @param {Array(String)} list The list of specification URLs
 * @return {Promise<Array(Object)} The promise to get a list of spec
 *  descriptions.
 */
function createInitialSpecDescriptions(list) {
    return Promise.all(list.map(getShortname).map(getSpecFromW3CApi));
}

/**
 * Main method that crawls the list of specification URLs and return a structure
 * that full describes its title, URLs, references, and IDL definitions.
 *
 * @function
 * @param {Array(String)} speclist List of URLs to parse
 * @return {Promise<Array(Object)} The promise to get an array of complete
 *   specification descriptions
 */
function crawlList(speclist) {
    function getRefAndIdl(spec) {
        var url = spec.latest ? spec.latest : spec.url;
        return loadSpecification(url).then(
            dom => Promise.all([
                spec,
                titleExtractor(dom),
                refParser.extract(dom).catch(err => err),
                webidlExtractor.extract(dom).then(idl => webidlParser.parse(idl)).catch(err => err),
                dom
                    ]))
            .then(res => {
                res[4].close();
                var spec = res[0];
                spec.title = spec.title ? spec.title : res[1];
                spec.refs = res[2];
                spec.idl = res[3];
                return spec;
            });
    }

    return createInitialSpecDescriptions(speclist)
        .then(list => Promise.all(list.map(getRefAndIdl)));
}

/**
 * Append the resulting data to the given file
 *
 * @function
 * @param {Array(Object)} data The list of specification structures to save
 * @param {String} path The path to the file to save
 * @return {Promise<void>} The promise to have saved the data
 */
function saveResults(data, path) {
    return new Promise((resolve, reject) => {
        fs.readFile(path, function(err, content) {
            if (err) return reject(err);
            var existingdata = [];
            try {
                existingdata = JSON.parse(content);
            } catch (e) {}
            var newdata = existingdata.concat(data);
            fs.writeFile(path, JSON.stringify(newdata, null, 2),
                         err => { if (err) return reject(err); resolve();});
        });
    });
}

/**
 * Processes a chunk of the initial list and move on the next chunk afterwards
 *
 * Note that we can probably drop this processing now that memory issues have
 * been solved.
 *
 * @function
 * @private
 */
function processChunk(list, remain, resultsPath, chunkSize) {
    return crawlList(list)
        .then(data => saveResults(data, resultsPath))
        .then(() => {
            if (remain.length) {
                return processChunk(remain.splice(0, chunkSize), remain, resultsPath, chunkSize);
            }
        });
}

/**************************************************
Export the crawlList method for use as module
**************************************************/
module.exports.crawlList = crawlList;

/**************************************************
Code run if the code is run as a stand-alone module
**************************************************/
if (require.main === module) {
    var speclistPath = process.argv[2];
    var resultsPath = process.argv[3];
    if (!speclistPath || !resultsPath) {
        console.error("Required filename parameter missing");
        process.exit(2);
    }
    var speclist;
    try {
        speclist = require(speclistPath);
    } catch(e) {
        console.error("Impossible to read " + speclistPath + ": " + e);
        process.exit(3);
    }
    try {
        fs.writeFileSync(resultsPath, "");
    } catch (e) {
        console.error("Impossible to write to " + resultsPath + ": " + e);
        process.exit(3);
    }
    // splitting list to avoid memory exhaustion
    var chunkSize = 80;
    var sublist = speclist.splice(0, chunkSize);
    processChunk(sublist, speclist, resultsPath, chunkSize)
        .then(function (data) {
            console.log("Finished");
        })
        .catch(function (err) {
            console.error(err);
            process.exit(64);
        });
}
<|endoftext|>


<commit_before>function Momentify(){
    var elements = document.getElementsByClassName("timestamp");
    for(var i=0; i < elements.length; i++){
        elements[i].innerHTML = moment(new Date(elements[i].innerHTML)).fromNow();
    }
}

$(document).ready(
    function(){
        Momentify();
    }
);<commit_msg>fixing fanciness<commit_after>function Momentify(){
    var elements = document.getElementsByClassName("timestamp");
    for(var i=0; i < elements.length; i++){
        console.log('Changing element containing '+elements[i].innerHTML);
        elements[i].innerHTML = moment(new Date(elements[i].innerHTML)).fromNow();
    }
}

$(document).ready(
    function(){
        Momentify();
    }
);<|endoftext|>