<commit_before>/* ========================================================================
* Warioware: script.js v0.1
* https://github.com/afahim/warioware/
* ========================================================================
* Copyright 2014 Techbridgeworld, Inc.
* Developed for 15-239 (http://www.cs.cmu.edu/~./239/about/)
* ======================================================================== */

/* Variable Names */
var nGames, fenceContainer;

/* Function Names */
var invertWidthHeight, setupGameplayHandlers, nextGame, startGame1,
  askQuestion, startGame2;

$(document).ready(function () {
  nGames = document.getElementById("all-games").children.length;
  fenceContainer = document.getElementById('fence-container');

  invertWidthHeight();
  setupGameplayHandlers();
});

// Fitting transition overlay on multiple screen sizes
// ===================================================
function invertWidthHeight() {
  $("#right-card").height($(window).width());
  $("#right-card").width($(window).height());

  $("#left-card").height($(window).width());
  $("#left-card").width($(window).height());
}

// Fitting to screen in case of screen resize
// ===================================================
$(window).resize(function () {
  invertWidthHeight();
});

// Handles setting up of and timing between game transitions
// =========================================================
function setupGameplayHandlers() {
  var card = document.getElementById('bottom-card');

  /* Hadler for finishing of a transition animation */
  fenceContainer.addEventListener("webkitAnimationEnd", function (e) {
    if (e.animationName === "pan-in") {
      $("#fence-container").css('visibility', 'hidden');
    } else if (e.animationName === "knock-over") {
      fenceContainer.className = "lateral-move";
      nextGame();
    } else if (e.animationName === "pan-out") {
      $(".door-holder").removeClass("not-slided");
      $(".door-holder").addClass("slided");
    } else if (e.animationName === "slidein-left-door") {
      $(".door-holder").removeClass("slided");
      $(".door-holder").addClass("not-slided");
      nextGame();
    } else if (e.animationName === "slideout-left-door") {
      fenceContainer.className = "lateral-move";
    }
  }, false);

  /* Triggering flip over animation for start screen */
  document.getElementById('bottom-card').addEventListener('click', function () {
    card.className = card.className + " flipped";
  }, false);
}

// Called by a mini-gme once a game has terminated
// ===============================================
function gameFinished() {
  $("#fence-container").css('visibility', '');
  fenceContainer.className = "lateral-back";
}

// Randomly selecting and displaying a minigame to the user
// ========================================================
function nextGame() {
  var gameIndex = Math.floor(Math.random() * nGames);
  $("#game-instance").html($("#game" + gameIndex).html());

  /* #ToDo: Remove hardcoded start game func and use game objs instead*/
  if (gameIndex === 0) {
    startGame1();
  } else if (gameIndex === 1) {
    askQuestion();
  } else if (gameIndex === 2) {
    startGame2();
  }
}<commit_msg>removed extra min folder<commit_after><|endoftext|>


<commit_before>'use strict';

var mongoose = require('mongoose');

module.exports = mongoose.model('Accounts', {
  url: {
    type: String,
    required: true
  },
  token: String,
  repositories: [String]
});<commit_msg>Removed condition of requirement for URL<commit_after>'use strict';

var mongoose = require('mongoose');

module.exports = mongoose.model('Accounts', {
  url: String,
  token: String,
  repositories: [String]
});
<|endoftext|>


<commit_before>var TradePage = (function(){

  var trading_page = 0, events_initialized = 0;

  var onLoad = function(){
    if(japanese_client() && /\/trading\.html/i.test(window.location.pathname)) {
        window.location.href = page.url.url_for('jptrading');
        return;
    } else if (!japanese_client() && /jp/.test(window.location.pathname)) {
        window.location.href = page.url.url_for('trading');
        return;
    }
    trading_page = 1;
    if(sessionStorage.getItem('currencies')){
      displayCurrencies();
    }
    BinarySocket.init({
      onmessage: function(msg){
        Message.process(msg);
      }
    });
    Price.clearFormId();
    if (events_initialized === 0) {
        events_initialized = 1;
        TradingEvents.init();
    }
    Content.populate();

    if(sessionStorage.getItem('currencies')){
      displayCurrencies();
      Symbols.getSymbols(1);
    }
    else {
      BinarySocket.send({ payout_currencies: 1 });
    }

    if (document.getElementById('websocket_form')) {
        addEventListenerForm();
    }

    // Walktrough Guide
    Guide.init({
      script : 'trading'
    });
    TradingAnalysis.bindAnalysisTabEvent();
    $('#tab_portfolio a').text(text.localize('Portfolio'));
    $('#tab_graph a').text(text.localize('Chart'));
    $('#tab_explanation a').text(text.localize('Explanation'));
    $('#tab_last_digit a').text(text.localize('Last Digit Stats'));
  };

  var reload = function() {
    sessionStorage.removeItem('underlying');
    window.location.reload();
  };

  var onUnload = function(){
    trading_page = 0;
    forgetTradingStreams();
    BinarySocket.clear();
    Defaults.clear();
  };

  return {
    onLoad: onLoad,
    reload: reload,
    onUnload : onUnload,
    is_trading_page: function(){return trading_page;}
  };
})();
<commit_msg>fix pjax<commit_after>var TradePage = (function(){

  var trading_page = 0, events_initialized = 0;

  var onLoad = function(){
    if(japanese_client() && /\/trading\.html/i.test(window.location.pathname)) {
        window.location.href = page.url.url_for('jptrading');
        return;
    } else if (!japanese_client() && /jp/.test(window.location.pathname)) {
        window.location.href = page.url.url_for('trading');
        return;
    }
    trading_page = 1;
    if(sessionStorage.getItem('currencies')){
      displayCurrencies();
    }
    BinarySocket.init({
      onmessage: function(msg){
        Message.process(msg);
      }
    });
    Price.clearFormId();
    if (events_initialized === 0) {
        events_initialized = 1;
        TradingEvents.init();
    }
    Content.populate();

    if(sessionStorage.getItem('currencies')){
      displayCurrencies();
      Symbols.getSymbols(1);
    }
    else {
      BinarySocket.send({ payout_currencies: 1 });
    }

    if (document.getElementById('websocket_form')) {
        addEventListenerForm();
    }

    // Walktrough Guide
    Guide.init({
      script : 'trading'
    });
    TradingAnalysis.bindAnalysisTabEvent();
    $('#tab_portfolio a').text(text.localize('Portfolio'));
    $('#tab_graph a').text(text.localize('Chart'));
    $('#tab_explanation a').text(text.localize('Explanation'));
    $('#tab_last_digit a').text(text.localize('Last Digit Stats'));
  };

  var reload = function() {
    sessionStorage.removeItem('underlying');
    window.location.reload();
  };

  var onUnload = function(){
    trading_page = 0;
    events_initialized = 0;
    forgetTradingStreams();
    BinarySocket.clear();
    Defaults.clear();
  };

  return {
    onLoad: onLoad,
    reload: reload,
    onUnload : onUnload,
    is_trading_page: function(){return trading_page;}
  };
})();
<|endoftext|>


<commit_before>'use strict';

define(['bitcoinjs-lib', 'util/btc'], function(Bitcoin, BtcUtils) {

var Crypto = Bitcoin.CryptoJS;

/**
 * Contacts (Address book).
 * @param {Object} store Object store
 * @constructor
 */
function Contacts(store, identity) {
  this.store = store;
  this.identity = identity
  this.contacts = this.store.init('contacts', []);
  this.validAddresses = [
      identity.wallet.versions.address,
      identity.wallet.versions.stealth.address,
      identity.wallet.versions.p2sh
  ]
  this.initContacts();
}

/**
 * Update contacts after loading them.
 * @private
 */
Contacts.prototype.initContacts = function() {
  var self = this;
  var updated;

  // TODO Remove when Darkwallet 1.0 release
  this.contacts.forEach(function(contact) {
      if (!contact) {
          return;
      }
      if (!contact.pubKeys) {
          self.updateKey(contact, contact.address, 0);
          contact.mainKey = 0;
          updated = true;
          self.updateContactHash(contact);
          // delete address since now is contained inside contact.pubKeys
          delete contact.address;
          delete contact.hash;
      }
  });
  if (updated) {
    console.log("updated contacts", this.contacts);
    // this.store.save();
  }
};

/**
 * Update address for a contact
 * @param {Object} contact Dictionary with a field address to feed the hash
 */
Contacts.prototype.prepareAddress = function(data) {
  var addresses = []; // {pubKey: ..., address: ..., data: ..., type: ...}
  var pubKey;
  try {
      // for now show uncompressed for contacts from uncompressed pubkeys
      pubKey = BtcUtils.extractPublicKey(data, (data.length == 130) ? false : true);
  } catch (e) {
  }
  var newKey = {data: data, pubKey: pubKey, type: 'address'};

  if (BtcUtils.isAddress(data, this.validAddresses)) {
      newKey.address = data;
      if (data[0] == '6') {
          newKey.type = 'stealth';
      }
  } else if (pubKey) {
      var pubKeyHash = Bitcoin.crypto.hash160(pubKey);
      var address = new Bitcoin.Address(pubKeyHash, this.identity.wallet.versions.address).toString();
      newKey.address = address;
      newKey.type = 'pubkey';
  } else {
      console.log("cant decode address properly!");
      newKey.address = data;
      newKey.type = 'unknown';
  }
  return newKey;
};

/**
 * Update fingerprint hash for a contact
 * @param {Object} contact Dictionary with a field address to feed the hash
 */
Contacts.prototype.updateContactHash = function(contact) {
    contact.hash = this.generateAddressHash(contact.pubKeys[contact.mainKey].address);
};

/**
 * Generate fingerprint hash for some address
 * @param {String} address address to generate the hash from
 */
Contacts.prototype.generateAddressHash = function(address) {
    return Crypto.SHA256(address).toString();
};

/**
 * Generate fingerprint hash for some data
 * @param {String} data address or pubkey to generate the hash from
 */
Contacts.prototype.generateContactHash = function(data) {
    var newKey = this.prepareAddress(data);
    return Crypto.SHA256(newKey.address).toString();
};

/**
 * Find Contact by pubkey
 * @param {Object} pubKey Public key to find.
 * @return {Object|null} The contact if it is there
 */
Contacts.prototype.findByPubKey = function (pubKey) {
  var toCheck = pubKey.toString();
  var compressed = (pubKey.length == 33);
  for(var i in this.contacts) {
    for(var j in this.contacts[i].pubKeys) {
      var address = this.contacts[i].pubKeys[j].data;
      var cPubKey;
      try {
          cPubKey = BtcUtils.extractPublicKey(address, compressed);
      } catch(e) {
          // not a good address
          continue;
      }
      if (cPubKey.toString() == toCheck) {
        return this.contacts[i];
      }
    }
  }
};

/**
 * Find Contact by address
 * @param {Object} address Address to find
 * @return {Object|null} The contact if it is there
 */
Contacts.prototype.findByAddress = function (address) {
  for(var i in this.contacts) {
    for(var j in this.contacts[i].pubKeys) {
      var cAddress = this.contacts[i].pubKeys[j].address;
      if (cAddress == address) {
        return this.contacts[i];
      }
    }
  }
};

/**
 * Add a contact to the address book
 * @param {Object} contact Contact information.
 */
Contacts.prototype.addContact = function (contact) {
  contact.pubKeys = [];

  this.updateKey(contact, contact.address, 0);
  delete contact.address;
  contact.mainKey = 0;

  this.updateContactHash(contact);
  this.contacts.push(contact);
  this.store.save();
};

/**
 * Add key
 */
Contacts.prototype.addContactKey = function (contact, data) {
  var newKey = this.prepareAddress(data);

  if (!contact.pubKeys) {
      contact.pubKeys = [];
  }
  contact.pubKeys.push(newKey);
  this.store.save();
  // delete address since now is contained inside contact.pubKeys
};

/**
 * Sets key index as main key
 * Will also update the contact hash to reflect new main identity.
 */
Contacts.prototype.setMainKey = function (contact, index) {
    if (index >= contact.pubKeys.length) {
       throw Error("Key does not exist");
    }
    contact.mainKey = index;
    this.updateContactHash(contact);
    this.store.save();
}

/**
 * Update a key from given user input
 */
Contacts.prototype.updateKey = function (contact, data, index) {
  var newKey = this.prepareAddress(data);

  if (!contact.pubKeys || !contact.pubKeys.length) {
      if (index) {
          throw Error("Trying to update key with index from contact with no keys");
      }
      contact.pubKeys = [newKey];
  } else {
      for(var par in newKey) {
          contact.pubKeys[index][par] = newKey[par];
      }
  }
};

/**
 * Edit a contact in the address book
 * @param {Object} contact Contact information.
 * @throws {Error} When trying to update a non-existing contact
 */
Contacts.prototype.updateContact = function (contact, data, index) {
  if (this.contacts.indexOf(contact) == -1) {
    throw Error("This is not an already existing contact!");
  }

  if (data) {
    this.updateKey(contact, data, index);
  }
  this.updateContactHash(contact);

  this.store.save();
};

/**
 * Delete a contact from the address book
 * @param {String} contact Contact information.
 * @throws {Error} When trying to delete a non-existing contact
 */
Contacts.prototype.deleteContact = function (contact) {
  var i = this.contacts.indexOf(contact);
  if (i == -1) {
    throw Error("Contact does not exist!");
  }
  this.contacts.splice(i, 1);
  this.store.save();
};

return Contacts;
});
<commit_msg>Don't delete the hash here!!!!<commit_after>'use strict';

define(['bitcoinjs-lib', 'util/btc'], function(Bitcoin, BtcUtils) {

var Crypto = Bitcoin.CryptoJS;

/**
 * Contacts (Address book).
 * @param {Object} store Object store
 * @constructor
 */
function Contacts(store, identity) {
  this.store = store;
  this.identity = identity
  this.contacts = this.store.init('contacts', []);
  this.validAddresses = [
      identity.wallet.versions.address,
      identity.wallet.versions.stealth.address,
      identity.wallet.versions.p2sh
  ]
  this.initContacts();
}

/**
 * Update contacts after loading them.
 * @private
 */
Contacts.prototype.initContacts = function() {
  var self = this;
  var updated;

  // TODO Remove when Darkwallet 1.0 release
  this.contacts.forEach(function(contact) {
      if (!contact) {
          return;
      }
      if (!contact.pubKeys) {
          self.updateKey(contact, contact.address, 0);
          contact.mainKey = 0;
          updated = true;
          self.updateContactHash(contact);
          // delete address since now is contained inside contact.pubKeys
          delete contact.address;
      }
  });
  if (updated) {
    console.log("updated contacts", this.contacts);
    // this.store.save();
  }
};

/**
 * Update address for a contact
 * @param {Object} contact Dictionary with a field address to feed the hash
 */
Contacts.prototype.prepareAddress = function(data) {
  var addresses = []; // {pubKey: ..., address: ..., data: ..., type: ...}
  var pubKey;
  try {
      // for now show uncompressed for contacts from uncompressed pubkeys
      pubKey = BtcUtils.extractPublicKey(data, (data.length == 130) ? false : true);
  } catch (e) {
  }
  var newKey = {data: data, pubKey: pubKey, type: 'address'};

  if (BtcUtils.isAddress(data, this.validAddresses)) {
      newKey.address = data;
      if (data[0] == '6') {
          newKey.type = 'stealth';
      }
  } else if (pubKey) {
      var pubKeyHash = Bitcoin.crypto.hash160(pubKey);
      var address = new Bitcoin.Address(pubKeyHash, this.identity.wallet.versions.address).toString();
      newKey.address = address;
      newKey.type = 'pubkey';
  } else {
      console.log("cant decode address properly!");
      newKey.address = data;
      newKey.type = 'unknown';
  }
  return newKey;
};

/**
 * Update fingerprint hash for a contact
 * @param {Object} contact Dictionary with a field address to feed the hash
 */
Contacts.prototype.updateContactHash = function(contact) {
    contact.hash = this.generateAddressHash(contact.pubKeys[contact.mainKey].address);
};

/**
 * Generate fingerprint hash for some address
 * @param {String} address address to generate the hash from
 */
Contacts.prototype.generateAddressHash = function(address) {
    return Crypto.SHA256(address).toString();
};

/**
 * Generate fingerprint hash for some data
 * @param {String} data address or pubkey to generate the hash from
 */
Contacts.prototype.generateContactHash = function(data) {
    var newKey = this.prepareAddress(data);
    return Crypto.SHA256(newKey.address).toString();
};

/**
 * Find Contact by pubkey
 * @param {Object} pubKey Public key to find.
 * @return {Object|null} The contact if it is there
 */
Contacts.prototype.findByPubKey = function (pubKey) {
  var toCheck = pubKey.toString();
  var compressed = (pubKey.length == 33);
  for(var i in this.contacts) {
    for(var j in this.contacts[i].pubKeys) {
      var address = this.contacts[i].pubKeys[j].data;
      var cPubKey;
      try {
          cPubKey = BtcUtils.extractPublicKey(address, compressed);
      } catch(e) {
          // not a good address
          continue;
      }
      if (cPubKey.toString() == toCheck) {
        return this.contacts[i];
      }
    }
  }
};

/**
 * Find Contact by address
 * @param {Object} address Address to find
 * @return {Object|null} The contact if it is there
 */
Contacts.prototype.findByAddress = function (address) {
  for(var i in this.contacts) {
    for(var j in this.contacts[i].pubKeys) {
      var cAddress = this.contacts[i].pubKeys[j].address;
      if (cAddress == address) {
        return this.contacts[i];
      }
    }
  }
};

/**
 * Add a contact to the address book
 * @param {Object} contact Contact information.
 */
Contacts.prototype.addContact = function (contact) {
  contact.pubKeys = [];

  this.updateKey(contact, contact.address, 0);
  delete contact.address;
  contact.mainKey = 0;

  this.updateContactHash(contact);
  this.contacts.push(contact);
  this.store.save();
};

/**
 * Add key
 */
Contacts.prototype.addContactKey = function (contact, data) {
  var newKey = this.prepareAddress(data);

  if (!contact.pubKeys) {
      contact.pubKeys = [];
  }
  contact.pubKeys.push(newKey);
  this.store.save();
  // delete address since now is contained inside contact.pubKeys
};

/**
 * Sets key index as main key
 * Will also update the contact hash to reflect new main identity.
 */
Contacts.prototype.setMainKey = function (contact, index) {
    if (index >= contact.pubKeys.length) {
       throw Error("Key does not exist");
    }
    contact.mainKey = index;
    this.updateContactHash(contact);
    this.store.save();
}

/**
 * Update a key from given user input
 */
Contacts.prototype.updateKey = function (contact, data, index) {
  var newKey = this.prepareAddress(data);

  if (!contact.pubKeys || !contact.pubKeys.length) {
      if (index) {
          throw Error("Trying to update key with index from contact with no keys");
      }
      contact.pubKeys = [newKey];
  } else {
      for(var par in newKey) {
          contact.pubKeys[index][par] = newKey[par];
      }
  }
};

/**
 * Edit a contact in the address book
 * @param {Object} contact Contact information.
 * @throws {Error} When trying to update a non-existing contact
 */
Contacts.prototype.updateContact = function (contact, data, index) {
  if (this.contacts.indexOf(contact) == -1) {
    throw Error("This is not an already existing contact!");
  }

  if (data) {
    this.updateKey(contact, data, index);
  }
  this.updateContactHash(contact);

  this.store.save();
};

/**
 * Delete a contact from the address book
 * @param {String} contact Contact information.
 * @throws {Error} When trying to delete a non-existing contact
 */
Contacts.prototype.deleteContact = function (contact) {
  var i = this.contacts.indexOf(contact);
  if (i == -1) {
    throw Error("Contact does not exist!");
  }
  this.contacts.splice(i, 1);
  this.store.save();
};

return Contacts;
});
<|endoftext|>


<commit_before>(function(NProgress) {

  this.NProgress = NProgress;

})(function($) {
  var NProgress = {};

  var Settings = NProgress.settings = {
    minimum: 0.08,
    easing: 'ease',
    speed: 300,
    trickleSpeed: 0.008,
    template: '

'
  };

  /**
   * Updates configuration.
   *
   *     NProgress.configure({
   *       minimum: 0.1
   *     });
   */
  NProgress.configure = function(options) {
    $.extend(Settings, options);
    return this;
  };

  /**
   * Last number.
   */

  NProgress.status = null;

  /**
   * Sets the progress bar status, where `n` is a number from `0.0` to `1.0`.
   *
   *     NProgress.set(0.4);
   *     NProgress.set(1.0);
   */

  NProgress.set = function(n) {
    n = clamp(n, Settings.minimum, 1);
    NProgress.status = (n === 1 ? null : n);

    var $progress = NProgress.render(),
        $bar      = $progress.find('[role~="bar"]'),
        speed     = Settings.speed,
        ease      = Settings.easing;

    setTimeout(function() {
      $progress.queue(function(next) {
        var perc = -1 + n; /* -1.0 ... 0.0 */

        $bar.css({
          transition: 'all '+speed+'ms '+ease,
          transform: 'translate3d('+(perc*100)+'%,0,0)'
        });

        if (n === 1) {
          $progress.css({ transition: 'none', opacity: 1 });

          setTimeout(function() {
            $progress.css({ transition: 'all '+speed+'ms linear', opacity: 0 });
            setTimeout(function() {
              NProgress.remove();
              next();
            }, speed);
          }, speed);
        } else {
          setTimeout(next, speed);
        }
      });
    }, 0);

    return this;
  };

  /**
   * Shows the progress bar.
   * This is the same as setting the status to 0%, except that it doesn't go backwards.
   *
   *     NProgress.start();
   *
   */
  NProgress.start = function() {
    if (!NProgress.status) NProgress.set(0);

    var work = function() {
      setTimeout(function() {
        if (!NProgress.status) return;
        NProgress.trickle();
        work();
      }, Settings.speed * 4);
    };

    if (Settings.trickleSpeed) work();

    return this;
  };

  /**
   * Hides the progress bar.
   * This is the *sort of* the same as setting the status to 100%, with the
   * difference being `done()` makes some placebo effect of some realistic motion.
   *
   *     NProgress.done();
   *
   * If `true` is passed, it will show the progress bar even if its hidden.
   *
   *     NProgress.done(true);
   */

  NProgress.done = function(force) {
    if (!force && !NProgress.status) return this;

    return NProgress.inc(0.3 + 0.5 * Math.random()).set(1);
  };

  /**
   * Increments by a random amount.
   */

  NProgress.inc = function(amount) {
    var n = NProgress.status;

    if (!n) {
      return NProgress.start();
    } else {
      if (typeof amount !== 'number') {
        amount = (1 - n) * clamp(Math.random() * n, 0.1, 0.95);
      }

      n = clamp(n + amount, 0, 0.994);
      return NProgress.set(n);
    }
  };

  NProgress.trickle = function() {
    return NProgress.inc(Math.random() * Settings.trickleSpeed);
  };

  /**
   * (Internal) renders the progress bar markup based on the `template`
   * setting.
   */

  NProgress.render = function() {
    if (NProgress.isRendered()) return $("#nprogress");
    $('body').addClass('nprogress-busy');

    var $el = $("
")
      .html(Settings.template)
      .appendTo(document.body);

    $el.find('[role~="bar"]').css({
      transition: 'all 0 linear',
      transform: 'translate3d(-100%,0,0)'
    });

    return $el;
  };

  /**
   * (Internal) Removes the element. Opposite of render().
   */

  NProgress.remove = function() {
    $('body').removeClass('nprogress-busy');
    $('#nprogress').remove();
  };

  /**
   * Checks if the progress bar is rendered.
   */

  NProgress.isRendered = function() {
    return ($("#nprogress").length > 0);
  };

  /**
   * Helpers
   */

  function clamp(n, min, max) {
    if (n < min) return min;
    if (n > max) return max;
    return n;
  }

  return NProgress;
}(jQuery));

<commit_msg>Try to fix the flash of full bar.<commit_after>(function(NProgress) {

  this.NProgress = NProgress;

})(function($) {
  var NProgress = {};

  var Settings = NProgress.settings = {
    minimum: 0.08,
    easing: 'ease',
    speed: 300,
    trickleSpeed: 0.008,
    template: '

'
  };

  /**
   * Updates configuration.
   *
   *     NProgress.configure({
   *       minimum: 0.1
   *     });
   */
  NProgress.configure = function(options) {
    $.extend(Settings, options);
    return this;
  };

  /**
   * Last number.
   */

  NProgress.status = null;

  /**
   * Sets the progress bar status, where `n` is a number from `0.0` to `1.0`.
   *
   *     NProgress.set(0.4);
   *     NProgress.set(1.0);
   */

  NProgress.set = function(n) {
    n = clamp(n, Settings.minimum, 1);
    NProgress.status = (n === 1 ? null : n);

    var $progress = NProgress.render(),
        $bar      = $progress.find('[role~="bar"]'),
        speed     = Settings.speed,
        ease      = Settings.easing;

    setTimeout(function() {
      $progress.queue(function(next) {
        var perc = -1 + n; /* -1.0 ... 0.0 */

        $bar.css({
          transition: 'all '+speed+'ms '+ease,
          transform: 'translate3d('+(perc*100)+'%,0,0)'
        });

        if (n === 1) {
          $progress.css({ transition: 'none', opacity: 1 });

          setTimeout(function() {
            $progress.css({ transition: 'all '+speed+'ms linear', opacity: 0 });
            setTimeout(function() {
              NProgress.remove();
              next();
            }, speed);
          }, speed);
        } else {
          setTimeout(next, speed);
        }
      });
    }, 0);

    return this;
  };

  /**
   * Shows the progress bar.
   * This is the same as setting the status to 0%, except that it doesn't go backwards.
   *
   *     NProgress.start();
   *
   */
  NProgress.start = function() {
    if (!NProgress.status) NProgress.set(0);

    var work = function() {
      setTimeout(function() {
        if (!NProgress.status) return;
        NProgress.trickle();
        work();
      }, Settings.speed * 4);
    };

    if (Settings.trickleSpeed) work();

    return this;
  };

  /**
   * Hides the progress bar.
   * This is the *sort of* the same as setting the status to 100%, with the
   * difference being `done()` makes some placebo effect of some realistic motion.
   *
   *     NProgress.done();
   *
   * If `true` is passed, it will show the progress bar even if its hidden.
   *
   *     NProgress.done(true);
   */

  NProgress.done = function(force) {
    if (!force && !NProgress.status) return this;

    return NProgress.inc(0.3 + 0.5 * Math.random()).set(1);
  };

  /**
   * Increments by a random amount.
   */

  NProgress.inc = function(amount) {
    var n = NProgress.status;

    if (!n) {
      return NProgress.start();
    } else {
      if (typeof amount !== 'number') {
        amount = (1 - n) * clamp(Math.random() * n, 0.1, 0.95);
      }

      n = clamp(n + amount, 0, 0.994);
      return NProgress.set(n);
    }
  };

  NProgress.trickle = function() {
    return NProgress.inc(Math.random() * Settings.trickleSpeed);
  };

  /**
   * (Internal) renders the progress bar markup based on the `template`
   * setting.
   */

  NProgress.render = function() {
    if (NProgress.isRendered()) return $("#nprogress");
    $('body').addClass('nprogress-busy');

    var $el = $("
")
      .html(Settings.template);

    $el.find('[role~="bar"]').css({
      transition: 'all 0 linear',
      transform: 'translate3d(-100%,0,0)'
    });

    $el.appendTo(document.body);

    return $el;
  };

  /**
   * (Internal) Removes the element. Opposite of render().
   */

  NProgress.remove = function() {
    $('body').removeClass('nprogress-busy');
    $('#nprogress').remove();
  };

  /**
   * Checks if the progress bar is rendered.
   */

  NProgress.isRendered = function() {
    return ($("#nprogress").length > 0);
  };

  /**
   * Helpers
   */

  function clamp(n, min, max) {
    if (n < min) return min;
    if (n > max) return max;
    return n;
  }

  return NProgress;
}(jQuery));

<|endoftext|>


<commit_before>/*global define*/

define(function () {
    'use strict';

    var DeleteController = function ($scope, $window, $state, $q, WriteQueries, notification, params, view, entry) {
        this.$scope = $scope;
        this.$window = $window;
        this.$state = $state;
        this.WriteQueries = WriteQueries;
        this.entityLabel = params.entity;
        this.entityId = params.id;
        this.view = view;
        this.title = view.title();
        this.description = view.description();
        this.actions = view.actions();
        this.entity = view.getEntity();
        this.notification = notification;
        this.$scope.entry = entry;
        this.$scope.view = view;

        $scope.$on('$destroy', this.destroy.bind(this));

        this.previousStateParametersDeferred = $q.defer();
        $scope.$on('$stateChangeSuccess', (event, to, toParams, from, fromParams) => {
            this.previousStateParametersDeferred.resolve(fromParams);
        });
    };

    DeleteController.prototype.deleteOne = function () {
        var notification = this.notification,
            entityName = this.entity.name();

        return this.WriteQueries.deleteOne(this.view, this.entityId)
            .then(
                function () {
                    this.previousStateParametersDeferred.promise.then(function(previousStateParameters) {
                        notification.log('Element successfully deleted.', { addnCls: 'humane-flatty-success' });

                        // if previous page was related to deleted entity, redirect to list
                        if (previousStateParameters.entity === entityName && previousStateParameters.id === this.entityId) {
                            return this.$state.go(this.$state.get('list'), angular.extend({
                                entity: entityName
                            }, this.$state.params));
                        }

                        this.back();
                    }.bind(this));
                }.bind(this),
                function (response) {
                    // @TODO: share this method when splitting controllers
                    var body = response.data;
                    if (typeof body === 'object') {
                        body = JSON.stringify(body);
                    }

                    notification.log('Oops, an error occured : (code: ' + response.status + ') ' + body, {addnCls: 'humane-flatty-error'});
                }
            );
    };

    DeleteController.prototype.back = function () {
        this.$window.history.back();
    };

    DeleteController.prototype.destroy = function () {
        this.$scope = undefined;
        this.WriteQueries = undefined;
        this.view = undefined;
        this.entity = undefined;
    };

    DeleteController.$inject = ['$scope', '$window', '$state', '$q', 'WriteQueries', 'notification', 'params', 'view', 'entry'];

    return DeleteController;
});
<commit_msg>Code review<commit_after>/*global define*/

define(function () {
    'use strict';

    var DeleteController = function ($scope, $window, $state, $q, WriteQueries, notification, params, view, entry) {
        this.$scope = $scope;
        this.$window = $window;
        this.$state = $state;
        this.WriteQueries = WriteQueries;
        this.entityLabel = params.entity;
        this.entityId = params.id;
        this.view = view;
        this.title = view.title();
        this.description = view.description();
        this.actions = view.actions();
        this.entity = view.getEntity();
        this.notification = notification;
        this.$scope.entry = entry;
        this.$scope.view = view;

        $scope.$on('$destroy', this.destroy.bind(this));

        this.previousStateParametersDeferred = $q.defer();
        $scope.$once('$stateChangeSuccess', (event, to, toParams, from, fromParams) => {
            this.previousStateParametersDeferred.resolve(fromParams);
        });
    };

    DeleteController.prototype.deleteOne = function () {
        var notification = this.notification,
            entityName = this.entity.name();

        return this.WriteQueries.deleteOne(this.view, this.entityId)
            .then(
                () => {
                    this.previousStateParametersDeferred.promise.then(previousStateParameters => {
                        // if previous page was related to deleted entity, redirect to list
                        if (previousStateParameters.entity === entityName && previousStateParameters.id === this.entityId) {
                            this.$state.go(this.$state.get('list'), angular.extend({
                                entity: entityName
                            }, this.$state.params));
                        } else {
                            this.$window.history.back();
                        }

                        notification.log('Element successfully deleted.', { addnCls: 'humane-flatty-success' });
                    });
                },
                response => {
                    // @TODO: share this method when splitting controllers
                    var body = response.data;
                    if (typeof body === 'object') {
                        body = JSON.stringify(body);
                    }

                    notification.log('Oops, an error occured : (code: ' + response.status + ') ' + body, {addnCls: 'humane-flatty-error'});
                }
            );
    };

    DeleteController.prototype.destroy = function () {
        this.$scope = undefined;
        this.WriteQueries = undefined;
        this.view = undefined;
        this.entity = undefined;
    };

    DeleteController.$inject = ['$scope', '$window', '$state', '$q', 'WriteQueries', 'notification', 'params', 'view', 'entry'];

    return DeleteController;
});
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.send({
    items: [
      {name:'Dummy Session', url: "/sessions/123456"}
    ]
  })
});

router.get('/:sessionId', function(req, res, next) {
  if (req.params.sessionId == "123456") {
    res.send({
      id: req.params.sessionId,
      items: [
        {name: 'Item 1', description: 'Lorem Ipsum', estimates: [4, 10, 23, 9]},
        {name: 'Item number 2', description: 'Lorem Ipsum hfhfhfhf'},
        {name: 'I am 3', description: 'Lorem asdfasdf Ipsum', estimates: [8, 0, 3456]},
        {name: 'Four', description: 'Lorem 444444444 v  44 4 4 4Ipsum'}
      ]
    });
  } else res.sendStatus(404);
});

router.post('/:sessionId/estimate', function(req, res, next) {
  res.statusCode = 200;
  res.send();
});

module.exports = router;
<commit_msg>#3 Add dummy data with for active session<commit_after>var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.send({
    items: [
      {name:'Dummy Session', links: [{rel: "self", href: "/sessions/123456"}]}
    ]
  })
});

router.get('/:sessionId', function(req, res, next) {
  if (req.params.sessionId == "123456") {
    res.send({
      id: req.params.sessionId,
      items: [
        {name: 'Item 1', description: 'Lorem Ipsum', estimates: [4, 10, 23, 9]},
        {name: 'Item number 2', description: 'Lorem Ipsum hfhfhfhf'},
        {name: 'I am 3', description: 'Lorem asdfasdf Ipsum', estimates: [8, 0, 3456]},
        {name: 'Four', description: 'Lorem 444444444 v  44 4 4 4Ipsum'}
      ],
      activeItem: {name: 'Four', description: 'Lorem 444444444 v  44 4 4 4Ipsum', links: [
        {rel: "estimate", href: "/sessions/123456/item/98765/estimate"}
      ]}
    });
  } else res.sendStatus(404);
});

router.post('/:sessionId/estimate', function(req, res, next) {
  res.statusCode = 200;
  res.send();
});

module.exports = router;
<|endoftext|>


<commit_before>var MissingPerson = require('../../app/models/missingPerson');

exports.create = function (req, res) {
    var firstname = req.body.firstname;
    var surname = req.body.surname;

    var missingPerson = new MissingPerson();

    if (firstname) {
        missingPerson.firstname = firstname
    }
    if (surname) {
        missingPerson.surname = surname
    }

    missingPerson.birthYear = req.body.birthYear
    missingPerson.borough = req.body.town

    missingPerson.latitude = req.body.latitude
    missingPerson.longitude = req.body.longitude

    missingPerson.wentMissing = new Date();
    missingPerson.created = new Date();
    missingPerson.updated = new Date();

    missingPerson.status = "Missing"

    missingPerson.save(function (err) {
        if (err) {
            console.log(err);
            res.json({ message: 'Error' });
        }
        else {
            res.json(missingPerson);
        }
    });
}
<commit_msg>Fix reporting person<commit_after>var MissingPerson = require('../../app/models/missingPerson');

exports.create = function (req, res) {
    var firstname = req.body.firstname;
    var surname = req.body.surname;

    var missingPerson = new MissingPerson();

    if (firstname) {
        missingPerson.forenames = firstname;
    }
    if (surname) {
        missingPerson.surname = surname;
    }

    missingPerson.gender = 'M';
    missingPerson.status = 'Missing';
    missingPerson.category = 'Missing';
    missingPerson.birthYear = req.body.birthYear;
    missingPerson.borough = req.body.town;

    missingPerson.latitude = req.body.latitude;
    missingPerson.longitude = req.body.longitude;

    missingPerson.wentMissing = new Date();
    missingPerson.created = new Date();
    missingPerson.updated = new Date();

    missingPerson.id = generateGUID();

    missingPerson.save(function (err) {
        if (err) {
            console.log(err);
            res.json({ message: 'Error' });
        }
        else {
            res.json(missingPerson);
        }
    });
}

generateGUID = function() {
    var _sym = 'ABCDEF1234567890';
    var str = '';
    var count = 20;

    for (var i = 0; i < count; i++) {
        str += _sym[parseInt(Math.random() * (_sym.length))];
    }
    return str;
}
<|endoftext|>


<commit_before>/*
 *
 * preload
 *
 * ---
 * @Copyright(c) 2014, falsandtru
 * @license MIT http://opensource.org/licenses/mit-license.php
 * @version 0.2.2
 * @updated 2014/06/08
 * @author falsandtru https://github.com/falsandtru/
 * @Compressor Closure Compiler
 */
(function(f,m,n,p){function q(a,b,d,e,h,c){var f=this;switch(!0){case "string"===typeof c:c={link:c};default:f=f instanceof a?f:a(d),f=h.setProperties.call(f,null,null)}var g;g=a.extend(!0,{gns:h.name,ns:e,observe:!0,link:"a:not([target])",filter:function(){return/(\/[^.]*|\.html?|\.php)([#?].*)?$/.test(this.href)},lock:1E3,forward:null,check:null,interval:1E3,limit:2,cooldown:1E4,skip:50,query:null,encode:!1,prefetch:null,ajax:{dataType:"text",async:!0,timeout:1500}},c);g.nss={array:[h.name].concat(g.ns&&
String(g.ns).split(".")||[])};a.extend(!0,g=g.scope&&h.scope(g)||g,{id:0,nss:{name:g.ns||"",alias:h.alias?[h.alias].concat(g.nss.array.slice(1)).join("."):!1,event:g.nss.array.join("."),data:g.nss.array.join("-"),class4html:g.nss.array.join("-"),click:["click"].concat(g.nss.array.join(":")).join("."),mousemove:["mousemove"].concat(g.nss.array.join(":")).join("."),mouseover:["mouseover"].concat(g.nss.array.join(":")).join("."),mouseout:["mouseout"].concat(g.nss.array.join(":")).join("."),touchstart:["touchstart"].concat(g.nss.array.join(":")).join("."),
touchmove:["touchmove"].concat(g.nss.array.join(":")).join("."),touchend:["touchend"].concat(g.nss.array.join(":")).join(".")},target:null,volume:0,points:[],touch:!1,queue:[],xhr:null,ajax:a.extend(!0,{},a.ajaxSettings,g.ajax),timeStamp:0,option:c});a(function(){h.registrate.call(f,a,b,d,e,h,g)});return f}var e;e={name:"preload",alias:"",ids:[],settings:[0],count:0,disable:!1,setAlias:function(a){e.alias="string"===typeof a?a:e.alias;e.name===e.alias||f[e.alias]||(f[e.name][e.alias]=f.fn[e.name],
f.fn[e.alias]=f[e.alias]=f.fn[e.name])},setProperties:function(a,b){var d=this;if(d instanceof f||d===f[e.name])d=d instanceof f&&b!==p?d.add(b):d,d[e.name]=f[e.name],d.enable=function(){e.disable=!1},d.disable=function(){e.disable=!0};return d},req:{},loaded:{},registrate:function(a,b,d,e,h,c){var f;f=this;c.id=h.settings.length;h.ids.push(c.id);h.settings[c.id]=c;b=c.encode?h.canonicalizeURL(b.location.href):b.location.href;h.loaded[b.replace(/#.*/,"")]=!0;a(d).unbind(c.nss.event).bind(c.nss.event,
function(b){c.volume=0;c.timeStamp=0;f.find(b.target).add(f.filter(b.target)).find(c.link).filter(c.filter).unbind(c.nss.click).one(c.nss.click,c.id,function(b){if(!h.disable){var g=h.settings[b.data];b.timeStamp=(new Date).getTime();g.encode&&("href"in this?this.href=h.getURL(g,this):this.src=h.getURL(g,this));switch(!b.isDefaultPrevented()&&a.data(b.currentTarget,g.nss.data)){case "preload":case "lock":g.forward?(h.getURL(g,b.currentTarget),!1===h.fire(g.forward,null,[b,g.xhr,g.timeStamp])?"lock"===
a.data(b.currentTarget,g.nss.data)?b.preventDefault():(h.click(g,b),a.removeData(b.currentTarget,g.nss.data)):(b.preventDefault(),a.removeData(b.currentTarget,g.nss.data))):"lock"===a.data(b.currentTarget,g.nss.data)?b.preventDefault():(h.click(g,b),a.removeData(b.currentTarget,g.nss.data));break;default:g.xhr&&4>g.xhr.readyState&&g.xhr.abort()}}}).unbind(c.nss.mouseover).bind(c.nss.mouseover,c.id,function(a){h.settings[a.data].target=this}).unbind(c.nss.mouseout).bind(c.nss.mouseout,c.id,function(a){h.settings[a.data].target=
null}).unbind(c.nss.mousemove).bind(c.nss.mousemove,c.id,function(a){var b=h.settings[a.data];a.timeStamp=(new Date).getTime();b.points.unshift(a);b.points.splice(10,1);h.check(b,a,b.target)})});c.observe&&a(d).trigger(c.nss.event);(function(a,b){setTimeout(function(){if(c=h.settings[a])c.volume-=Number(!!c.volume),setTimeout(arguments.callee,b)},b)})(c.id,c.cooldown);c.prefetch&&a(c.prefetch).each(function(){h.prefetch.call(this)})},check:function(a,b,d,k){var h,c,l;if(d)switch(h=e.getURL(a,b.currentTarget),
c=a.queue,!0){case !e.settings[a.id]:case 100<c.length:case a.interval?(new Date).getTime()-a.timeStamp<a.interval:0:case a.volume>=a.limit:case a.target!==d:case a.target.protocol!==d.protocol:case a.target.host!==d.host:case f(d).is('[target="_blank"]'):case a.check?!!e.fire(a.check,b.currentTarget,[h]):e.loaded[h.replace(/#.*/,"")]:case !function(a){if(3>a.length)return!1;var b,c,d;c=a[0].timeStamp-a[1].timeStamp;b=Math.pow(a[0].pageX-a[1].pageX,2)+Math.pow(a[0].pageY-a[1].pageY,2)/(c||1);d=a[1].timeStamp-
a[2].timeStamp;a=Math.pow(a[1].pageX-a[2].pageX,2)+Math.pow(a[1].pageY-a[2].pageY,2)/(d||1);switch(!0){case 100<c||100<d:return!1;case b<a+Math.pow(5,2)&&b<=Math.pow(25,2):return!0;default:return!1}}(a.points):break;default:for(;l=c.shift();)clearTimeout(l);l=setTimeout(function(){for(;l=c.shift();)clearTimeout(l);switch(!0){case !a.target:case b!==a.points[0]:case b.pageX!==a.points[0].pageX||b.pageY!==a.points[0].pageY:case !a.ajax.crossDomain&&a.target.protocol!==m.location.protocol:case !a.ajax.crossDomain&&
a.target.host!==m.location.host:break;default:a.xhr&&4>a.xhr.readyState&&a.xhr.abort(),e.loaded[h.replace(/#.*/,"")]=!0,++a.volume,a.timeStamp=b.timeStamp,f.data(d,a.nss.data,"preload"),a.lock&&(f.data(a.target,a.nss.data,"lock"),f(a.target).one(a.nss.click,b.timeStamp,function(b){if(f.data(b.currentTarget,a.nss.data)){f(this);var c=Math.max(a.lock-(new Date).getTime()+b.data,0);f.data(b.currentTarget,a.nss.data,"click");c&&(setTimeout(function(){"click"===f.data(b.currentTarget,a.nss.data)&&e.click(a,
b);f.removeData(b.currentTarget,a.nss.data)},c),b.preventDefault())}})),e.preload(a,b)}},30);c.push(l)}},preload:function(a,b){var d=f.extend(!0,{},a.ajax,{success:function(){c=(new Date).getTime()-c;e.fire(a.ajax.success,this,arguments);e.loaded[this.url.replace(/#.*/,"")]=!0;for(var d in e.req){var g=e.req[d];g&&4>g.readyState&&(g.abort(),e.req[d]=null)}if(304===arguments[2].status||c<=a.skip)a.volume-=Number(!!a.volume),a.timeStamp=0;if("click"===f.data(b.currentTarget,a.nss.data))e.click(a,b);
else{var k;a.prefetch&&(k={async:!0,dataType:"text",success:function(){e.loaded[this.url]=!0;e.req[h]=null}},d=f(arguments[0]),d.filter(a.prefetch).add(d.find(a.prefetch)).each(function(){e.prefetch.call(this,a,k)}))}f.removeData(b.currentTarget,a.nss.data)},error:function(){e.fire(a.ajax.error,this,arguments);a.volume-=Number(!!a.volume);a.timeStamp=0;f.removeData(b.currentTarget,a.nss.data)}}),k=a.query;k&&(k=k.split("="),k=encodeURIComponent(k[0])+(0<k.length?"="+encodeURIComponent(k[1]):""));
var h=e.getURL(a,b.currentTarget);d.url=h.replace(/([^#]+)(#[^\s]*)?$/,"$1"+(k?(h.match(/\?/)?"&":"?")+k:"")+"$2");var c=(new Date).getTime();a.xhr=f.ajax(d)},click:function(a,b){var d=b.currentTarget;a.xhr&&4>a.xhr.readyState&&a.xhr.abort();f(b.currentTarget).removeData(a.nss.data);f(n).find(b.currentTarget)[0]&&(f(n).unbind(a.nss.click).one(a.nss.click,function(b){b.isDefaultPrevented()||(m.location.href=a.encode?e.canonicalizeURL(d.href):d.href,a.encode&&(m.location.href=e.getURL(a,this)))}),f(b.currentTarget).click());
b.preventDefault()},prefetch:function(a,b){var d=e.getURL(a,this);b?d&&!e.loaded[d]&&(b.url=d,e.req[d]=f.ajax(b)):e.loaded[d]=!0},getURL:function(a,b){var d;switch(b.tagName.toLowerCase()){case "a":case "link":d=b.href;break;case "script":case "img":case "iframe":d=b.src}return a.encode?e.canonicalizeURL(d):d},canonicalizeURL:function(a){var b;b=e.trim(a);b=b.replace(/["`^|\\<>{}\[\]\s].*/,"");b=/^https?:/i.test(b)?b:f("<a/>",{href:b})[0].href;b=encodeURI(decodeURI(b));return b=b.replace(/(?:%\w{2})+/g,
function(b){return a.match(b.toLowerCase())||b})},trim:function(a){if(String.prototype.trim)a=String(a).trim();else if(a=String(a).replace(/^[\s\uFEFF\xA0]+/,""))for(var b=a.length;--b;)if(/[^\s\uFEFF\xA0]/.test(a.charAt(b))){a=a.substring(0,b+1);break}return a},fire:function(a,b,d,e){return"function"===typeof a?e?setTimeout(function(){a.apply(b,d)},0):a.apply(b,d):a}};(function(a,b,d,e,f){a.fn[f.name]=a[f.name]=function(){return q.apply(this,[a,b,d,e,f].concat([].slice.call(arguments)))};f.setProperties.call(a[f.name])}).apply(this,
[].slice.call(arguments).concat([e]))})(jQuery,window,document,void 0);
<commit_msg>Compress<commit_after>/*
 *
 * preload
 *
 * ---
 * @Copyright(c) 2014, falsandtru
 * @license MIT http://opensource.org/licenses/mit-license.php
 * @version 0.2.2
 * @updated 2014/06/08
 * @author falsandtru https://github.com/falsandtru/
 * @Compressor Closure Compiler
 */
(function(f,m,n,p){function q(a,b,d,e,h,c){var f=this;switch(!0){case "string"===typeof c:c={link:c};default:f=f instanceof a?f:a(d),f=h.setProperties.call(f,null,null)}var g;g=a.extend(!0,{gns:h.name,ns:e,observe:!0,link:"a:not([target])",filter:function(){return/(\/[^.]*|\.html?|\.php)([#?].*)?$/.test(this.href)},lock:1E3,forward:null,check:null,interval:1E3,limit:2,cooldown:1E4,skip:50,query:null,encode:!1,prefetch:null,ajax:{dataType:"text",async:!0,timeout:1500}},c);g.nss={array:[h.name].concat(g.ns&&
String(g.ns).split(".")||[])};a.extend(!0,g=g.scope&&h.scope(g)||g,{id:0,nss:{name:g.ns||"",alias:h.alias?[h.alias].concat(g.nss.array.slice(1)).join("."):!1,event:g.nss.array.join("."),data:g.nss.array.join("-"),class4html:g.nss.array.join("-"),click:["click"].concat(g.nss.array.join(":")).join("."),mousemove:["mousemove"].concat(g.nss.array.join(":")).join("."),mouseover:["mouseover"].concat(g.nss.array.join(":")).join("."),mouseout:["mouseout"].concat(g.nss.array.join(":")).join("."),touchstart:["touchstart"].concat(g.nss.array.join(":")).join("."),
touchmove:["touchmove"].concat(g.nss.array.join(":")).join("."),touchend:["touchend"].concat(g.nss.array.join(":")).join(".")},target:null,volume:0,points:[],touch:!1,queue:[],xhr:null,ajax:a.extend(!0,{},a.ajaxSettings,g.ajax),timeStamp:0,option:c});a(function(){h.registrate.call(f,a,b,d,e,h,g)});return f}var e;e={name:"preload",alias:"",ids:[],settings:[0],count:0,disable:!1,setAlias:function(a){e.alias="string"===typeof a?a:e.alias;e.name===e.alias||f[e.alias]||(f[e.name][e.alias]=f.fn[e.name],
f.fn[e.alias]=f[e.alias]=f.fn[e.name])},setProperties:function(a,b){var d=this;if(d instanceof f||d===f[e.name])d=d instanceof f&&b!==p?d.add(b):d,d[e.name]=f[e.name],d.enable=function(){e.disable=!1},d.disable=function(){e.disable=!0};return d},req:{},loaded:{},registrate:function(a,b,d,e,h,c){var f;f=this;c.id=h.settings.length;h.ids.push(c.id);h.settings[c.id]=c;b=c.encode?h.canonicalizeURL(b.location.href):b.location.href;h.loaded[b.replace(/#.*/,"")]=!0;a(d).unbind(c.nss.event).bind(c.nss.event,
function(b){c.volume=0;c.timeStamp=0;f.find(b.target).add(f.filter(b.target)).find(c.link).filter(c.filter).unbind(c.nss.click).one(c.nss.click,c.id,function(b){if(!h.disable){var g=h.settings[b.data];b.timeStamp=(new Date).getTime();g.encode&&("href"in this?this.href=h.getURL(g,this):this.src=h.getURL(g,this));switch(!b.isDefaultPrevented()&&a.data(b.currentTarget,g.nss.data)){case "preload":case "lock":g.forward?(h.getURL(g,b.currentTarget),!1===h.fire(g.forward,null,[b,g.xhr,g.timeStamp])?"lock"===
a.data(b.currentTarget,g.nss.data)?b.preventDefault():(h.click(g,b),a.removeData(b.currentTarget,g.nss.data)):(b.preventDefault(),a.removeData(b.currentTarget,g.nss.data))):"lock"===a.data(b.currentTarget,g.nss.data)?b.preventDefault():(h.click(g,b),a.removeData(b.currentTarget,g.nss.data));break;default:g.xhr&&4>g.xhr.readyState&&g.xhr.abort()}}}).unbind(c.nss.mouseover).bind(c.nss.mouseover,c.id,function(a){h.settings[a.data].target=this}).unbind(c.nss.mouseout).bind(c.nss.mouseout,c.id,function(a){h.settings[a.data].target=
null}).unbind(c.nss.mousemove).bind(c.nss.mousemove,c.id,function(a){var b=h.settings[a.data];a.timeStamp=(new Date).getTime();b.points.unshift(a);b.points.splice(10,1);h.check(b,a,b.target)})});c.observe&&a(d).trigger(c.nss.event);(function(a,b){setTimeout(function(){if(c=h.settings[a])c.volume-=Number(!!c.volume),setTimeout(arguments.callee,b)},b)})(c.id,c.cooldown);c.prefetch&&a(c.prefetch).each(function(){h.prefetch.call(this)})},check:function(a,b,d,k){var h,c,l;if(d)switch(h=e.getURL(a,b.currentTarget),
c=a.queue,!0){case !e.settings[a.id]:case 100<c.length:case a.interval?(new Date).getTime()-a.timeStamp<a.interval:0:case a.volume>=a.limit:case a.target!==d:case a.target.protocol!==d.protocol:case a.target.host!==d.host:case f(d).is('[target="_blank"]'):case a.check?!!e.fire(a.check,b.currentTarget,[h]):e.loaded[h.replace(/#.*/,"")]:case !function(a){if(3>a.length)return!1;var b,c,d;c=a[0].timeStamp-a[1].timeStamp;b=Math.pow(a[0].pageX-a[1].pageX,2)+Math.pow(a[0].pageY-a[1].pageY,2)/(c||1);d=a[1].timeStamp-
a[2].timeStamp;a=Math.pow(a[1].pageX-a[2].pageX,2)+Math.pow(a[1].pageY-a[2].pageY,2)/(d||1);switch(!0){case 100<c||100<d:return!1;case b<a+Math.pow(5,2)&&b<=Math.pow(25,2):return!0;default:return!1}}(a.points):break;default:for(;l=c.shift();)clearTimeout(l);l=setTimeout(function(){for(;l=c.shift();)clearTimeout(l);switch(!0){case !a.target:case b!==a.points[0]:case b.pageX!==a.points[0].pageX||b.pageY!==a.points[0].pageY:case !a.ajax.crossDomain&&a.target.protocol!==m.location.protocol:case !a.ajax.crossDomain&&
a.target.host!==m.location.host:break;default:a.xhr&&4>a.xhr.readyState&&a.xhr.abort(),e.loaded[h.replace(/#.*/,"")]=!0,++a.volume,a.timeStamp=b.timeStamp,f.data(d,a.nss.data,"preload"),a.lock&&(f.data(a.target,a.nss.data,"lock"),f(a.target).one(a.nss.click,b.timeStamp,function(b){if(f.data(b.currentTarget,a.nss.data)){f(this);var c=Math.max(a.lock-(new Date).getTime()+b.data,0);f.data(b.currentTarget,a.nss.data,"click");c&&(setTimeout(function(){"click"===f.data(b.currentTarget,a.nss.data)&&e.click(a,
b);f.removeData(b.currentTarget,a.nss.data)},c),b.preventDefault())}})),e.preload(a,b)}},30);c.push(l)}},preload:function(a,b){var d=f.extend(!0,{},a.ajax,{success:function(){c=(new Date).getTime()-c;e.fire(a.ajax.success,this,arguments);e.loaded[this.url.replace(/#.*/,"")]=!0;for(var d in e.req){var g=e.req[d];g&&4>g.readyState&&(g.abort(),e.req[d]=null)}if(304===arguments[2].status||c<=a.skip)a.volume-=Number(!!a.volume),a.timeStamp=0;if("click"===f.data(b.currentTarget,a.nss.data))e.click(a,b);
else{var k;a.prefetch&&(k={async:!0,dataType:"text",success:function(){e.loaded[this.url]=!0;e.req[h]=null}},d=f(arguments[0]),d.filter(a.prefetch).add(d.find(a.prefetch)).each(function(){e.prefetch.call(this,a,k)}))}f.removeData(b.currentTarget,a.nss.data)},error:function(){e.fire(a.ajax.error,this,arguments);a.volume-=Number(!!a.volume);a.timeStamp=0;f.removeData(b.currentTarget,a.nss.data)}}),k=a.query;k&&(k=k.split("="),k=encodeURIComponent(k[0])+(0<k.length?"="+encodeURIComponent(k[1]):""));
var h=e.getURL(a,b.currentTarget);d.url=h.replace(/([^#]+)(#[^\s]*)?$/,"$1"+(k?(h.match(/\?/)?"&":"?")+k:"")+"$2");var c=(new Date).getTime();a.xhr=f.ajax(d)},click:function(a,b){var d=b.currentTarget;a.xhr&&4>a.xhr.readyState&&a.xhr.abort();f(b.currentTarget).removeData(a.nss.data);f(n).find(b.currentTarget)[0]&&(f(n).unbind(a.nss.click).one(a.nss.click,function(b){b.isDefaultPrevented()||(m.location.href=a.encode?e.canonicalizeURL(d.href):d.href,a.encode&&(m.location.href=e.getURL(a,b.target)))}),
f(b.currentTarget).click());b.preventDefault()},prefetch:function(a,b){var d=e.getURL(a,this);b?d&&!e.loaded[d]&&(b.url=d,e.req[d]=f.ajax(b)):e.loaded[d]=!0},getURL:function(a,b){var d;switch(b.tagName.toLowerCase()){case "a":case "link":d=b.href;break;case "script":case "img":case "iframe":d=b.src}return a.encode?e.canonicalizeURL(d):d},canonicalizeURL:function(a){var b;b=e.trim(a);b=b.replace(/["`^|\\<>{}\[\]\s].*/,"");b=/^https?:/i.test(b)?b:f("<a/>",{href:b})[0].href;b=encodeURI(decodeURI(b));
return b=b.replace(/(?:%\w{2})+/g,function(b){return a.match(b.toLowerCase())||b})},trim:function(a){if(String.prototype.trim)a=String(a).trim();else if(a=String(a).replace(/^[\s\uFEFF\xA0]+/,""))for(var b=a.length;--b;)if(/[^\s\uFEFF\xA0]/.test(a.charAt(b))){a=a.substring(0,b+1);break}return a},fire:function(a,b,d,e){return"function"===typeof a?e?setTimeout(function(){a.apply(b,d)},0):a.apply(b,d):a}};(function(a,b,d,e,f){a.fn[f.name]=a[f.name]=function(){return q.apply(this,[a,b,d,e,f].concat([].slice.call(arguments)))};
f.setProperties.call(a[f.name])}).apply(this,[].slice.call(arguments).concat([e]))})(jQuery,window,document,void 0);
<|endoftext|>


<commit_before>var Alcohol = Backbone.Model.extend({
	defaults: {
		"alcoholContent": 0,
		"ounces": 0
	}
});<commit_msg>Created a model for Alcohol<commit_after>var Alcohol = Backbone.Model.extend({
	defaults: {
		"alcoholContent": 0,
		"ounces": 0
	},
});<|endoftext|>


<commit_before>/*! NProgress (c) 2013, Rico Sta. Cruz
 *  http://ricostacruz.com/nprogress */

;(function(factory) {

  if (typeof module === 'function') {
    module.exports = factory();
  } else if (typeof define === 'function' && define.amd) {
    define(factory);
  } else {
    this.NProgress = factory();
  }

})(function() {
  var NProgress = {};

  NProgress.version = '0.1.3';

  var Settings = NProgress.settings = {
    minimum: 0.08,
    easing: 'ease',
    positionUsing: '',
    speed: 200,
    trickle: true,
    trickleRate: 0.02,
    trickleSpeed: 800,
    showSpinner: true,
    barSelector: '[role="bar"]',
    spinnerSelector: '[role="spinner"]',
    template: '

'
  };

  /**
   * Updates configuration.
   *
   *     NProgress.configure({
   *       minimum: 0.1
   *     });
   */
  NProgress.configure = function(options) {
    var key, value;
    for (key in options) {
      value = options[key];
      if (value !== undefined && options.hasOwnProperty(key)) Settings[key] = value;
    }

    return this;
  };

  /**
   * Last number.
   */

  NProgress.status = null;

  /**
   * Sets the progress bar status, where `n` is a number from `0.0` to `1.0`.
   *
   *     NProgress.set(0.4);
   *     NProgress.set(1.0);
   */

  NProgress.set = function(n) {
    var started = NProgress.isStarted();

    n = clamp(n, Settings.minimum, 1);
    NProgress.status = (n === 1 ? null : n);

    var progress = NProgress.render(!started),
        bar      = progress.querySelector(Settings.barSelector),
        speed    = Settings.speed,
        ease     = Settings.easing;

    progress.offsetWidth; /* Repaint */

    queue(function(next) {
      // Set positionUsing if it hasn't already been set
      if (Settings.positionUsing === '') Settings.positionUsing = NProgress.getPositioningCSS();

      // Add transition
      css(bar, barPositionCSS(n, speed, ease));

      if (n === 1) {
        // Fade out
        css(progress, {
          transition: 'none',
          opacity: 1
        });
        progress.offsetWidth; /* Repaint */

        setTimeout(function() {
          css(progress, {
            transition: 'all ' + speed + 'ms linear',
            opacity: 0
          });
          setTimeout(function() {
            NProgress.remove();
            next();
          }, speed);
        }, speed);
      } else {
        setTimeout(next, speed);
      }
    });

    return this;
  };

  NProgress.isStarted = function() {
    return typeof NProgress.status === 'number';
  };

  /**
   * Shows the progress bar.
   * This is the same as setting the status to 0%, except that it doesn't go backwards.
   *
   *     NProgress.start();
   *
   */
  NProgress.start = function() {
    if (!NProgress.status) NProgress.set(0);

    var work = function() {
      setTimeout(function() {
        if (!NProgress.status) return;
        NProgress.trickle();
        work();
      }, Settings.trickleSpeed);
    };

    if (Settings.trickle) work();

    return this;
  };

  /**
   * Hides the progress bar.
   * This is the *sort of* the same as setting the status to 100%, with the
   * difference being `done()` makes some placebo effect of some realistic motion.
   *
   *     NProgress.done();
   *
   * If `true` is passed, it will show the progress bar even if its hidden.
   *
   *     NProgress.done(true);
   */

  NProgress.done = function(force) {
    if (!force && !NProgress.status) return this;

    return NProgress.inc(0.3 + 0.5 * Math.random()).set(1);
  };

  /**
   * Increments by a random amount.
   */

  NProgress.inc = function(amount) {
    var n = NProgress.status;

    if (!n) {
      return NProgress.start();
    } else {
      if (typeof amount !== 'number') {
        amount = (1 - n) * clamp(Math.random() * n, 0.1, 0.95);
      }

      n = clamp(n + amount, 0, 0.994);
      return NProgress.set(n);
    }
  };

  NProgress.trickle = function() {
    return NProgress.inc(Math.random() * Settings.trickleRate);
  };

  /**
   * Waits for all supplied jQuery promises and
   * increases the progress as the promises resolve.
   *
   * @param $promise jQUery Promise
   */
  (function() {
    var initial = 0, current = 0;

    NProgress.promise = function($promise) {
      if (!$promise || $promise.state() == "resolved") {
        return this;
      }

      if (current == 0) {
        NProgress.start();
      }

      initial++;
      current++;

      $promise.always(function() {
        current--;
        if (current == 0) {
            initial = 0;
            NProgress.done();
        } else {
            NProgress.set((initial - current) / initial);
        }
      });

      return this;
    };

  })();

  /**
   * (Internal) renders the progress bar markup based on the `template`
   * setting.
   */

  NProgress.render = function(fromStart) {
    if (NProgress.isRendered()) return document.getElementById('nprogress');

    addClass(document.documentElement, 'nprogress-busy');

    var progress = document.createElement('div');
    progress.id = 'nprogress';
    progress.innerHTML = Settings.template;

    var bar      = progress.querySelector(Settings.barSelector),
        perc     = fromStart ? '-100' : toBarPerc(NProgress.status || 0),
        spinner;

    css(bar, {
      transition: 'all 0 linear',
      transform: 'translate3d(' + perc + '%,0,0)'
    });

    if (!Settings.showSpinner) {
      spinner = progress.querySelector(Settings.spinnerSelector);
      spinner && removeElement(spinner);
    }

    document.body.appendChild(progress);
    return progress;
  };

  /**
   * Removes the element. Opposite of render().
   */

  NProgress.remove = function() {
    removeClass(document.documentElement, 'nprogress-busy');
    var progress = document.getElementById('nprogress');
    progress && removeElement(progress);
  };

  /**
   * Checks if the progress bar is rendered.
   */

  NProgress.isRendered = function() {
    return !!document.getElementById('nprogress');
  };

  /**
   * Determine which positioning CSS rule to use.
   */

  NProgress.getPositioningCSS = function() {
    // Sniff on document.body.style
    var bodyStyle = document.body.style;

    // Sniff prefixes
    var vendorPrefix = ('WebkitTransform' in bodyStyle) ? 'Webkit' :
                       ('MozTransform' in bodyStyle) ? 'Moz' :
                       ('msTransform' in bodyStyle) ? 'ms' :
                       ('OTransform' in bodyStyle) ? 'O' : '';

    if (vendorPrefix + 'Perspective' in bodyStyle) {
      // Modern browsers with 3D support, e.g. Webkit, IE10
      return 'translate3d';
    } else if (vendorPrefix + 'Transform' in bodyStyle) {
      // Browsers without 3D support, e.g. IE9
      return 'translate';
    } else {
      // Browsers without translate() support, e.g. IE7-8
      return 'margin';
    }
  };

  /**
   * Helpers
   */

  function clamp(n, min, max) {
    if (n < min) return min;
    if (n > max) return max;
    return n;
  }

  /**
   * (Internal) converts a percentage (`0..1`) to a bar translateX
   * percentage (`-100%..0%`).
   */

  function toBarPerc(n) {
    return (-1 + n) * 100;
  }

  /**
   * (Internal) returns the correct CSS for changing the bar's
   * position given an n percentage, and speed and ease from Settings
   */

  function barPositionCSS(n, speed, ease) {
    var barCSS;

    if (Settings.positionUsing === 'translate3d') {
      barCSS = { transform: 'translate3d('+toBarPerc(n)+'%,0,0)' };
    } else if (Settings.positionUsing === 'translate') {
      barCSS = { transform: 'translate('+toBarPerc(n)+'%,0)' };
    } else {
      barCSS = { 'margin-left': toBarPerc(n)+'%' };
    }

    barCSS.transition = 'all '+speed+'ms '+ease;

    return barCSS;
  }

  /**
   * (Internal) Queues a function to be executed.
   */

  var queue = (function() {
    var pending = [];

    function next() {
      var fn = pending.shift();
      if (fn) {
        fn(next);
      }
    }

    return function(fn) {
      pending.push(fn);
      if (pending.length == 1) next();
    };
  })();

  /**
   * (Internal) Applies css properties to an element, similar to the jQuery
   * css method.
   *
   * While this helper does assist with vendor prefixed property names, it
   * does not perform any manipulation of values prior to setting styles.
   */

  var css = (function() {
    var cssPrefixes = [ 'Webkit', 'O', 'Moz', 'ms' ],
        cssProps    = {};

    function camelCase(string) {
      return string.replace(/^-ms-/, 'ms-').replace(/-([\da-z])/gi, function(match, letter) {
        return letter.toUpperCase();
      });
    }

    function getVendorProp(name) {
      var style = document.body.style;
      if (name in style) return name;

      var i = cssPrefixes.length,
          capName = name.charAt(0).toUpperCase() + name.slice(1),
          vendorName;
      while (i--) {
        vendorName = cssPrefixes[i] + capName;
        if (vendorName in style) return vendorName;
      }

      return name;
    }

    function getStyleProp(name) {
      name = camelCase(name);
      return cssProps[name] || (cssProps[name] = getVendorProp(name));
    }

    function applyCss(element, prop, value) {
      prop = getStyleProp(prop);
      element.style[prop] = value;
    }

    return function(element, properties) {
      var args = arguments,
          prop,
          value;

      if (args.length == 2) {
        for (prop in properties) {
          value = properties[prop];
          if (value !== undefined && properties.hasOwnProperty(prop)) applyCss(element, prop, value);
        }
      } else {
        applyCss(element, args[1], args[2]);
      }
    }
  })();

  /**
   * (Internal) Determines if an element or space separated list of class names contains a class name.
   */

  function hasClass(element, name) {
    var list = typeof element == 'string' ? element : classList(element);
    return list.indexOf(' ' + name + ' ') >= 0;
  }

  /**
   * (Internal) Adds a class to an element.
   */

  function addClass(element, name) {
    var oldList = classList(element),
        newList = oldList + name;

    if (hasClass(oldList, name)) return;

    // Trim the opening space.
    element.className = newList.substring(1);
  }

  /**
   * (Internal) Removes a class from an element.
   */

  function removeClass(element, name) {
    var oldList = classList(element),
        newList;

    if (!hasClass(element, name)) return;

    // Replace the class name.
    newList = oldList.replace(' ' + name + ' ', ' ');

    // Trim the opening and closing spaces.
    element.className = newList.substring(1, newList.length - 1);
  }

  /**
   * (Internal) Gets a space separated list of the class names on the element.
   * The list is wrapped with a single space on each end to facilitate finding
   * matches within the list.
   */

  function classList(element) {
    return (' ' + (element.className || '') + ' ').replace(/\s+/gi, ' ');
  }

  /**
   * (Internal) Removes an element from the DOM.
   */

  function removeElement(element) {
    element && element.parentNode && element.parentNode.removeChild(element);
  }

  return NProgress;
});

<commit_msg>stronger check on module<commit_after>/*! NProgress (c) 2013, Rico Sta. Cruz
 *  http://ricostacruz.com/nprogress */

;(function(factory) {

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = factory();
  } else if (typeof define === 'function' && define.amd) {
    define(factory);
  } else {
    this.NProgress = factory();
  }

})(function() {
  var NProgress = {};

  NProgress.version = '0.1.3';

  var Settings = NProgress.settings = {
    minimum: 0.08,
    easing: 'ease',
    positionUsing: '',
    speed: 200,
    trickle: true,
    trickleRate: 0.02,
    trickleSpeed: 800,
    showSpinner: true,
    barSelector: '[role="bar"]',
    spinnerSelector: '[role="spinner"]',
    template: '

'
  };

  /**
   * Updates configuration.
   *
   *     NProgress.configure({
   *       minimum: 0.1
   *     });
   */
  NProgress.configure = function(options) {
    var key, value;
    for (key in options) {
      value = options[key];
      if (value !== undefined && options.hasOwnProperty(key)) Settings[key] = value;
    }

    return this;
  };

  /**
   * Last number.
   */

  NProgress.status = null;

  /**
   * Sets the progress bar status, where `n` is a number from `0.0` to `1.0`.
   *
   *     NProgress.set(0.4);
   *     NProgress.set(1.0);
   */

  NProgress.set = function(n) {
    var started = NProgress.isStarted();

    n = clamp(n, Settings.minimum, 1);
    NProgress.status = (n === 1 ? null : n);

    var progress = NProgress.render(!started),
        bar      = progress.querySelector(Settings.barSelector),
        speed    = Settings.speed,
        ease     = Settings.easing;

    progress.offsetWidth; /* Repaint */

    queue(function(next) {
      // Set positionUsing if it hasn't already been set
      if (Settings.positionUsing === '') Settings.positionUsing = NProgress.getPositioningCSS();

      // Add transition
      css(bar, barPositionCSS(n, speed, ease));

      if (n === 1) {
        // Fade out
        css(progress, {
          transition: 'none',
          opacity: 1
        });
        progress.offsetWidth; /* Repaint */

        setTimeout(function() {
          css(progress, {
            transition: 'all ' + speed + 'ms linear',
            opacity: 0
          });
          setTimeout(function() {
            NProgress.remove();
            next();
          }, speed);
        }, speed);
      } else {
        setTimeout(next, speed);
      }
    });

    return this;
  };

  NProgress.isStarted = function() {
    return typeof NProgress.status === 'number';
  };

  /**
   * Shows the progress bar.
   * This is the same as setting the status to 0%, except that it doesn't go backwards.
   *
   *     NProgress.start();
   *
   */
  NProgress.start = function() {
    if (!NProgress.status) NProgress.set(0);

    var work = function() {
      setTimeout(function() {
        if (!NProgress.status) return;
        NProgress.trickle();
        work();
      }, Settings.trickleSpeed);
    };

    if (Settings.trickle) work();

    return this;
  };

  /**
   * Hides the progress bar.
   * This is the *sort of* the same as setting the status to 100%, with the
   * difference being `done()` makes some placebo effect of some realistic motion.
   *
   *     NProgress.done();
   *
   * If `true` is passed, it will show the progress bar even if its hidden.
   *
   *     NProgress.done(true);
   */

  NProgress.done = function(force) {
    if (!force && !NProgress.status) return this;

    return NProgress.inc(0.3 + 0.5 * Math.random()).set(1);
  };

  /**
   * Increments by a random amount.
   */

  NProgress.inc = function(amount) {
    var n = NProgress.status;

    if (!n) {
      return NProgress.start();
    } else {
      if (typeof amount !== 'number') {
        amount = (1 - n) * clamp(Math.random() * n, 0.1, 0.95);
      }

      n = clamp(n + amount, 0, 0.994);
      return NProgress.set(n);
    }
  };

  NProgress.trickle = function() {
    return NProgress.inc(Math.random() * Settings.trickleRate);
  };

  /**
   * Waits for all supplied jQuery promises and
   * increases the progress as the promises resolve.
   *
   * @param $promise jQUery Promise
   */
  (function() {
    var initial = 0, current = 0;

    NProgress.promise = function($promise) {
      if (!$promise || $promise.state() == "resolved") {
        return this;
      }

      if (current == 0) {
        NProgress.start();
      }

      initial++;
      current++;

      $promise.always(function() {
        current--;
        if (current == 0) {
            initial = 0;
            NProgress.done();
        } else {
            NProgress.set((initial - current) / initial);
        }
      });

      return this;
    };

  })();

  /**
   * (Internal) renders the progress bar markup based on the `template`
   * setting.
   */

  NProgress.render = function(fromStart) {
    if (NProgress.isRendered()) return document.getElementById('nprogress');

    addClass(document.documentElement, 'nprogress-busy');

    var progress = document.createElement('div');
    progress.id = 'nprogress';
    progress.innerHTML = Settings.template;

    var bar      = progress.querySelector(Settings.barSelector),
        perc     = fromStart ? '-100' : toBarPerc(NProgress.status || 0),
        spinner;

    css(bar, {
      transition: 'all 0 linear',
      transform: 'translate3d(' + perc + '%,0,0)'
    });

    if (!Settings.showSpinner) {
      spinner = progress.querySelector(Settings.spinnerSelector);
      spinner && removeElement(spinner);
    }

    document.body.appendChild(progress);
    return progress;
  };

  /**
   * Removes the element. Opposite of render().
   */

  NProgress.remove = function() {
    removeClass(document.documentElement, 'nprogress-busy');
    var progress = document.getElementById('nprogress');
    progress && removeElement(progress);
  };

  /**
   * Checks if the progress bar is rendered.
   */

  NProgress.isRendered = function() {
    return !!document.getElementById('nprogress');
  };

  /**
   * Determine which positioning CSS rule to use.
   */

  NProgress.getPositioningCSS = function() {
    // Sniff on document.body.style
    var bodyStyle = document.body.style;

    // Sniff prefixes
    var vendorPrefix = ('WebkitTransform' in bodyStyle) ? 'Webkit' :
                       ('MozTransform' in bodyStyle) ? 'Moz' :
                       ('msTransform' in bodyStyle) ? 'ms' :
                       ('OTransform' in bodyStyle) ? 'O' : '';

    if (vendorPrefix + 'Perspective' in bodyStyle) {
      // Modern browsers with 3D support, e.g. Webkit, IE10
      return 'translate3d';
    } else if (vendorPrefix + 'Transform' in bodyStyle) {
      // Browsers without 3D support, e.g. IE9
      return 'translate';
    } else {
      // Browsers without translate() support, e.g. IE7-8
      return 'margin';
    }
  };

  /**
   * Helpers
   */

  function clamp(n, min, max) {
    if (n < min) return min;
    if (n > max) return max;
    return n;
  }

  /**
   * (Internal) converts a percentage (`0..1`) to a bar translateX
   * percentage (`-100%..0%`).
   */

  function toBarPerc(n) {
    return (-1 + n) * 100;
  }

  /**
   * (Internal) returns the correct CSS for changing the bar's
   * position given an n percentage, and speed and ease from Settings
   */

  function barPositionCSS(n, speed, ease) {
    var barCSS;

    if (Settings.positionUsing === 'translate3d') {
      barCSS = { transform: 'translate3d('+toBarPerc(n)+'%,0,0)' };
    } else if (Settings.positionUsing === 'translate') {
      barCSS = { transform: 'translate('+toBarPerc(n)+'%,0)' };
    } else {
      barCSS = { 'margin-left': toBarPerc(n)+'%' };
    }

    barCSS.transition = 'all '+speed+'ms '+ease;

    return barCSS;
  }

  /**
   * (Internal) Queues a function to be executed.
   */

  var queue = (function() {
    var pending = [];

    function next() {
      var fn = pending.shift();
      if (fn) {
        fn(next);
      }
    }

    return function(fn) {
      pending.push(fn);
      if (pending.length == 1) next();
    };
  })();

  /**
   * (Internal) Applies css properties to an element, similar to the jQuery
   * css method.
   *
   * While this helper does assist with vendor prefixed property names, it
   * does not perform any manipulation of values prior to setting styles.
   */

  var css = (function() {
    var cssPrefixes = [ 'Webkit', 'O', 'Moz', 'ms' ],
        cssProps    = {};

    function camelCase(string) {
      return string.replace(/^-ms-/, 'ms-').replace(/-([\da-z])/gi, function(match, letter) {
        return letter.toUpperCase();
      });
    }

    function getVendorProp(name) {
      var style = document.body.style;
      if (name in style) return name;

      var i = cssPrefixes.length,
          capName = name.charAt(0).toUpperCase() + name.slice(1),
          vendorName;
      while (i--) {
        vendorName = cssPrefixes[i] + capName;
        if (vendorName in style) return vendorName;
      }

      return name;
    }

    function getStyleProp(name) {
      name = camelCase(name);
      return cssProps[name] || (cssProps[name] = getVendorProp(name));
    }

    function applyCss(element, prop, value) {
      prop = getStyleProp(prop);
      element.style[prop] = value;
    }

    return function(element, properties) {
      var args = arguments,
          prop,
          value;

      if (args.length == 2) {
        for (prop in properties) {
          value = properties[prop];
          if (value !== undefined && properties.hasOwnProperty(prop)) applyCss(element, prop, value);
        }
      } else {
        applyCss(element, args[1], args[2]);
      }
    }
  })();

  /**
   * (Internal) Determines if an element or space separated list of class names contains a class name.
   */

  function hasClass(element, name) {
    var list = typeof element == 'string' ? element : classList(element);
    return list.indexOf(' ' + name + ' ') >= 0;
  }

  /**
   * (Internal) Adds a class to an element.
   */

  function addClass(element, name) {
    var oldList = classList(element),
        newList = oldList + name;

    if (hasClass(oldList, name)) return;

    // Trim the opening space.
    element.className = newList.substring(1);
  }

  /**
   * (Internal) Removes a class from an element.
   */

  function removeClass(element, name) {
    var oldList = classList(element),
        newList;

    if (!hasClass(element, name)) return;

    // Replace the class name.
    newList = oldList.replace(' ' + name + ' ', ' ');

    // Trim the opening and closing spaces.
    element.className = newList.substring(1, newList.length - 1);
  }

  /**
   * (Internal) Gets a space separated list of the class names on the element.
   * The list is wrapped with a single space on each end to facilitate finding
   * matches within the list.
   */

  function classList(element) {
    return (' ' + (element.className || '') + ' ').replace(/\s+/gi, ' ');
  }

  /**
   * (Internal) Removes an element from the DOM.
   */

  function removeElement(element) {
    element && element.parentNode && element.parentNode.removeChild(element);
  }

  return NProgress;
});

<|endoftext|>


<commit_before>var locked = false;

jQuery(document).ready(function () {
    initTree();

    fillForms();

    // Scroll to the tree div
    $('html, body').animate({
        scrollTop: $('.tree-container').offset().top
    }, 'slow');
});

var showPerson = function (url) {
    console.log('url: ' + url);

    var param = '&ajax=1';
    var ajaxUrl = (url.indexOf(param) === -1) ? url + param : url;
    var cleanUrl = url.replace(new RegExp(param + '$'), '');

    $('#tree-loader').show();
    $('#genealogy-tree').html('');

    lockLinks();

    console.log('ajaxUrl: ' + ajaxUrl);
    $.ajax(ajaxUrl)
            .done(function (response) {
                $('#tree-holder').html(response);
                initTree();

                window.history.pushState(
                        {url: cleanUrl},
                        document.title,
                        cleanUrl
                        );

                $('#tree-loader').hide();

                releaseLinks();
            })
            .fail(function (xhr) {
                alert('Error: ' + xhr.responseText);
            });
};

/**
 *
 * @param {type} url
 * @returns {undefined}
 */
var updateInfo = function (url) {
    var param = '&ajax=1';
    var ajaxUrl = (url.indexOf(param) === -1) ? url + param : url;

    $('#info-loader').show();
    $('#info-body').html('');
    lockLinks();

    $.ajax(ajaxUrl)
            .done(function (response) {
                $("#panel-info").html(response);
                registerLinks();
                $('#info-loader').hide();
                $('#collapse-info-btn').trigger('click');

                releaseLinks();
            })
            .fail(function (xhr) {
                alert('Error: ' + xhr.responseText);
            });
};

var initTree = function () {
    $("#genealogy-relations").jOrgChart({
        chartElement: '#genealogy-tree'
    });

    registerLinks();
    $('#genealogy-tree').dragScroll({});

    window.onpopstate = function (e) {
        console.log('e: ' + e);
        if (e.state.url) {
            console.log('onpopstate: ' + e.state.url);
            showPerson(e.state.url);
        } else {
            e.preventDefault();
        }
    };
};

var fillForms = function () {
    url = $(location).attr('href');
    var uri = URI(url);
    console.log(uri.toString());

    var params = uri.search(true);
    console.log(params);

    $('input.options-check').each(function () {
        id = $(this).attr('id');
        status = params[id];
        $(this).prop('checked', status == 1 ? true : false);
    });

};

var registerLinks = function () {
    $("a.info-item").click(function (event) {
        event.preventDefault();

        if (locked) {
            return;
        }

        url = $(this).attr('data-url');
        updateInfo(url);
    });

    $("a.options-item").click(function (event) {
        event.preventDefault();

        if (locked) {
            return;
        }

        url = $(this).attr('href');
        showPerson(url);
    });

    // Full-screen link
    $('#toggle-fullscreen').on('click', function () {
        event.preventDefault();
        if (locked) {
            return;
        }

        $('.tree-container').toggleFullScreen();

    });

    $('input[type=checkbox]#f').change(function () {
        event.preventDefault();
        if (!this.checked) {
            $('input#fs').prop('checked', false);
        }
    });

    $('input[type=checkbox]#fs').change(function () {
        event.preventDefault();
        if (this.checked) {
            $('input#f').prop('checked', true);
        }
    });

    $('input[type=checkbox]#m').change(function () {
        event.preventDefault();
        if (!this.checked) {
            $('input#ms').prop('checked', false);
        }
    });

    $('input[type=checkbox]#ms').change(function () {
        event.preventDefault();
        if (this.checked) {
            $('input#m').prop('checked', true);
        }
    });

    $('input.options-check').change(function () {
        event.preventDefault();
        if (locked) {
            return;
        }

        url = $(location).attr('href');
        var uri = URI(url);

        var params = {};
        $('input[type=checkbox].options-check').each(function () {
            id = $(this).attr('id');
            value = this.checked ? 1 : 0;
            params[id] = value;
        });
        uri.setSearch(params);

        showPerson(uri.toString());
    });
};

var lockLinks = function () {
    $('a.info-item, a.options-item, #toggle-fullscreen, input.options-check').attr('disabled', true);
    locked = true;
};

var releaseLinks = function () {
    locked = false;
    $('a.info-item, a.options-item, #toggle-fullscreen, input.options-check').attr('disabled', false);
};<commit_msg>- Fixed minor bug<commit_after>var locked = false;

jQuery(document).ready(function () {
    localStorage.setItem("myvar", "Smith");
    initTree();

    initFilters();

    // Scroll to the tree div
    $('html, body').animate({
        scrollTop: $('.tree-container').offset().top
    }, 'slow');
});

var showPerson = function (url) {
    url = appendFilters(url);

    var param = '&ajax=1';
    var ajaxUrl = (url.indexOf(param) === -1) ? url + param : url;
    var cleanUrl = url.replace(new RegExp(param + '$'), '');

    $('#tree-loader').show();
    $('#genealogy-tree').html('');

    lockLinks();

    $.ajax(ajaxUrl)
            .done(function (response) {
                $('#tree-holder').html(response);
                initTree();

                window.history.pushState(
                        {url: cleanUrl},
                        document.title,
                        cleanUrl
                        );

                $('#tree-loader').hide();

                releaseLinks();
            })
            .fail(function (xhr) {
                alert('Error: ' + xhr.responseText);
            });
};

/**
 *
 * @param {type} url
 * @returns {undefined}
 */
var updateInfo = function (url) {
    var param = '&ajax=1';
    var ajaxUrl = (url.indexOf(param) === -1) ? url + param : url;

    $('#info-loader').show();
    $('#info-body').html('');
    lockLinks();

    $.ajax(ajaxUrl)
            .done(function (response) {
                $("#panel-info").html(response);
                registerLinks();
                $('#info-loader').hide();
                $('#collapse-info-btn').trigger('click');

                releaseLinks();
            })
            .fail(function (xhr) {
                alert('Error: ' + xhr.responseText);
            });
};

var initTree = function () {
    $("#genealogy-relations").jOrgChart({
        chartElement: '#genealogy-tree'
    });

    registerLinks();
    $('#genealogy-tree').dragScroll({});

    window.onpopstate = function (e) {
        console.log('e: ' + e);
        if (e.state.url) {
            console.log('onpopstate: ' + e.state.url);
            showPerson(e.state.url);
        } else {
            e.preventDefault();
        }
    };
};

var initFilters = function () {
    url = $(location).attr('href');
    var uri = URI(url);

    var params = uri.search(true);
    if (!params['m']) {
        params['m'] = 1;
    }

    if (!params['ms']) {
        params['ms'] = 1;
    }

    $('input.options-check').each(function () {
        id = $(this).attr('id');
        status = params[id];
        $(this).prop('checked', status == 1 ? true : false);
    });

};

var appendFilters = function (url) {
    var uri = URI(url);
    localStorage.setItem("myvar", "Smith");

    var params = {};
    $('input[type=checkbox].options-check').each(function () {
        id = $(this).attr('id');
        value = this.checked ? 1 : 0;

        params[id] = value;
    });
    uri.setSearch(params);

    return uri.toString();
};

var lockLinks = function () {
    $('a.info-item, a.options-item, #toggle-fullscreen, input.options-check').attr('disabled', true);
    locked = true;
};

var releaseLinks = function () {
    locked = false;
    $('a.info-item, a.options-item, #toggle-fullscreen, input.options-check').attr('disabled', false);
};

var registerLinks = function () {
    $("a.info-item").click(function (event) {
        event.preventDefault();

        if (locked) {
            return;
        }

        url = $(this).attr('data-url');
        updateInfo(url);
    });

    $("a.options-item").click(function (event) {
        event.preventDefault();

        if (locked) {
            return;
        }

        url = $(this).attr('href');
        showPerson(url);
    });

    // Full-screen link
    $('#toggle-fullscreen').on('click', function () {
        event.preventDefault();
        if (locked) {
            return;
        }

        $('.tree-container').toggleFullScreen();

    });

    $('input[type=checkbox]#f').change(function () {
        event.preventDefault();
        if (!this.checked) {
            $('input#fs').prop('checked', false);
        }
    });

    $('input[type=checkbox]#fs').change(function () {
        event.preventDefault();
        if (this.checked) {
            $('input#f').prop('checked', true);
        }
    });

    $('input[type=checkbox]#m').change(function () {
        event.preventDefault();
        if (!this.checked) {
            $('input#ms').prop('checked', false);
        }
    });

    $('input[type=checkbox]#ms').change(function () {
        event.preventDefault();
        if (this.checked) {
            $('input#m').prop('checked', true);
        }
    });

    $('input.options-check').change(function () {
        event.preventDefault();
        if (locked) {
            return;
        }

        url = $(location).attr('href');
//        var uri = appendFilters(url);
//        var uri = URI(url);
//
//        var params = {};
//        $('input[type=checkbox].options-check').each(function () {
//            id = $(this).attr('id');
//            value = this.checked ? 1 : 0;
//            params[id] = value;
//        });
//        uri.setSearch(params);

//        showPerson(uri.toString());
        showPerson(url);
    });
};
<|endoftext|>


<commit_before>var DS = require('./datasource.js');
var makeDataFrame = require('./dataframe.js').makeDataFrame;

module.exports.dataSource = DS.makeDataSource(
  'police-uk', // name

  "#Police-uk\n" +
  "This sources return the monthly crime statistiques for a given localisation.\n" +

  "##getData parameters\n" +
  "In addition to the mandatory (from, to) time parameters, getData takes two\n" +
  "parameters for the localisation of the crime statistic: latitude and\n" +
  "longitude GPS coordinates.\n" +

  "##returned data format\n" +
  "The source returns a dataframe per month. The date attribute of the frame is\n" +
  "set to the first day of the month, and the data attribute carries an object.\n" +
  "This object has a field of each crime type (eg. `antisocial-behaviour` or \n" +
  "`bike-theft`), and the field's value is the monthly arrest count for this crime.",

  function hasNewsSince(date) {
    // TODO use http://data.police.uk/api/crime-last-updated and compare date to
    // the returned timestamp
    var threshold = new Date('2014-05-01');
    return date > threshold;
  },

  function getData(from, to, lat, lng) {
    // let currDate be the 1st of current month if day <= 15, 1st of next month
    // otherwise
    var currDate = from;
    if (currDate.getDay() <= 15) {
      currDate.setDate(1);
    }
    else {
      currDate.setDate(32) // will go to 1st of next month
    }

    var crimeArray = new Array();
    var baseQuery =
        "http://data.police.uk/api/crimes-street/all-crime?lat=" + lat + "&lng=" + lng;

    while (currDate <= to) {
      var currMonth = currDate.getMonth() + 1; // months start at 0 ¬_¬
      currMonth = currMonth > 9 ? String(currMonth) : '0' + String(currMonth);
      var timeQuery = "&date=" + currDate.getFullYear() + "-" + currMonth;

      var data = crimeQuery(baseQuery + timeQuery);
      crimeArray.push(makeDataFrame(currDate, data));

      currDate.setMonth(currDate.getMonth() + 1); // go to the next dataframe
    }

    return crimeArray;
  }
);

function crimeQuery(path_json, crimeArrayIndex) {
  var monthCrimeStat = {};

  $.ajax({
    url: path_json,
    async: false,
    success: process(result)
  });

  function process(data) {
    for(var i = 0; i < data.length; i++) {
      if (!(data[i].category in crime)) {
        monthCrimeStat[data[i].category] = 0; // 1st crime seen for this category
      }
      monthCrimeStat[data[i].category] += 1;
    }
  };

  return monthCrimeStat;
}

<commit_msg>datasource-police-uk: is asynchronous; actually works.<commit_after>var DS = require('./datasource.js');
var makeDataFrame = require('./dataframe.js').makeDataFrame;
var sync = require('synchronize');
var getTheFuckingJSON = require('./utils.js').getTheFuckingJSON;

module.exports.dataSource = DS.makeDataSource(
  'police-uk', // name

  "#Police-uk\n" +
  "This sources return the monthly crime statistiques for a given localisation.\n" +

  "##getData parameters\n" +
  "In addition to the mandatory (from, to) time parameters, getData takes two\n" +
  "parameters for the localisation of the crime statistic: latitude and\n" +
  "longitude GPS coordinates.\n" +

  "##returned data format\n" +
  "The source returns a dataframe per month. The date attribute of the frame is\n" +
  "set to the first day of the month, and the data attribute carries an object.\n" +
  "This object has a field of each crime type (eg. `antisocial-behaviour` or \n" +
  "`bike-theft`), and the field's value is the monthly arrest count for this crime.",

  function hasNewsSince(date) {
    // TODO use http://data.police.uk/api/crime-last-updated and compare date to
    // the returned timestamp
    var threshold = new Date('2014-05-01');
    return date > threshold;
  },

  function getData(from, to, lat, lng, callback) {
    // let currDate be the 1st of current month if day <= 15, 1st of next month
    // otherwise
    var currDate = from;
    if (currDate.getDay() <= 15) {
      currDate.setDate(1);
    }
    else {
      currDate.setDate(32) // will go to 1st of next month
    }

    var crimeArray = new Array();
    var baseQuery =
        "http://data.police.uk/api/crimes-street/all-crime?lat=" + lat + "&lng=" + lng;

    sync.fiber(function() {
      while (currDate <= to) {
        var currMonth = currDate.getMonth() + 1; // months start at 0 ¬_¬
        currMonth = currMonth > 9 ? String(currMonth) : '0' + String(currMonth);
        var timeQuery = "&date=" + currDate.getFullYear() + "-" + currMonth;

        console.log('police-uk: fetching data for ' + timeQuery);
        try {
          var data = sync.await(crimeQuery(baseQuery + timeQuery, sync.defer()));
          crimeArray.push(makeDataFrame(new Date(currDate), data));
        }
        catch(e) {
          console.log('caught exception while fetching data for ' + currDate +
            ', skipping to next month');
        }
        currDate.setMonth(currDate.getMonth() + 1); // go to the next dataframe
      }
      callback(crimeArray);
    });
  }
);

function crimeQuery(path_json, callback) {
  getTheFuckingJSON(path_json, process);

  function process(err, json) {
    if (err) {
      callback(err);
      return;
    }

    var data = JSON.parse(json);
    var monthCrimeStat = {};
    for(var i = 0; i < data.length; i++) {
      if (!(data[i].category in monthCrimeStat)) {
        monthCrimeStat[data[i].category] = 0; // 1st crime seen for this category
      }
      monthCrimeStat[data[i].category] += 1;
    }
    callback(undefined, monthCrimeStat);
  };
}

<|endoftext|>