<commit_before>/*
 * Copyright (c) 2017 Sebastian Rager
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

const EventEmitter = require('events');
const debug = require('debug')('zyre:zyre_peer');
const zeromq = require('zeromq');
const ZreMsg = require('./zre_msg');

const PEER_EVASIVE = 5000;
const PEER_EXPIRED = 10000;

const ID_PREFIX = 1;

/**
 * ZyrePeer represents a foreign peer in the network
 *
 * @extends EventEmitter
 */
class ZyrePeer extends EventEmitter {

  /**
   * @param {Object} options - Options Object
   * @param {string} options.identity - Identity of the peer
   * @param {Buffer} options.originID - 16 byte UUID as Buffer
   */
  constructor({ identity, originID }) {
    super();

    this._identity = identity;
    this._originID = originID;
    this._sequenceIn = 0;
    this._sequenceOut = 0;
    this._groups = {};
    this._connected = false;
    this._evasiveAt = 0;
  }

  /**
   * @return {string} Identity of the peer
   */
  getIdentity() {
    return this._identity;
  }

  /**
   * @return {string} Name of the peer
   */
  getName() {
    return this._name;
  }

  /**
   * @return {number} Sequence of the last received message
   */
  getSequence() {
    return this._sequenceIn;
  }

  /**
   * Adds this ZyrePeer to a given ZyreGroup
   *
   * @param {ZyreGroup} group - ZyreGroup
   */
  addToGroup(group) {
    if (typeof this._groups[group.getName()] === 'undefined') {
      this._groups[group.getName()] = group;
      group.add(this);
    }
  }

  /**
   * Removes this ZyrePeer from a given ZyreGroup
   *
   * @param {ZyreGroup} group - ZyreGroup
   */
  removeFromGroup(group) {
    if (typeof this._groups[group.getName()] !== 'undefined') {
      delete this._groups[group.getName()];
      group.remove(this);
    }
  }

  /**
   * Connects to this ZyrePeer
   */
  connect() {
    if (!this._connected) {
      this._socket = zeromq.socket('dealer', {
        identity: Buffer.concat([Buffer.from([ID_PREFIX]), this._originID]),
      });

      this._socket.setsockopt(zeromq.ZMQ_LINGER, 0);
      this._socket.setsockopt(zeromq.ZMQ_SNDHWM, PEER_EXPIRED / 10);
      this._socket.setsockopt(zeromq.ZMQ_SNDTIMEO, 0);

      this._socket.connect(this._endpoint);
      this._connected = true;
    }

    debug(`${this._identity}: connected`);
  }

  /**
   * Disconnects from this ZyrePeer and stops every activity
   */
  disconnect() {
    this._clearTimeouts();

    for (const i in this._groups) {
      if ({}.hasOwnProperty.call(this._groups, i)) {
        this.removeFromGroup(this._groups[i]);
      }
    }

    if (this._connected) {
      this._socket.disconnect(this._endpoint);
      this._socket.close();
      this._connected = false;
    }

    debug(`${this._identity}: disconnected`);
  }

  /**
   * Sends a ZreMsg to this ZyrePeer
   *
   * @param {ZreMsg} msg - ZreMsg
   */
  send(msg) {
    if (this._connected) {
      this._sequenceOut = (this._sequenceOut + 1) % 65535;
      msg.setSequence(this._sequenceOut);
      msg.send(this._socket).then((cmd) => {
        debug(`${this._identity}: sent message (${cmd}), seq (${this._sequenceOut})`);
      });
    }
  }

  /**
   * Updates the data of this ZyrePeer, manages timeouts for evasive and expired
   *
   * @fires ZyrePeer#disconnect
   * @fires ZyrePeer#back
   * @fires ZyrePeer#evasive
   * @fires ZyrePeer#expired
   * @param {Object} options - Options Object
   * @param {number} [options.sequence] - Sequence of the last received message
   * @param {string} [options.address] - IP of the peer
   * @param {number} [options.mailbox] - Network port of the peer
   * @param {string} [options.endpoint] - TCP address of the peer
   * @param {number} [options.status] - Group status of the peer
   * @param {string} [options.name] - Name of the peer
   * @param {Object} [options.headers] - Headers of the peer
   * @return {ZyrePeer}
   */
  update({ sequence, address, mailbox, endpoint, status, name, headers }) {
    if (typeof sequence !== 'undefined') {
      // Disconnect on wrong sequence number
      const expectedSeq = (this._sequenceIn + 1) % 65535;
      if (sequence !== expectedSeq) {
        debug(`${this._identity}: wrong sequence (${sequence}), expected (${expectedSeq})`);
        /**
         * @event ZyrePeer#disconnect
         * @property {ZyrePeer} zyrePeer - ZyrePeer
         */
        this.emit('disconnect', this);
        return undefined;
      }

      this._sequenceIn = sequence;
    }

    if (typeof address !== 'undefined' && typeof mailbox !== 'undefined') {
      // If received a message with mailbox === 0, disconnect from the peer (zre beacon protocol)
      if (mailbox === 0) {
        debug(`${this._identity}: received disconnect beacon`);
        /**
         * @event ZyrePeer#disconnect
         * @property {ZyrePeer} zyrePeer - ZyrePeer
         */
        this.emit('disconnect', this);
        return undefined;
      }

      this._endpoint = `tcp://${address}:${mailbox}`;
    } else if (typeof endpoint !== 'undefined') {
      this._endpoint = endpoint;
    }

    if (typeof status !== 'undefined') this._status = status;
    if (typeof name !== 'undefined') this._name = name;
    if (typeof headers !== 'undefined') this._headers = headers;

    if (this._evasiveAt > 0) {
      this._evasiveAt = 0;
      debug(`${this._identity}: back from being evasive`);
      /**
       * @event ZyrePeer#back
       * @property {ZyrePeer} zyrePeer - ZyrePeer
       */
      this.emit('back', this);
    }

    this._clearTimeouts();
    this._setTimeouts();

    return this;
  }

  /**
   * Sets timeouts for evasive and expired
   *
   * @protected
   */
  _setTimeouts() {
    this._evasiveTimeout = setTimeout(() => {
      this._evasiveAt = Date.now();
      debug(`${this._identity}: evasive at ${this._evasiveAt}`);
      /**
       * @event ZyrePeer#evasive
       * @property {ZyrePeer} zyrePeer - ZyrePeer
       */
      this.emit('evasive', this);

      this.send(new ZreMsg(ZreMsg.PING));
    }, PEER_EVASIVE);

    this._expiredTimeout = setTimeout(() => {
      debug(`${this._identity}: expired at ${Date.now()}`);
      /**
       * @event ZyrePeer#expired
       * @property {ZyrePeer} zyrePeer - ZyrePeer
       */
      this.emit('expired', this);
    }, PEER_EXPIRED);
  }

  /**
   * Clears the evasive and expired timeouts
   *
   * @protected
   */
  _clearTimeouts() {
    clearTimeout(this._evasiveTimeout);
    clearTimeout(this._expiredTimeout);
  }

  /**
   * @typedef {Object} PeerObject
   * @property {string} name
   * @property {string} endpoint
   * @property {Object} headers
   * @property {string[]} groups
   */

  /**
   * Creates an object with public data of this peer
   *
   * @return {PeerObject}
   */
  toObj() {
    const obj = {};
    obj.name = this._name;
    obj.endpoint = this._endpoint;
    obj.evasive = this._evasiveAt > 0;
    obj.headers = this._headers;
    obj.groups = [];
    for (const i in this._groups) {
      if ({}.hasOwnProperty.call(this._groups, i)) {
        obj.groups.push(i);
      }
    }

    return obj;
  }
}

ZyrePeer.PEER_EVASIVE = PEER_EVASIVE;
ZyrePeer.PEER_EXPIRED = PEER_EXPIRED;

module.exports = ZyrePeer;
<commit_msg>Increase expired timeout to 30s<commit_after>/*
 * Copyright (c) 2017 Sebastian Rager
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

const EventEmitter = require('events');
const debug = require('debug')('zyre:zyre_peer');
const zeromq = require('zeromq');
const ZreMsg = require('./zre_msg');

const PEER_EVASIVE = 5000;
const PEER_EXPIRED = 30000;

const ID_PREFIX = 1;

/**
 * ZyrePeer represents a foreign peer in the network
 *
 * @extends EventEmitter
 */
class ZyrePeer extends EventEmitter {

  /**
   * @param {Object} options - Options Object
   * @param {string} options.identity - Identity of the peer
   * @param {Buffer} options.originID - 16 byte UUID as Buffer
   */
  constructor({ identity, originID }) {
    super();

    this._identity = identity;
    this._originID = originID;
    this._sequenceIn = 0;
    this._sequenceOut = 0;
    this._groups = {};
    this._connected = false;
    this._evasiveAt = 0;
  }

  /**
   * @return {string} Identity of the peer
   */
  getIdentity() {
    return this._identity;
  }

  /**
   * @return {string} Name of the peer
   */
  getName() {
    return this._name;
  }

  /**
   * @return {number} Sequence of the last received message
   */
  getSequence() {
    return this._sequenceIn;
  }

  /**
   * Adds this ZyrePeer to a given ZyreGroup
   *
   * @param {ZyreGroup} group - ZyreGroup
   */
  addToGroup(group) {
    if (typeof this._groups[group.getName()] === 'undefined') {
      this._groups[group.getName()] = group;
      group.add(this);
    }
  }

  /**
   * Removes this ZyrePeer from a given ZyreGroup
   *
   * @param {ZyreGroup} group - ZyreGroup
   */
  removeFromGroup(group) {
    if (typeof this._groups[group.getName()] !== 'undefined') {
      delete this._groups[group.getName()];
      group.remove(this);
    }
  }

  /**
   * Connects to this ZyrePeer
   */
  connect() {
    if (!this._connected) {
      this._socket = zeromq.socket('dealer', {
        identity: Buffer.concat([Buffer.from([ID_PREFIX]), this._originID]),
      });

      this._socket.setsockopt(zeromq.ZMQ_LINGER, 0);
      this._socket.setsockopt(zeromq.ZMQ_SNDHWM, PEER_EXPIRED / 10);
      this._socket.setsockopt(zeromq.ZMQ_SNDTIMEO, 0);

      this._socket.connect(this._endpoint);
      this._connected = true;
    }

    debug(`${this._identity}: connected`);
  }

  /**
   * Disconnects from this ZyrePeer and stops every activity
   */
  disconnect() {
    this._clearTimeouts();

    for (const i in this._groups) {
      if ({}.hasOwnProperty.call(this._groups, i)) {
        this.removeFromGroup(this._groups[i]);
      }
    }

    if (this._connected) {
      this._socket.disconnect(this._endpoint);
      this._socket.close();
      this._connected = false;
    }

    debug(`${this._identity}: disconnected`);
  }

  /**
   * Sends a ZreMsg to this ZyrePeer
   *
   * @param {ZreMsg} msg - ZreMsg
   */
  send(msg) {
    if (this._connected) {
      this._sequenceOut = (this._sequenceOut + 1) % 65535;
      msg.setSequence(this._sequenceOut);
      msg.send(this._socket).then((cmd) => {
        debug(`${this._identity}: sent message (${cmd}), seq (${this._sequenceOut})`);
      });
    }
  }

  /**
   * Updates the data of this ZyrePeer, manages timeouts for evasive and expired
   *
   * @fires ZyrePeer#disconnect
   * @fires ZyrePeer#back
   * @fires ZyrePeer#evasive
   * @fires ZyrePeer#expired
   * @param {Object} options - Options Object
   * @param {number} [options.sequence] - Sequence of the last received message
   * @param {string} [options.address] - IP of the peer
   * @param {number} [options.mailbox] - Network port of the peer
   * @param {string} [options.endpoint] - TCP address of the peer
   * @param {number} [options.status] - Group status of the peer
   * @param {string} [options.name] - Name of the peer
   * @param {Object} [options.headers] - Headers of the peer
   * @return {ZyrePeer}
   */
  update({ sequence, address, mailbox, endpoint, status, name, headers }) {
    if (typeof sequence !== 'undefined') {
      // Disconnect on wrong sequence number
      const expectedSeq = (this._sequenceIn + 1) % 65535;
      if (sequence !== expectedSeq) {
        debug(`${this._identity}: wrong sequence (${sequence}), expected (${expectedSeq})`);
        /**
         * @event ZyrePeer#disconnect
         * @property {ZyrePeer} zyrePeer - ZyrePeer
         */
        this.emit('disconnect', this);
        return undefined;
      }

      this._sequenceIn = sequence;
    }

    if (typeof address !== 'undefined' && typeof mailbox !== 'undefined') {
      // If received a message with mailbox === 0, disconnect from the peer (zre beacon protocol)
      if (mailbox === 0) {
        debug(`${this._identity}: received disconnect beacon`);
        /**
         * @event ZyrePeer#disconnect
         * @property {ZyrePeer} zyrePeer - ZyrePeer
         */
        this.emit('disconnect', this);
        return undefined;
      }

      this._endpoint = `tcp://${address}:${mailbox}`;
    } else if (typeof endpoint !== 'undefined') {
      this._endpoint = endpoint;
    }

    if (typeof status !== 'undefined') this._status = status;
    if (typeof name !== 'undefined') this._name = name;
    if (typeof headers !== 'undefined') this._headers = headers;

    if (this._evasiveAt > 0) {
      this._evasiveAt = 0;
      debug(`${this._identity}: back from being evasive`);
      /**
       * @event ZyrePeer#back
       * @property {ZyrePeer} zyrePeer - ZyrePeer
       */
      this.emit('back', this);
    }

    this._clearTimeouts();
    this._setTimeouts();

    return this;
  }

  /**
   * Sets timeouts for evasive and expired
   *
   * @protected
   */
  _setTimeouts() {
    this._evasiveTimeout = setTimeout(() => {
      this._evasiveAt = Date.now();
      debug(`${this._identity}: evasive at ${this._evasiveAt}`);
      /**
       * @event ZyrePeer#evasive
       * @property {ZyrePeer} zyrePeer - ZyrePeer
       */
      this.emit('evasive', this);

      this.send(new ZreMsg(ZreMsg.PING));
    }, PEER_EVASIVE);

    this._expiredTimeout = setTimeout(() => {
      debug(`${this._identity}: expired at ${Date.now()}`);
      /**
       * @event ZyrePeer#expired
       * @property {ZyrePeer} zyrePeer - ZyrePeer
       */
      this.emit('expired', this);
    }, PEER_EXPIRED);
  }

  /**
   * Clears the evasive and expired timeouts
   *
   * @protected
   */
  _clearTimeouts() {
    clearTimeout(this._evasiveTimeout);
    clearTimeout(this._expiredTimeout);
  }

  /**
   * @typedef {Object} PeerObject
   * @property {string} name
   * @property {string} endpoint
   * @property {Object} headers
   * @property {string[]} groups
   */

  /**
   * Creates an object with public data of this peer
   *
   * @return {PeerObject}
   */
  toObj() {
    const obj = {};
    obj.name = this._name;
    obj.endpoint = this._endpoint;
    obj.evasive = this._evasiveAt > 0;
    obj.headers = this._headers;
    obj.groups = [];
    for (const i in this._groups) {
      if ({}.hasOwnProperty.call(this._groups, i)) {
        obj.groups.push(i);
      }
    }

    return obj;
  }
}

ZyrePeer.PEER_EVASIVE = PEER_EVASIVE;
ZyrePeer.PEER_EXPIRED = PEER_EXPIRED;

module.exports = ZyrePeer;
<|endoftext|>


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

define([
  'text!./success.html',
  'pentaho/i18n-osgi!connections.messages',
  'css!./success.css'
], function (template, i18n) {

  'use strict';

  var options = {
    bindings: {},
    controllerAs: "vm",
    template: template,
    controller: successController
  };

  successController.$inject = ["$state", "$stateParams"];

  function successController($state, $stateParams) {
    var vm = this;
    vm.$onInit = onInit;
    vm.onCreateNew = onCreateNew;
    vm.onEditConnection = onEditConnection;

    function onInit() {
      vm.data = $stateParams.data;
      vm.congratulationsLabel = i18n.get('connections.final.congratulationsLabel');
      vm.ready = !vm.data.isSaved ? i18n.get('connections.final.readyCreate') : i18n.get('connections.final.readyUpdated');
      vm.question = i18n.get('connections.final.question');
      vm.createNewConnection = i18n.get('connections.final.createNewConnection');
      vm.editConnection = i18n.get('connections.final.editConnection');
      vm.closeLabel = i18n.get('connections.final.closeLabel');
      vm.data.isSaved = true;
      vm.buttons = getButtons();
    }

    function onCreateNew() {
      $state.go("intro");
    }

    function onEditConnection() {
      vm.data.state = "edit";
      setDialogTitle(i18n.get('connections.intro.edit.label'));
      $state.go(vm.data.model.type + "step1", {data: vm.data, transition: "slideRight"});
    }

    function getButtons() {
      return [{
        label: i18n.get('connections.controls.closeLabel'),
        class: "primary",
        position: "right",
        onClick: function() {
          close();
        }
      }];
    }

    function setDialogTitle(title) {
      try {
        setTitle(title);
      } catch (e) {
        console.log(title);
      }
    }
  }

  return {
    name: "success",
    options: options
  };

});
<commit_msg>[BACKLOG-27694] When VFS connection created edit goes to summary screen<commit_after>/*!
 * Copyright 2019 Hitachi Vantara. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

define([
  'text!./success.html',
  'pentaho/i18n-osgi!connections.messages',
  'css!./success.css'
], function (template, i18n) {

  'use strict';

  var options = {
    bindings: {},
    controllerAs: "vm",
    template: template,
    controller: successController
  };

  successController.$inject = ["$state", "$stateParams"];

  function successController($state, $stateParams) {
    var vm = this;
    vm.$onInit = onInit;
    vm.onCreateNew = onCreateNew;
    vm.onEditConnection = onEditConnection;

    function onInit() {
      vm.data = $stateParams.data;
      vm.congratulationsLabel = i18n.get('connections.final.congratulationsLabel');
      vm.ready = !vm.data.isSaved ? i18n.get('connections.final.readyCreate') : i18n.get('connections.final.readyUpdated');
      vm.question = i18n.get('connections.final.question');
      vm.createNewConnection = i18n.get('connections.final.createNewConnection');
      vm.editConnection = i18n.get('connections.final.editConnection');
      vm.closeLabel = i18n.get('connections.final.closeLabel');
      vm.data.isSaved = true;
      vm.buttons = getButtons();
    }

    function onCreateNew() {
      $state.go("intro");
    }

    function onEditConnection() {
      vm.data.state = "edit";
      setDialogTitle(i18n.get('connections.intro.edit.label'));
      $state.go("summary", {data: vm.data, transition: "slideRight"});
    }

    function getButtons() {
      return [{
        label: i18n.get('connections.controls.closeLabel'),
        class: "primary",
        position: "right",
        onClick: function() {
          close();
        }
      }];
    }

    function setDialogTitle(title) {
      try {
        setTitle(title);
      } catch (e) {
        console.log(title);
      }
    }
  }

  return {
    name: "success",
    options: options
  };

});
<|endoftext|>


<commit_before>/*
 * Loading screen Controller
 */

define([], function () {

    var Controller = Em.Controller.extend({

      load: function () {
        var self = this;

        self.set('serviceStatuses', []);

        /**
         * Check if all services have been loaded periodically and transition page
         * if everything is loaded.
         */
        this.interval = setInterval(function() {
          self.HTTP.rest('system/services/status', function (statuses) {
            self.set('statuses', statuses);
            if (!statuses) {
              $(".warning-text").text('Could not get core Reactor services. Please restart Reactor.');
              return;
            }

            var serviceStatuses = [];
            if (Object.prototype.toString.call(statuses) === '[object Array]') {
              for (item in statuses) {
                if (statuses.hasOwnProperty(item)) {
                  var imgSrc = statuses[item] === 'OK' ? 'complete' : 'loading';
                  serviceStatuses.push({
                    name: item,
                    status: statuses[item],
                    imgClass: imgSrc
                  });
                }
              }
            }

            self.set('serviceStatuses', serviceStatuses);

            if (C.Util.isLoadingComplete(statuses)) {
              setTimeout(function() {
                clearInterval(self.interval);
                $("#warning").hide();
                self.transitionToRoute('Overview');
              }, 500);
            }

          });
        }, 1000);
      },

      unload: function () {
        clearInterval(this.interval);
      }

    });

    Controller.reopenClass({
      type: 'Loading',
      kind: 'Controller'
    });

    return Controller;

});
<commit_msg>fix mistake<commit_after>/*
 * Loading screen Controller
 */

define([], function () {

    var Controller = Em.Controller.extend({

      load: function () {
        var self = this;

        self.set('serviceStatuses', []);

        /**
         * Check if all services have been loaded periodically and transition page
         * if everything is loaded.
         */
        this.interval = setInterval(function() {
          self.HTTP.rest('system/services/status', function (statuses) {
            self.set('statuses', statuses);
            if (!statuses) {
              $(".warning-text").text('Could not get core Reactor services. Please restart Reactor.');
              return;
            }

            var serviceStatuses = [];
            if (Object.prototype.toString.call(statuses) === '[object Object]') {
              for (item in statuses) {
                if (statuses.hasOwnProperty(item)) {
                  var imgSrc = statuses[item] === 'OK' ? 'complete' : 'loading';
                  serviceStatuses.push({
                    name: item,
                    status: statuses[item],
                    imgClass: imgSrc
                  });
                }
              }
            }

            self.set('serviceStatuses', serviceStatuses);

            if (C.Util.isLoadingComplete(statuses)) {
              setTimeout(function() {
                clearInterval(self.interval);
                $("#warning").hide();
                self.transitionToRoute('Overview');
              }, 500);
            }

          });
        }, 1000);
      },

      unload: function () {
        clearInterval(this.interval);
      }

    });

    Controller.reopenClass({
      type: 'Loading',
      kind: 'Controller'
    });

    return Controller;

});
<|endoftext|>


<commit_before>;(function() {
  'use strict';

function httpPrefix() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attrs, controller) {
      function ensureHttpPrefix(value) {
        if(value && !/^(http):\/\//i.test(value) && 'http://'.indexOf(value) === -1) {
          controller.$setViewValue('http://' + value);
          controller.$render();
          return 'http://' + value;
        } else {
          return value;
        }
      }
      controller.$formatters.push(ensureHttpPrefix);
      controller.$parsers.push(ensureHttpPrefix);
    }
  };
}

angular
    .module('cpZenPlatform')
    .directive('httpPrefix', httpPrefix)

}());<commit_msg>updating httpprefix directive to allow http and https at the start of urls<commit_after>;(function() {
  'use strict';

var subStrings = ["http://","https://"];

function httpPrefix() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attrs, controller) {
      function ensureHttpPrefix(value) {
        if(value && !/^(https?):\/\//i.test(value) && containsAny(value, subStrings)) {
          controller.$setViewValue('http://' + value);
          controller.$render();
          return 'http://' + value;
        } else {
          return value;
        }
      }
      controller.$formatters.push(ensureHttpPrefix);
      controller.$parsers.push(ensureHttpPrefix);
    }
  };
}

function containsAny(str, substrings) {
  for (var i=0; i < substrings.length; i++) {
    var substring = substrings[i];
    if (substring.indexOf(str) !== -1) {
      return false;
    }
  }
  return true;
}

angular
    .module('cpZenPlatform')
    .directive('httpPrefix', httpPrefix)

}());<|endoftext|>


<commit_before>function ready(fn) {
  if (document.readyState != 'loading') {
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

function loadReusableComponents() {
  loadUQFavicon();

  addAppleTouchIcon();

  modifyUserAreaTile();

  //show notification bar if user is not logged in
  loadSigninNotification();

  listenToLoginStatusChanges();

  //first element of the original document
  var firstElement = document.body.children[0];

  // insert alerts after body-tag
  var alerts = document.querySelector('uqlibrary-alerts');
  if (!alerts) {
    //as a back up insert header if it's not defined already
    alerts = document.createElement('uqlibrary-alerts');
    document.body.insertBefore(alerts, firstElement);
  }

  // insert header after alerts
  var header = document.createElement('uq-minimal-header');
  document.body.insertBefore(header, firstElement);

  // insert sub footer before body-tag
  var subFooter = document.createElement('uql-connect-footer');
  document.body.appendChild(subFooter);

  // insert footer before body-tag
  var footer = document.createElement('uq-minimal-footer');
  document.body.appendChild(footer);

  window.addEventListener('WebComponentsReady', function () {
    // when polymer is ready - configure elements
    header.showLoginButton = false;
    header.showAppsButton = true;
  });

  displayPublicationDates();
}

function displayPublicationDates() {
  // Use the Primo supplied function to preload the start and end dates in the Publication Date facet
  // function found in http://search.library.uq.edu.au/primo_library/libweb/wro/primo_library_web.js
  onTBChange('start');
  onTBChange('end');
}

function loadUQFavicon() {
  var link = document.createElement('link'),
      href = '//assets.library.uq.edu.au/master/reusable-components/resources/favicon.ico';
  link.type = 'image/x-icon';
  link.rel = 'shortcut icon';
  link.href = href;
  document.getElementsByTagName('head')[0].appendChild(link);
  link.rel = 'icon'; //for IE
  document.getElementsByTagName('head')[0].appendChild(link);

}

function addAppleTouchIcon() {
  // replace apple-touch-icon
  var appleTouchIconlink = $('link[rel="apple-touch-icon"]'),
      link = document.createElement('link'),
      sizes = ['152x152', '120x120', '76x76'],
      rel = 'apple-touch-icon',
      href = '//assets.library.uq.edu.au/master/reusable-components/resources/images/apple-touch-icon.png';

  if (appleTouchIconlink) {
    appleTouchIconlink.attr('href', href);
  } else {
    link.rel = rel;
    link.href = href;
    document.getElementsByTagName('head')[0].appendChild(link);
  }

  for (var i = 0; i < sizes.length; i++) {
    var size = sizes[i],
        iconLink = document.createElement('link');
    iconLink.rel = rel;
    iconLink.sizes = size;
    iconLink.href = href.replace('icon.png','icon-' + size + '.png');
    document.getElementsByTagName('head')[0].appendChild(iconLink);
  }
}

/* Call primo defined method isUserLoggedIn() to check users login status, show the notification if the user is not logged in */
function loadSigninNotification() {
  if (isUserLoggedIn())
    return;
  if ($('#signInPrompt').length > 0) /* prevents a double sign-in on some pages */
    return;
  if ($('body').hasClass('MyAccount')) /* don't repeat sign-in prompt on E-Shelf page */
    return;

  /* get the login address from the signin link already generated by primo */
  var signInLink = $('#exlidSignIn a').attr('href');

  //put the notification bar in the feedback area which is sitting right after search bar
  var container = $('#exlidHeaderSystemFeedback');
  container.prepend('

Log in to access full text, more search results and more services. Refresh this page if you are logged in but still see this message.
');
}

function modifyUserAreaTile() {
  var userAreaRibbon = $('#exlidUserAreaTile #exlidUserAreaRibbon');

  if (userAreaRibbon) {

    var myAccount = userAreaRibbon.find('#exlidMyAccount'),
        myShelf = userAreaRibbon.find('#exlidMyShelf'),
        hiddenClass = 'EXLHidden';

    // move signin and signout button next to the user name
    userAreaRibbon.find('.EXLLastItem').insertAfter(userAreaRibbon.find('#exlidUserName'));

    if (isUserLoggedIn()){
      // undo not logged in changes
      if (myAccount.hasClass(hiddenClass)) {
        myAccount.removeClass(hiddenClass);
        myShelf.children('span').remove();
      }

      // add saved searches and alerts link
      var savedSearches = $('
Saved searches & alerts
');
      myShelf.after(savedSearches);

    } else {
      if ($('#exlidSavedSearches')){
        $('#exlidSavedSearches').remove();
      }
      // hide my account link
      myAccount.addClass(hiddenClass);

      // insert a login reminder after myself
      myShelf.append(' - temporary if not logged in');
    }
  }

}

// add a event on fadein, this is to solve session timeout issue,
// when session timeout, primo will trigger an ajax call via function ssoByAjax then update the user login status
function listenToLoginStatusChanges() {
  var _old = $.fn.fadeIn;

  $.fn.fadeIn = function(){
    var self = this;
    _old.apply(this,arguments).promise().done(function(){
      self.trigger('fadeIn');
    });
  };

  $('#exlidSignOut').on('fadeIn',function(){
    location.reload();
  });
}

ready(loadReusableComponents);

// load google analytics
(function (i, s, o, g, r, a, m) {
  i.GoogleAnalyticsObject = r;
  i[r] = i[r] || function () {
        (i[r].q = i[r].q || []).push(arguments);
      };

  i[r].l = 1 * new Date();
  a = s.createElement(o);
  m = s.getElementsByTagName(o)[0];
  a.async = 1;
  a.src = g;
  m.parentNode.insertBefore(a, m);
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

ga('create', 'UA-4365437-14', 'auto');
ga('send', 'pageview');
<commit_msg>move refine dropdown<commit_after>function ready(fn) {
  if (document.readyState != 'loading') {
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

function loadReusableComponents() {
  loadUQFavicon();

  addAppleTouchIcon();

  modifyUserAreaTile();

  //show notification bar if user is not logged in
  loadSigninNotification();

  listenToLoginStatusChanges();

  listenToChangesinSearchRibbon();

  //first element of the original document
  var firstElement = document.body.children[0];

  // insert alerts after body-tag
  var alerts = document.querySelector('uqlibrary-alerts');
  if (!alerts) {
    //as a back up insert header if it's not defined already
    alerts = document.createElement('uqlibrary-alerts');
    document.body.insertBefore(alerts, firstElement);
  }

  // insert header after alerts
  var header = document.createElement('uq-minimal-header');
  document.body.insertBefore(header, firstElement);

  // insert sub footer before body-tag
  var subFooter = document.createElement('uql-connect-footer');
  document.body.appendChild(subFooter);

  // insert footer before body-tag
  var footer = document.createElement('uq-minimal-footer');
  document.body.appendChild(footer);

  var refineResuls = $('#EXLFacetsMobile');
  if(refineResuls){
    $('#exlidHeaderSearchLimits').after(refineResuls);
  }

  window.addEventListener('WebComponentsReady', function () {
    // when polymer is ready - configure elements
    header.showLoginButton = false;
    header.showAppsButton = true;

  });

  displayPublicationDates();
}

function displayPublicationDates() {
  // Use the Primo supplied function to preload the start and end dates in the Publication Date facet
  // function found in http://search.library.uq.edu.au/primo_library/libweb/wro/primo_library_web.js
  onTBChange('start');
  onTBChange('end');
}

function loadUQFavicon() {
  var link = document.createElement('link'),
      href = '//assets.library.uq.edu.au/master/reusable-components/resources/favicon.ico';
  link.type = 'image/x-icon';
  link.rel = 'shortcut icon';
  link.href = href;
  document.getElementsByTagName('head')[0].appendChild(link);
  link.rel = 'icon'; //for IE
  document.getElementsByTagName('head')[0].appendChild(link);

}

function addAppleTouchIcon() {
  // replace apple-touch-icon
  var appleTouchIconlink = $('link[rel="apple-touch-icon"]'),
      link = document.createElement('link'),
      sizes = ['152x152', '120x120', '76x76'],
      rel = 'apple-touch-icon',
      href = '//assets.library.uq.edu.au/master/reusable-components/resources/images/apple-touch-icon.png';

  if (appleTouchIconlink) {
    appleTouchIconlink.attr('href', href);
  } else {
    link.rel = rel;
    link.href = href;
    document.getElementsByTagName('head')[0].appendChild(link);
  }

  for (var i = 0; i < sizes.length; i++) {
    var size = sizes[i],
        iconLink = document.createElement('link');
    iconLink.rel = rel;
    iconLink.sizes = size;
    iconLink.href = href.replace('icon.png','icon-' + size + '.png');
    document.getElementsByTagName('head')[0].appendChild(iconLink);
  }
}

/* Call primo defined method isUserLoggedIn() to check users login status, show the notification if the user is not logged in */
function loadSigninNotification() {
  if (isUserLoggedIn())
    return;
  if ($('#signInPrompt').length > 0) /* prevents a double sign-in on some pages */
    return;
  if ($('body').hasClass('MyAccount')) /* don't repeat sign-in prompt on E-Shelf page */
    return;

  /* get the login address from the signin link already generated by primo */
  var signInLink = $('#exlidSignIn a').attr('href');

  //put the notification bar in the feedback area which is sitting right after search bar
  var container = $('#exlidHeaderSystemFeedback');
  container.prepend('

Log in to access full text, more search results and more services. Refresh this page if you are logged in but still see this message.
');
}

function modifyUserAreaTile() {
  var userAreaRibbon = $('#exlidUserAreaTile #exlidUserAreaRibbon');

  if (userAreaRibbon) {

    var myAccount = userAreaRibbon.find('#exlidMyAccount'),
        myShelf = userAreaRibbon.find('#exlidMyShelf'),
        hiddenClass = 'EXLHidden';

    // move signin and signout button next to the user name
    userAreaRibbon.find('.EXLLastItem').insertAfter(userAreaRibbon.find('#exlidUserName'));

    if (isUserLoggedIn()){
      // undo not logged in changes
      if (myAccount.hasClass(hiddenClass)) {
        myAccount.removeClass(hiddenClass);
        myShelf.children('span').remove();
      }

      // add saved searches and alerts link
      var savedSearches = $('
Saved searches & alerts
');
      myShelf.after(savedSearches);

    } else {
      if ($('#exlidSavedSearches')){
        $('#exlidSavedSearches').remove();
      }
      // hide my account link
      myAccount.addClass(hiddenClass);

      // insert a login reminder after myself
      myShelf.append(' - temporary if not logged in');
    }
  }

}

// add a event on fadein, this is to solve session timeout issue,
// when session timeout, primo will trigger an ajax call via function ssoByAjax then update the user login status
function listenToLoginStatusChanges() {
  var _old = $.fn.fadeIn;

  $.fn.fadeIn = function(){
    var self = this;
    _old.apply(this,arguments).promise().done(function(){
      self.trigger('fadeIn');
    });
  };

  $('#exlidSignOut').on('fadeIn',function(){
    location.reload();
  });
}

function listenToChangesinSearchRibbon () {
  var target = document.querySelector('#exlidSearchRibbon');

  // create an observer instance
  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      console.log(mutation.type);
    });
  });

  // configuration of the observer:
  var config = { attributes: true, childList: true, characterData: true }

  // pass in the target node, as well as the observer options
  observer.observe(target, config);
}

ready(loadReusableComponents);

// load google analytics
(function (i, s, o, g, r, a, m) {
  i.GoogleAnalyticsObject = r;
  i[r] = i[r] || function () {
        (i[r].q = i[r].q || []).push(arguments);
      };

  i[r].l = 1 * new Date();
  a = s.createElement(o);
  m = s.getElementsByTagName(o)[0];
  a.async = 1;
  a.src = g;
  m.parentNode.insertBefore(a, m);
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

ga('create', 'UA-4365437-14', 'auto');
ga('send', 'pageview');
<|endoftext|>


<commit_before>function ready(fn) {
  if (document.readyState != 'loading') {
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

function loadReusableComponents() {
  loadUQFavicon();

  //show notification bar if user is not logged in
  loadSigninNotification();

  moveActions();

  //first element of the original document
  var firstElement = document.body.children[0];

  // insert alerts after body-tag
  var alerts = document.querySelector('uqlibrary-alerts');
  if (!alerts) {
    //as a back up insert header if it's not defined already
    alerts = document.createElement('uqlibrary-alerts');
    document.body.insertBefore(alerts, firstElement);
  }

  // insert header after alerts
  var header = document.createElement('uq-minimal-header');
  document.body.insertBefore(header, firstElement);

  // insert sub footer before body-tag
  var subFooter = document.createElement('uql-connect-footer');
  document.body.appendChild(subFooter);

  // insert footer before body-tag
  var footer = document.createElement('uq-minimal-footer');
  document.body.appendChild(footer);

  window.addEventListener('WebComponentsReady', function () {
    // when polymer is ready - configure elements
    header.showLoginButton = false;
  });
}

function loadUQFavicon() {
  var link = document.createElement('link');
  link.type = 'image/x-icon';
  link.rel = 'shortcut icon';
  link.href = '//assets.library.uq.edu.au/reusable-components/resources/favicon.ico';
  document.getElementsByTagName('head')[0].appendChild(link);
  link.rel = 'icon'; //for IE
  document.getElementsByTagName('head')[0].appendChild(link);
}

function createActions() {
  var results = document.querySelectorAll('.EXLResultTabs');

  for (var index = 0; index < actions.length; index++) {
    results[index].appendChild('
Actions
');
  }
}

/* Call primo defined method isUserLoggedIn() to check users login status, show the notification if the user is not logged in */
function loadSigninNotification() {
  if (isUserLoggedIn())
    return;
  if ($('#signInPrompt').length > 0) /* prevents a double sign-in on some pages */
    return;
  if ($('body').hasClass('MyAccount')) /* don't repeat sign-in prompt on E-Shelf page */
    return;

  /* get the login address from the signin link already generated by primo */
  var signInLink = $('#exlidSignIn a').attr('href');

  //put the notification bar in the feedback area which is sitting right after search bar
  var container = $('#exlidHeaderSystemFeedback');
  container.prepend('

Log in to access full text, more search results and more services
');
}

ready(loadReusableComponents);

/* MOVE THE ITEM ACTIONS OUT OF THE TABS
 -----------------------------------------------------------------
 The following code moves the Item Actions (Share/Save) menu out
 of Primo's tabs and places it with the result records for easy
 access. The actions are stored in a dropdown menu but other
 buttons can be added directly to the created toolbar.

 Last edited 2016.02.22 by Kate Deibel
 */

/* -------------------------------------- */
/* UNCOMMENT ONE OF THE TWO OPTIONS BELOW */
/* -------------------------------------- */

/* OPTION 1: Uncomment the code below if using the MutationSupport widget */
//AddMutation('tr.EXLResult td.EXLSummary', addItemActionsToResult, false); // Brief Results
//AddMutation('.EXLFullView .EXLResult .EXLTabHeaderButtonSendToList', addItemActionsToResult); // Full Display

/* OPTION 2: Uncomment the code below if NOT using MutationSupport */
jQuery(document).ready(function () {
  jQuery('tr.EXLResult td.EXLSummary').each(function (i, elem) {
    addItemActionsToResult(elem);
  });
  jQuery('.EXLFullView .EXLResult .EXLTabHeaderButtonSendToList').each(function (i, elem) {
    addItemActionsToResult(elem);
  });
});

/* Main generator function for moving the item actions (Share/Save) out
 of the tabs.
 */
function addItemActionsToResult(elem) {
  /* set parameters */
  var $result;
  if (isFullDisplay()) {
    $result = jQuery('.EXLResult');
  }
  else {
    $result = jQuery(elem).parent();
  }
  /* create the tool generator */
  var toolsGen = new PrimoItemTools($result);
  /* generate the toolbar */
  var toolbarObject = generateToolbar($result, toolsGen);
  $result.find('.EXLSummaryFields').prepend(toolbarObject.toolbar);
  toolbarObject.dropdown.FitDropDown();

  /* if on brief display, add a click event to the default e-shelf link to to toggle
   the new e-shelf buttons */
  if (!isFullDisplay()) {
    $result.find('td.EXLMyShelfStar a').on('click', {index: toolsGen.index}, function (event) {
      var $stars = jQuery('.eshelf-button-class-' + event.data.index);
      $stars.each(function (i, elem) {
        var $this = jQuery(elem);
        if ($this.hasClass('off_shelf')) {
          $this.attr('title', 'Remove record from e-Shelf');
        }
        else {
          $this.attr('title', 'Add record to e-Shelf');
        }
        $this.toggleClass('on_shelf off_shelf');
      });
      return false;
    });
  }
}

/* Helper function for moving the toolbar.
 NOTE:
 If you wish to have buttons outside of the dropdown menu, you can insert
 them here as indicated by the comments.
 */
function generateToolbar($result, toolsGen) {
  /********************************************************
   Configure the button text and hovertext for the dropdown menu
   ********************************************************/
  var buttonText = 'Share/Save';
  var buttonTitle = 'Show actions for this item';
  /********** END EDITABLE CODE **********/

  var index = toolsGen.index;
  /* ids */
  var containerID = 'localidItemToolsContainer-' + (index);
  var dropdownID = 'item-tools-dropdown-' + (index);

  /* create the toolbar */
  var toolbarContainer = jQuery('
');
  toolbarContainer.attr('id', containerID);
  var toolbar = jQuery('
');
  toolbarContainer.append(toolbar);

  /********************************************************
   Add a tool button to the toolbar (not in the dropdown)
   ********************************************************/
  //toolbar.append( generateInlineItemToolButton(toolsGen.eShelf(), index) );
  //toolbar.append( generateInlineItemToolButton(toolsGen.Permalink(), index) );
  //toolbar.append( generateInlineItemToolButton(toolsGen.Citation(), index) )
  /********** END EDITABLE CODE **********/

  /* create the dropdown */
  var dropdownMenu = jQuery('
');

  /* Handle the z-index so that menus properly overlap each other */
  dropdownMenu.css('z-index', 150 - (index % 50));

  /* Load the tools into the dropdown */
  var dropdownWidget = generateItemToolDropdown(toolsGen, dropdownID, buttonText, buttonTitle);

  dropdownMenu.append(dropdownWidget.GetMenu());
  toolbar.append(dropdownMenu);

  /* ensure that the dropdown has proper width */
  dropdownWidget.FitDropDown();

  return {toolbar: toolbarContainer, dropdown: dropdownWidget};
}

/* Helper function for generating an inline item tool button (one not in the
 dropdown menu)
 */
function generateInlineItemToolButton(tool, index) {
  var toolDiv = jQuery('
');
  /* adjust the id and name to reflect that this is a toolbar item */
  tool.attr('id', tool.attr('id') + '-toolbar');
  tool.attr('name', tool.attr('name') + '-toolbar');
  /* z-index maxes at 150 for tool items, so we subtract index % 50 to make
   proper overlapping */
  tool.css('z-index', (150 - (index % 50)));
  toolDiv.append(tool);
  return toolDiv;
}

/* Generate the item action dropdown menu (Share/Save).
 You control what appears and their ordering.
 */
function generateItemToolDropdown(toolsGen, id, text, title) {
  var dropdown = new PrimoDropDown(id);
  dropdown.ButtonTitle(title);
  dropdown.ButtonText('', text, 'Click/Enter to show actions');

  /********************************************************
   Add the tool buttons to the dropdown. You control the
   order and what appears.
   ********************************************************/
  dropdown.AddButtonItem(toolsGen.eShelf());
  dropdown.AddButtonItem(toolsGen.Email());
  dropdown.AddButtonItem(toolsGen.Print());
  dropdown.AddButtonItem(toolsGen.Permalink());
  dropdown.AddButtonItem(toolsGen.Citation());
  dropdown.AddButtonItem(toolsGen.EndNote());
  dropdown.AddButtonItem(toolsGen.RefWorks());
  dropdown.AddButtonItem(toolsGen.EasyBib());
  dropdown.AddButtonItem(toolsGen.ExportRIS());
  /********** END EDITABLE CODE **********/

  return dropdown;
}<commit_msg>primo results 'actions' manipulations<commit_after>function ready(fn) {
  if (document.readyState != 'loading') {
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

function loadReusableComponents() {
  loadUQFavicon();

  //show notification bar if user is not logged in
  loadSigninNotification();

  moveActions();

  //first element of the original document
  var firstElement = document.body.children[0];

  // insert alerts after body-tag
  var alerts = document.querySelector('uqlibrary-alerts');
  if (!alerts) {
    //as a back up insert header if it's not defined already
    alerts = document.createElement('uqlibrary-alerts');
    document.body.insertBefore(alerts, firstElement);
  }

  // insert header after alerts
  var header = document.createElement('uq-minimal-header');
  document.body.insertBefore(header, firstElement);

  // insert sub footer before body-tag
  var subFooter = document.createElement('uql-connect-footer');
  document.body.appendChild(subFooter);

  // insert footer before body-tag
  var footer = document.createElement('uq-minimal-footer');
  document.body.appendChild(footer);

  window.addEventListener('WebComponentsReady', function () {
    // when polymer is ready - configure elements
    header.showLoginButton = false;
  });
}

function loadUQFavicon() {
  var link = document.createElement('link');
  link.type = 'image/x-icon';
  link.rel = 'shortcut icon';
  link.href = '//assets.library.uq.edu.au/reusable-components/resources/favicon.ico';
  document.getElementsByTagName('head')[0].appendChild(link);
  link.rel = 'icon'; //for IE
  document.getElementsByTagName('head')[0].appendChild(link);
}

function createActions() {
  var results = document.querySelectorAll('.EXLResultTabs');

  for (var index = 0; index < results.length; index++) {
    results[index].appendChild('
Actions
');
  }
}

/* Call primo defined method isUserLoggedIn() to check users login status, show the notification if the user is not logged in */
function loadSigninNotification() {
  if (isUserLoggedIn())
    return;
  if ($('#signInPrompt').length > 0) /* prevents a double sign-in on some pages */
    return;
  if ($('body').hasClass('MyAccount')) /* don't repeat sign-in prompt on E-Shelf page */
    return;

  /* get the login address from the signin link already generated by primo */
  var signInLink = $('#exlidSignIn a').attr('href');

  //put the notification bar in the feedback area which is sitting right after search bar
  var container = $('#exlidHeaderSystemFeedback');
  container.prepend('

Log in to access full text, more search results and more services
');
}

ready(loadReusableComponents);

/* MOVE THE ITEM ACTIONS OUT OF THE TABS
 -----------------------------------------------------------------
 The following code moves the Item Actions (Share/Save) menu out
 of Primo's tabs and places it with the result records for easy
 access. The actions are stored in a dropdown menu but other
 buttons can be added directly to the created toolbar.

 Last edited 2016.02.22 by Kate Deibel
 */

/* -------------------------------------- */
/* UNCOMMENT ONE OF THE TWO OPTIONS BELOW */
/* -------------------------------------- */

/* OPTION 1: Uncomment the code below if using the MutationSupport widget */
//AddMutation('tr.EXLResult td.EXLSummary', addItemActionsToResult, false); // Brief Results
//AddMutation('.EXLFullView .EXLResult .EXLTabHeaderButtonSendToList', addItemActionsToResult); // Full Display

/* OPTION 2: Uncomment the code below if NOT using MutationSupport */
jQuery(document).ready(function () {
  jQuery('tr.EXLResult td.EXLSummary').each(function (i, elem) {
    addItemActionsToResult(elem);
  });
  jQuery('.EXLFullView .EXLResult .EXLTabHeaderButtonSendToList').each(function (i, elem) {
    addItemActionsToResult(elem);
  });
});

/* Main generator function for moving the item actions (Share/Save) out
 of the tabs.
 */
function addItemActionsToResult(elem) {
  /* set parameters */
  var $result;
  if (isFullDisplay()) {
    $result = jQuery('.EXLResult');
  }
  else {
    $result = jQuery(elem).parent();
  }
  /* create the tool generator */
  var toolsGen = new PrimoItemTools($result);
  /* generate the toolbar */
  var toolbarObject = generateToolbar($result, toolsGen);
  $result.find('.EXLSummaryFields').prepend(toolbarObject.toolbar);
  toolbarObject.dropdown.FitDropDown();

  /* if on brief display, add a click event to the default e-shelf link to to toggle
   the new e-shelf buttons */
  if (!isFullDisplay()) {
    $result.find('td.EXLMyShelfStar a').on('click', {index: toolsGen.index}, function (event) {
      var $stars = jQuery('.eshelf-button-class-' + event.data.index);
      $stars.each(function (i, elem) {
        var $this = jQuery(elem);
        if ($this.hasClass('off_shelf')) {
          $this.attr('title', 'Remove record from e-Shelf');
        }
        else {
          $this.attr('title', 'Add record to e-Shelf');
        }
        $this.toggleClass('on_shelf off_shelf');
      });
      return false;
    });
  }
}

/* Helper function for moving the toolbar.
 NOTE:
 If you wish to have buttons outside of the dropdown menu, you can insert
 them here as indicated by the comments.
 */
function generateToolbar($result, toolsGen) {
  /********************************************************
   Configure the button text and hovertext for the dropdown menu
   ********************************************************/
  var buttonText = 'Share/Save';
  var buttonTitle = 'Show actions for this item';
  /********** END EDITABLE CODE **********/

  var index = toolsGen.index;
  /* ids */
  var containerID = 'localidItemToolsContainer-' + (index);
  var dropdownID = 'item-tools-dropdown-' + (index);

  /* create the toolbar */
  var toolbarContainer = jQuery('
');
  toolbarContainer.attr('id', containerID);
  var toolbar = jQuery('
');
  toolbarContainer.append(toolbar);

  /********************************************************
   Add a tool button to the toolbar (not in the dropdown)
   ********************************************************/
  //toolbar.append( generateInlineItemToolButton(toolsGen.eShelf(), index) );
  //toolbar.append( generateInlineItemToolButton(toolsGen.Permalink(), index) );
  //toolbar.append( generateInlineItemToolButton(toolsGen.Citation(), index) )
  /********** END EDITABLE CODE **********/

  /* create the dropdown */
  var dropdownMenu = jQuery('
');

  /* Handle the z-index so that menus properly overlap each other */
  dropdownMenu.css('z-index', 150 - (index % 50));

  /* Load the tools into the dropdown */
  var dropdownWidget = generateItemToolDropdown(toolsGen, dropdownID, buttonText, buttonTitle);

  dropdownMenu.append(dropdownWidget.GetMenu());
  toolbar.append(dropdownMenu);

  /* ensure that the dropdown has proper width */
  dropdownWidget.FitDropDown();

  return {toolbar: toolbarContainer, dropdown: dropdownWidget};
}

/* Helper function for generating an inline item tool button (one not in the
 dropdown menu)
 */
function generateInlineItemToolButton(tool, index) {
  var toolDiv = jQuery('
');
  /* adjust the id and name to reflect that this is a toolbar item */
  tool.attr('id', tool.attr('id') + '-toolbar');
  tool.attr('name', tool.attr('name') + '-toolbar');
  /* z-index maxes at 150 for tool items, so we subtract index % 50 to make
   proper overlapping */
  tool.css('z-index', (150 - (index % 50)));
  toolDiv.append(tool);
  return toolDiv;
}

/* Generate the item action dropdown menu (Share/Save).
 You control what appears and their ordering.
 */
function generateItemToolDropdown(toolsGen, id, text, title) {
  var dropdown = new PrimoDropDown(id);
  dropdown.ButtonTitle(title);
  dropdown.ButtonText('', text, 'Click/Enter to show actions');

  /********************************************************
   Add the tool buttons to the dropdown. You control the
   order and what appears.
   ********************************************************/
  dropdown.AddButtonItem(toolsGen.eShelf());
  dropdown.AddButtonItem(toolsGen.Email());
  dropdown.AddButtonItem(toolsGen.Print());
  dropdown.AddButtonItem(toolsGen.Permalink());
  dropdown.AddButtonItem(toolsGen.Citation());
  dropdown.AddButtonItem(toolsGen.EndNote());
  dropdown.AddButtonItem(toolsGen.RefWorks());
  dropdown.AddButtonItem(toolsGen.EasyBib());
  dropdown.AddButtonItem(toolsGen.ExportRIS());
  /********** END EDITABLE CODE **********/

  return dropdown;
}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014
 *
 * This file is licensed under the Affero General Public License version 3
 * or later.
 *
 * See the COPYING-README file.
 *
 */
(function(OC, OCA, $) {
	"use strict";

	/**
	 * Construct a new FileActions instance
	 * @constructs Files
	 */
	var Comment = function() {
		this.initialize();
	};

	Comment.prototype = {

		fileList: null,

		/**
		 * Initialize the file search
		 */
		initialize: function() {

			var self = this;

			this.fileAppLoaded = function() {
				return !!OCA.Files && !!OCA.Files.App;
			};
			function inFileList($row, result) {
				return false;

				if (! self.fileAppLoaded()) {
					return false;
				}
				var dir = self.fileList.getCurrentDirectory().replace(/\/+$/,'');
				var resultDir = OC.dirname(result.path);
				return dir === resultDir && self.fileList.inList(result.name);
			}
			function hideNoFilterResults() {
				var $nofilterresults = $('.nofilterresults');
				if ( ! $nofilterresults.hasClass('hidden') ) {
					$nofilterresults.addClass('hidden');
				}
			}

			/**
			 *
			 * @param {jQuery} $row
			 * @param {Object} result
			 * @param {int} result.id
			 * @param {string} result.comment
			 * @param {string} result.authorId
			 * @param {string} result.authorName
			 * @param {string} result.link
			 * @param {string} result.fileName
			 * @param {string} result.path
			 * @returns {*}
			 */
			this.renderCommentResult = function($row, result) {
				if (inFileList($row, result)) {
					return null;
				}
				hideNoFilterResults();
				/*render preview icon, show path beneath filename,
				 show size and last modified date on the right */
				this.updateLegacyMimetype(result);

				var $pathDiv = $('<div>').addClass('path').text(result.path);

				var $avatar = $('<div>');
				$avatar.addClass('avatar')
					.css('display', 'inline-block')
					.css('vertical-align', 'middle')
					.css('margin', '0 5px 2px 3px');

				if (result.authorName) {
					$avatar.avatar(result.authorId, 21, undefined, false, undefined, result.authorName);
				} else {
					$avatar.avatar(result.authorId, 21);
				}

				$row.find('td.info div.name').after($pathDiv).text(result.comment).prepend($('<span>').addClass('path').css('margin-right', '5px').text(result.authorName)).prepend($avatar);
				$row.find('td.result a').attr('href', result.link);

				$row.find('td.icon').css('background-image', 'url(' + OC.imagePath('core', 'actions/comment') + ')');
				var dir = OC.dirname(result.path);
				if (dir === '') {
					dir = '/';
				}
				$row.find('td.info a').attr('href',
					OC.generateUrl('/apps/files/?dir={dir}&scrollto={scrollto}', {dir: dir, scrollto: result.fileName})
				);

				return $row;
			};

			this.handleCommentClick = function($row, result, event) {
				if (self.fileAppLoaded() && self.fileList.id === 'files') {
					self.fileList.changeDirectory(OC.dirname(result.path));
					self.fileList.scrollTo(result.name);
					return false;
				} else {
					return true;
				}
			};

			this.updateLegacyMimetype = function (result) {
				// backward compatibility:
				if (!result.mime && result.mime_type) {
					result.mime = result.mime_type;
				}
			};
			this.setFileList = function (fileList) {
				this.fileList = fileList;
			};

			OC.Plugins.register('OCA.Search.Core', this);
		},
		attach: function(search) {
			search.setRenderer('comment', this.renderCommentResult.bind(this));
			search.setHandler('comment', this.handleCommentClick.bind(this));
		}
	};

	OCA.Search.comment = new Comment();
})(OC, OCA, $);
<commit_msg>Brighter comments icon<commit_after>/*
 * Copyright (c) 2014
 *
 * This file is licensed under the Affero General Public License version 3
 * or later.
 *
 * See the COPYING-README file.
 *
 */
(function(OC, OCA, $) {
	"use strict";

	/**
	 * Construct a new FileActions instance
	 * @constructs Files
	 */
	var Comment = function() {
		this.initialize();
	};

	Comment.prototype = {

		fileList: null,

		/**
		 * Initialize the file search
		 */
		initialize: function() {

			var self = this;

			this.fileAppLoaded = function() {
				return !!OCA.Files && !!OCA.Files.App;
			};
			function inFileList($row, result) {
				return false;

				if (! self.fileAppLoaded()) {
					return false;
				}
				var dir = self.fileList.getCurrentDirectory().replace(/\/+$/,'');
				var resultDir = OC.dirname(result.path);
				return dir === resultDir && self.fileList.inList(result.name);
			}
			function hideNoFilterResults() {
				var $nofilterresults = $('.nofilterresults');
				if ( ! $nofilterresults.hasClass('hidden') ) {
					$nofilterresults.addClass('hidden');
				}
			}

			/**
			 *
			 * @param {jQuery} $row
			 * @param {Object} result
			 * @param {int} result.id
			 * @param {string} result.comment
			 * @param {string} result.authorId
			 * @param {string} result.authorName
			 * @param {string} result.link
			 * @param {string} result.fileName
			 * @param {string} result.path
			 * @returns {*}
			 */
			this.renderCommentResult = function($row, result) {
				if (inFileList($row, result)) {
					return null;
				}
				hideNoFilterResults();
				/*render preview icon, show path beneath filename,
				 show size and last modified date on the right */
				this.updateLegacyMimetype(result);

				var $pathDiv = $('<div>').addClass('path').text(result.path);

				var $avatar = $('<div>');
				$avatar.addClass('avatar')
					.css('display', 'inline-block')
					.css('vertical-align', 'middle')
					.css('margin', '0 5px 2px 3px');

				if (result.authorName) {
					$avatar.avatar(result.authorId, 21, undefined, false, undefined, result.authorName);
				} else {
					$avatar.avatar(result.authorId, 21);
				}

				$row.find('td.info div.name').after($pathDiv).text(result.comment).prepend($('<span>').addClass('path').css('margin-right', '5px').text(result.authorName)).prepend($avatar);
				$row.find('td.result a').attr('href', result.link);

				$row.find('td.icon')
					.css('background-image', 'url(' + OC.imagePath('core', 'actions/comment') + ')')
					.css('opacity', '.4');
				var dir = OC.dirname(result.path);
				if (dir === '') {
					dir = '/';
				}
				$row.find('td.info a').attr('href',
					OC.generateUrl('/apps/files/?dir={dir}&scrollto={scrollto}', {dir: dir, scrollto: result.fileName})
				);

				return $row;
			};

			this.handleCommentClick = function($row, result, event) {
				if (self.fileAppLoaded() && self.fileList.id === 'files') {
					self.fileList.changeDirectory(OC.dirname(result.path));
					self.fileList.scrollTo(result.name);
					return false;
				} else {
					return true;
				}
			};

			this.updateLegacyMimetype = function (result) {
				// backward compatibility:
				if (!result.mime && result.mime_type) {
					result.mime = result.mime_type;
				}
			};
			this.setFileList = function (fileList) {
				this.fileList = fileList;
			};

			OC.Plugins.register('OCA.Search.Core', this);
		},
		attach: function(search) {
			search.setRenderer('comment', this.renderCommentResult.bind(this));
			search.setHandler('comment', this.handleCommentClick.bind(this));
		}
	};

	OCA.Search.comment = new Comment();
})(OC, OCA, $);
<|endoftext|>


<commit_before>require.config({
    baseUrl: "https://raw.github.com/adamjmoon/ToDoApp/master/assets/javascripts/",
    paths: {
        'text': 'vendor/requirejs-text/text',
        'plugins': 'durandal/plugins',
        'transitions': 'durandal/transitions'
    }
});
require(['app'], function () {
        "use strict";

        define('knockout', function () {
            return window.ko
        });
        define('jquery', function () {
            return window.$
        });

        require(['durandal/app', 'durandal/viewLocator', 'durandal/system', 'localStorage', 'OT'], function (app, viewLocator, system, LocalStorage, OT) {

            OT.DataService = new LocalStorage();
            //>>excludeStart("build", true);
            system.debug(true);
            //>>excludeEnd("build");

            app.title = 'Todo Durandal';

            app.configurePlugins({
                router: true
            });

            app.start().then(function () {
                //Replace 'viewmodels' in the moduleId with 'views' to locate the view.
                //Look for partial views in a 'views' folder in the root.
                viewLocator.useConvention();

                //Show the app by setting the root view model for our application with a transition.

                app.setRoot('viewmodels/shell');
            });
        });

    }
);

<commit_msg>main<commit_after>require.config({
    baseUrl: "https://raw.github.com/adamjmoon/ToDoApp/master/assets/javascripts/",
    paths: {
        'text': 'vendor/requirejs-text/text',
        'plugins': 'durandal/plugins',
        'transitions': 'durandal/transitions'
        'app': 'app'
    }
});
require(['app'], function () {
        "use strict";

        define('knockout', function () {
            return window.ko
        });
        define('jquery', function () {
            return window.$
        });

        require(['durandal/app', 'durandal/viewLocator', 'durandal/system', 'localStorage', 'OT'], function (app, viewLocator, system, LocalStorage, OT) {

            OT.DataService = new LocalStorage();
            //>>excludeStart("build", true);
            system.debug(true);
            //>>excludeEnd("build");

            app.title = 'Todo Durandal';

            app.configurePlugins({
                router: true
            });

            app.start().then(function () {
                //Replace 'viewmodels' in the moduleId with 'views' to locate the view.
                //Look for partial views in a 'views' folder in the root.
                viewLocator.useConvention();

                //Show the app by setting the root view model for our application with a transition.

                app.setRoot('viewmodels/shell');
            });
        });

    }
);

<|endoftext|>


<commit_before>
//setInterval(heatbeat, 30000); //30 seconds

function heatbeat(button) {
    $.ajax({
        url: "/assets/php/ajax/cartManager.php",
        data: {}
    })
    .done(function(retVal) {
        console.log("AJAX heartbeat complete.");
    });
}

<commit_msg>closed #45<commit_after>
setInterval(heatbeat, 5 * 60 * 1000); //heartbeat every 5 minutes

function heatbeat(button) {
    $.ajax({
        url: "/assets/php/ajax/cartManager.php",
        data: {}
    })
    .done(function(retVal) {
        console.log("AJAX heartbeat complete.");
    });
}

<|endoftext|>


<commit_before>
(function () {

	"use strict";

	/**
	 * This will prefix all the requests that ping makes. This is specially
	 * important when the
	 *
	 * @type String
	 */
	var baseURL = '/ping/';

	var token   = undefined;
	var actions = { follow: 'Follow', unfollow: 'Unfollow', pending: 'Loading...' };

	var JSRequest = function (url, callback) {
		//Export the callback to a global scope for the other elements to read
		var name = 'pingcb' + parseInt(Math.random() * 1000000);
		var s = document.createElement('script');

		//Unregister the callback and pass the data we received
		window[name]  = function (e) {
			callback(e);

			window[name] = undefined;
			document.head.removeChild(s);
		};

		s.src = baseURL + url + '?' + 'p=' + name + (token? '&token=' + token : '');
		s.async = true;
		document.head.appendChild(s);
	};

	var CORSRequest = function (url, callback) {
		var request = new XMLHttpRequest();

		if (!"withCredentials" in request) {
			throw "XHR is not CORS compatible";
		}

		request.onreadystatechange = function () {
			if (request.readyState === 4 && request.status === 200) {
				callback({error: false});
			}

			if (request.readyState === 4 && request.status !== 200) {
				callback({error: true});
			}
		};

		request.open('GET', baseURL + url + '?' + (token? 'token=' + token : ''));
		request.send();
	};

	var Request = function (url, callback) {
		try {
			return CORSRequest(url, callback);
		}
		catch (e) {
			return JSRequest(url, callback);
		}
	}

	var Button = function (html, userid) {
		var ctx = this;

		this.following = false;

		this.toggle = function () {
			this.following = !this.following;
			html.innerHTML = actions.pending;

			Request( (this.following? 'people/follow' : 'people/unfollow') + '/' + userid + '.json', function () {
				html.innerHTML = ctx.following? actions.unfollow : actions.follow;
			} );
		};

		Request('people/isFollowing/' + userid + '.json', function (e) {
			if (e.error) { return; }

			html.innerHTML = e.following? actions.unfollow : actions.follow;
			ctx.following  = e.following;

			html.addEventListener('click', function (e) {
				e.preventDefault();
				ctx.toggle();
			}, false);
		});
	};

	var init = function () {
		var buttons = document.querySelectorAll('*[data-ping-follow]');

		for (var i = 0; i < buttons.length; i++) {
			new Button(buttons[i], buttons[i].getAttribute('data-ping-follow'));
		}
	};

	window.ping = window.ping? window.ping : {};
	window.ping.setBaseURL = function (baseurl)  { baseURL = baseurl; };
	window.ping.setToken   = function (newToken) { token   = newToken; };
	window.ping.Button     = Button;
	window.ping.init       = init;

}());<commit_msg>Added a nonce parameter to some requests to ensure they're not being  cached.<commit_after>
(function () {

	"use strict";

	/**
	 * This will prefix all the requests that ping makes. This is specially
	 * important when the
	 *
	 * @type String
	 */
	var baseURL = '/ping/';

	var token   = undefined;
	var actions = { follow: 'Follow', unfollow: 'Unfollow', pending: 'Loading...' };

	var JSRequest = function (url, callback) {
		//Export the callback to a global scope for the other elements to read
		var name = 'pingcb' + parseInt(Math.random() * 1000000);
		var s = document.createElement('script');

		//Unregister the callback and pass the data we received
		window[name]  = function (e) {
			callback(e);

			window[name] = undefined;
			document.head.removeChild(s);
		};

		s.src = baseURL + url + '?' + 'p=' + name + (token? '&token=' + token : '');
		s.async = true;
		document.head.appendChild(s);
	};

	var CORSRequest = function (url, callback) {
		var request = new XMLHttpRequest();

		if (!"withCredentials" in request) {
			throw "XHR is not CORS compatible";
		}

		request.onreadystatechange = function () {
			if (request.readyState === 4 && request.status === 200) {
				callback({error: false});
			}

			if (request.readyState === 4 && request.status !== 200) {
				callback({error: true});
			}
		};

		request.open('GET', baseURL + url + '?' + (token? 'token=' + token : '') + '&nonce=' + (+new Date()));
		request.send();
	};

	var Request = function (url, callback) {
		try {
			return CORSRequest(url, callback);
		}
		catch (e) {
			return JSRequest(url, callback);
		}
	}

	var Button = function (html, userid) {
		var ctx = this;

		this.following = false;

		this.toggle = function () {
			this.following = !this.following;
			html.innerHTML = actions.pending;

			Request( (this.following? 'people/follow' : 'people/unfollow') + '/' + userid + '.json', function () {
				html.innerHTML = ctx.following? actions.unfollow : actions.follow;
			} );
		};

		Request('people/isFollowing/' + userid + '.json', function (e) {
			if (e.error) { return; }

			html.innerHTML = e.following? actions.unfollow : actions.follow;
			ctx.following  = e.following;

			html.addEventListener('click', function (e) {
				e.preventDefault();
				ctx.toggle();
			}, false);
		});
	};

	var init = function () {
		var buttons = document.querySelectorAll('*[data-ping-follow]');

		for (var i = 0; i < buttons.length; i++) {
			new Button(buttons[i], buttons[i].getAttribute('data-ping-follow'));
		}
	};

	window.ping = window.ping? window.ping : {};
	window.ping.setBaseURL = function (baseurl)  { baseURL = baseurl; };
	window.ping.setToken   = function (newToken) { token   = newToken; };
	window.ping.Button     = Button;
	window.ping.init       = init;

}());<|endoftext|>


<commit_before>window.packageVersionToggleHandler = function() {
  $('#packageVersionSelect').change(function(){
    var url = $(this).find('option:selected').data('uri');
    if(urlParam('viewer_pane') === '1'){
      window.replacePage(url,true);
    } else {
      window.location.href = url;
    }
  });

};

window.graphDownloadStatistics = function() {
  var getData = function(data_url, callback) {
    return $.get(data_url, callback);
  };

  nv.addGraph(function() {
      window.chart = nv.models.multiBarChart()
        .reduceXTicks(true)   //If 'false', every single x-axis tick label will be rendered.
        .rotateLabels(0)      //Angle to rotate x-axis labels.
        .showControls(true)   //Allow user to switch between 'Grouped' and 'Stacked' mode.
        .groupSpacing(0.1)    //Distance between each group of bars.
        .stacked(true)
        .x(function (d){
          return d.timestamp;
        })
        .y(function (d){
          return d.count;
        })
      ;

      window.chart.xAxis
          .tickFormat(function(d) { return d3.time.format('%x')(new Date(d)); });

      window.chart.yAxis
          .tickFormat(d3.format(',.1f'));

      if($('#chart').data('url')) {
        getData($('#chart').data('url'), function(data) {
          var direct_serie = {
            key: "Direct downloads",
            values: data.filter(function(e){
              return e.key=="direct_downloads";
            })
          };
          var indirect_serie = {
            key: "Indirect downloads",
            values: data.filter(function(e){
              return e.key=="indirect_downloads";
            })
          };
          $('#chart').show();
          d3.select('#chart svg')
            .datum([direct_serie,indirect_serie])
            .call(window.chart);
        });
        nv.utils.windowResize(window.chart.update);
      }

      return window.chart;
  });

};

window.dependencyGraph = function(){
  var getData = function(data_url, callback) {
    return $.get(data_url, callback);
  };

  nv.addGraph({
    generate: function() {
      var width = $('#packagedependencygraph').innerWidth(),
        height = $('#packagedependencygraph').innerHeight();
      var d3Colors = d3.scale.category20();
      var chart = nv.models.forceDirectedGraph()
        .width(width)
        .height(height)
        .color(function(d) { return d3Colors(d.group); })
        .nodeExtras(function(node) {
          node
            .append("text")
            .attr("dx", 12)
            .attr("dy", ".35em")
            .text(function(d) { return d.name; });
        });
      getData($('#packagedependencygraph').data('url'), function(data) {
        $('#packagedependencygraph').show();
        d3.select('#packagedependencygraph svg')
          .datum(data)
          .call(chart);
      });

      return chart;
    },
        callback: function(graph) {
            window.onresize = function() {
               var width = $('#packagedependencygraph').innerWidth(),
                height = $('#packagedependencygraph').innerHeight();
                graph.width(width).height(height);
                d3.select('#packagedependencygraph svg')
                    .attr('width', width)
                    .attr('height', height)
                    .call(graph);
            };
        }
    });
};

window.reverseDependencyGraph = function(){
  var getData = function(data_url, callback) {
    return $.get(data_url, callback);
  };

  nv.addGraph({
    generate: function() {
      var width = $('#packagereversedependencygraph').innerWidth(),
        height = $('#packagereversedependencygraph').innerHeight();
      var d3Colors = d3.scale.category20();
      var chart = nv.models.forceDirectedGraph()
        .width(width)
        .height(height)
        .color(function(d) { return d3Colors(d.group) })
        .nodeExtras(function(node) {
          node.append("text")
            .attr("dx", 12)
            .attr("dy", ".35em")
            .text(function(d) { return d.name });
        });
      getData($('#packagereversedependencygraph').data('url'), function(data) {
        $('#packagereversedependencygraph').show();
        d3.select('#packagereversedependencygraph svg')
          .datum(data)
          .call(chart);
      });

      return chart;
    },
    callback: function(graph) {
      window.onresize = function() {
        var width = $('#packagereversedependencygraph').innerWidth(),
          height = $('#packagereversedependencygraph').innerHeight();
        graph.width(width).height(height);
        d3.select('#packagereversedependencygraph svg')
          .attr('width', width)
          .attr('height', height)
          .call(graph);
      };
    }

  });

};

window.redrawChart = function(days){
  var getData = function(data_url, callback) {
    return $.get(data_url, callback);
  };
  var url = $('#chart').data('url');
  url = url.substring(0,url.indexOf('/per_day_last_month'));
  url = url+'/days/'+days+'/per_day'
  if(days<30){
    getData(url, function(data) {
      var direct_serie = {
        key: "Direct downloads",
        values: data.filter(function(e){
          return e.key=="direct_downloads";
        })
      };
      var indirect_serie = {
        key: "Indirect downloads",
        values: data.filter(function(e){
          return e.key=="indirect_downloads";
        })
      };
      chartData = d3.select('#chart svg').datum(data);
      chartData.datum([direct_serie,indirect_serie]).transition().duration(500).call(window.chart);
    });
  }
  else{
    getData(url, function(data) {
      var total_serie = {
        key: "Total downloads",
        values: data.filter(function(e){
          return e.key=="total_downloads";
        })
      };
      chartData = d3.select('#chart svg').datum(data);
      chartData.datum([total_serie]).transition().duration(500).call(window.chart);
    });
  }
    nv.utils.windowResize(window.chart.update);
};

window.makeSlider = function(){
  $(".slider").click(function(){
    var slider = $(".slider");
    if(slider.hasClass("fa-angle-down")){
      slider.removeClass("fa-angle-down");
      slider.addClass("fa-angle-up");
      $(".sliding").slideDown();
      if(!$("#chart svg").hasClass("nvd3-svg")){
      window.graphDownloadStatistics();
    }
    }else{
      slider.removeClass("fa-angle-up");
      slider.addClass("fa-angle-down");
      $(".sliding").slideUp();
    }
  });
};

window.triggerIcon = function(){
  $("table").bind("sortEnd",function(){
    $("thead td").each(function(){
      var current = $(this);
      if(current.hasClass("tablesorter-headerDesc")){
        current.find("i").removeClass("fa-sort");
        current.find("i").removeClass("fa-sort-asc");
        current.find("i").addClass("fa-sort-desc");
      }
      if(current.hasClass("tablesorter-headerAsc")){
        current.find("i").removeClass("fa-sort");
        current.find("i").removeClass("fa-sort-desc");
        current.find("i").addClass("fa-sort-asc");
      }
      if(current.hasClass("tablesorter-headerUnSorted")){
        current.find("i").removeClass("fa-sort-desc");
        current.find("i").removeClass("fa-sort-asc");
        current.find("i").addClass("fa-sort");
      }
    });
  })
}

$(document).ready(function() {
  $.getScript("http://code.jquery.com/ui/1.12.0/jquery-ui.js", function(){
    window.triggerIcon();
    $("#show").click(function(){
      $("#show").hide();
      $("#details").find(".hidden").removeClass("hidden");
    });
    window.packageVersionToggleHandler();
    if(urlParam('viewer_pane') === '1'){
      $('#tabs').tabs({
        'beforeLoad':function(event,ui){
          window.setTab(event,ui);
        }
      });
    }
    else{
      $('#tabs').tabs({
      active: 0
      });
    }
  });
  $.getScript("http://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js",function(){
    $.getScript("http://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.3/nv.d3.min.js",function(){
      window.makeSlider();
      if(!urlParam('viewer_pane') === '1'){
        $("#tab1").click(function(){
          if(!$("#packagedependencygraph svg").hasClass("nvd3-svg")){
          window.dependencyGraph();
          }
        });
        $("#tab2").click(function(){
          if(!$("#packagereversedependencygraph svg").hasClass("nvd3-svg")){
          window.reverseDependencyGraph();
          }
        });
      }
    });
  });
  $.getScript("http://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.27.2/js/jquery.tablesorter.js",function(){
    // add parser through the tablesorter addParser method
    $.tablesorter.addParser({
        // set a unique id
        id: 'rating',
        is: function(s) {
            // return false so this parser is not auto detected
            return false;
        },
        format: function(s) {
            // format your data for normalization
            return parseFloat(s);
        },
        // set type, either numeric or text
        type: 'numeric'
    });
    $("table").tablesorter({
          headers: {
              2: {
                  sorter:'rating'
              }
          },
          textExtraction: function (node){
            if($(node).find("i").length>0){
              var stars = $(node).find("i");
              //console.log(stars);
              var count = 0.0;
              stars.each(function(i){
                if($(this).hasClass("fa-star")){
                  count += 1.0;
                }else if($(this).hasClass("fa-star-half-o")){
                  count += 0.5;
                }
              });
              return ""+count;
            }
            return $(node).text();
          }
    });
  });
});
<commit_msg>solved small problem with montly downloads graph<commit_after>window.packageVersionToggleHandler = function() {
  $('#packageVersionSelect').change(function(){
    var url = $(this).find('option:selected').data('uri');
    if(urlParam('viewer_pane') === '1'){
      window.replacePage(url,true);
    } else {
      window.location.href = url;
    }
  });

};

window.graphDownloadStatistics = function() {
  var getData = function(data_url, callback) {
    return $.get(data_url, callback);
  };

  nv.addGraph(function() {
      window.chart = nv.models.multiBarChart()
        .reduceXTicks(true)   //If 'false', every single x-axis tick label will be rendered.
        .rotateLabels(0)      //Angle to rotate x-axis labels.
        .showControls(true)   //Allow user to switch between 'Grouped' and 'Stacked' mode.
        .groupSpacing(0.1)    //Distance between each group of bars.
        .stacked(true)
        .x(function (d){
          return d.timestamp;
        })
        .y(function (d){
          return d.count;
        })
      ;

      window.chart.xAxis
          .tickFormat(function(d) { return d3.time.format('%x')(new Date(d)); });

      window.chart.yAxis
          .tickFormat(d3.format(',.1f'));

      if($('#chart').data('url')) {
        getData($('#chart').data('url'), function(data) {
          var direct_serie = {
            key: "Direct downloads",
            values: data.filter(function(e){
              return e.key=="direct_downloads";
            })
          };
          var indirect_serie = {
            key: "Indirect downloads",
            values: data.filter(function(e){
              return e.key=="indirect_downloads";
            })
          };
          $('#chart').show();
          d3.select('#chart svg')
            .datum([direct_serie,indirect_serie])
            .call(window.chart);
        });
        nv.utils.windowResize(window.chart.update);
      }

      return window.chart;
  });

};

window.dependencyGraph = function(){
  var getData = function(data_url, callback) {
    return $.get(data_url, callback);
  };

  nv.addGraph({
    generate: function() {
      var width = $('#packagedependencygraph').innerWidth(),
        height = $('#packagedependencygraph').innerHeight();
      var d3Colors = d3.scale.category20();
      var chart = nv.models.forceDirectedGraph()
        .width(width)
        .height(height)
        .color(function(d) { return d3Colors(d.group); })
        .nodeExtras(function(node) {
          node
            .append("text")
            .attr("dx", 12)
            .attr("dy", ".35em")
            .text(function(d) { return d.name; });
        });
      getData($('#packagedependencygraph').data('url'), function(data) {
        $('#packagedependencygraph').show();
        d3.select('#packagedependencygraph svg')
          .datum(data)
          .call(chart);
      });

      return chart;
    },
        callback: function(graph) {
            window.onresize = function() {
               var width = $('#packagedependencygraph').innerWidth(),
                height = $('#packagedependencygraph').innerHeight();
                graph.width(width).height(height);
                d3.select('#packagedependencygraph svg')
                    .attr('width', width)
                    .attr('height', height)
                    .call(graph);
            };
        }
    });
};

window.reverseDependencyGraph = function(){
  var getData = function(data_url, callback) {
    return $.get(data_url, callback);
  };

  nv.addGraph({
    generate: function() {
      var width = $('#packagereversedependencygraph').innerWidth(),
        height = $('#packagereversedependencygraph').innerHeight();
      var d3Colors = d3.scale.category20();
      var chart = nv.models.forceDirectedGraph()
        .width(width)
        .height(height)
        .color(function(d) { return d3Colors(d.group) })
        .nodeExtras(function(node) {
          node.append("text")
            .attr("dx", 12)
            .attr("dy", ".35em")
            .text(function(d) { return d.name });
        });
      getData($('#packagereversedependencygraph').data('url'), function(data) {
        $('#packagereversedependencygraph').show();
        d3.select('#packagereversedependencygraph svg')
          .datum(data)
          .call(chart);
      });

      return chart;
    },
    callback: function(graph) {
      window.onresize = function() {
        var width = $('#packagereversedependencygraph').innerWidth(),
          height = $('#packagereversedependencygraph').innerHeight();
        graph.width(width).height(height);
        d3.select('#packagereversedependencygraph svg')
          .attr('width', width)
          .attr('height', height)
          .call(graph);
      };
    }

  });

};

window.redrawChart = function(days){
  var getData = function(data_url, callback) {
    return $.get(data_url, callback);
  };
  var url = $('#chart').data('url');
  url = url.substring(0,url.indexOf('/per_day_last_month'));
  url = url+'/days/'+days+'/per_day'
  if(days<31){
    getData(url, function(data) {
      var direct_serie = {
        key: "Direct downloads",
        values: data.filter(function(e){
          return e.key=="direct_downloads";
        })
      };
      var indirect_serie = {
        key: "Indirect downloads",
        values: data.filter(function(e){
          return e.key=="indirect_downloads";
        })
      };
      chartData = d3.select('#chart svg').datum(data);
      chartData.datum([direct_serie,indirect_serie]).transition().duration(500).call(window.chart);
    });
  }
  else{
    getData(url, function(data) {
      var total_serie = {
        key: "Total downloads",
        values: data.filter(function(e){
          return e.key=="total_downloads";
        })
      };
      chartData = d3.select('#chart svg').datum(data);
      chartData.datum([total_serie]).transition().duration(500).call(window.chart);
    });
  }
    nv.utils.windowResize(window.chart.update);
};

window.makeSlider = function(){
  $(".slider").click(function(){
    var slider = $(".slider");
    if(slider.hasClass("fa-angle-down")){
      slider.removeClass("fa-angle-down");
      slider.addClass("fa-angle-up");
      $(".sliding").slideDown();
      if(!$("#chart svg").hasClass("nvd3-svg")){
      window.graphDownloadStatistics();
    }
    }else{
      slider.removeClass("fa-angle-up");
      slider.addClass("fa-angle-down");
      $(".sliding").slideUp();
    }
  });
};

window.triggerIcon = function(){
  $("table").bind("sortEnd",function(){
    $("thead td").each(function(){
      var current = $(this);
      if(current.hasClass("tablesorter-headerDesc")){
        current.find("i").removeClass("fa-sort");
        current.find("i").removeClass("fa-sort-asc");
        current.find("i").addClass("fa-sort-desc");
      }
      if(current.hasClass("tablesorter-headerAsc")){
        current.find("i").removeClass("fa-sort");
        current.find("i").removeClass("fa-sort-desc");
        current.find("i").addClass("fa-sort-asc");
      }
      if(current.hasClass("tablesorter-headerUnSorted")){
        current.find("i").removeClass("fa-sort-desc");
        current.find("i").removeClass("fa-sort-asc");
        current.find("i").addClass("fa-sort");
      }
    });
  })
}

$(document).ready(function() {
  $.getScript("http://code.jquery.com/ui/1.12.0/jquery-ui.js", function(){
    window.triggerIcon();
    $("#show").click(function(){
      $("#show").hide();
      $("#details").find(".hidden").removeClass("hidden");
    });
    window.packageVersionToggleHandler();
    if(urlParam('viewer_pane') === '1'){
      $('#tabs').tabs({
        'beforeLoad':function(event,ui){
          window.setTab(event,ui);
        }
      });
    }
    else{
      $('#tabs').tabs({
      active: 0
      });
    }
  });
  $.getScript("http://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js",function(){
    $.getScript("http://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.3/nv.d3.min.js",function(){
      window.makeSlider();
      if(!urlParam('viewer_pane') === '1'){
        $("#tab1").click(function(){
          if(!$("#packagedependencygraph svg").hasClass("nvd3-svg")){
          window.dependencyGraph();
          }
        });
        $("#tab2").click(function(){
          if(!$("#packagereversedependencygraph svg").hasClass("nvd3-svg")){
          window.reverseDependencyGraph();
          }
        });
      }
    });
  });
  $.getScript("http://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.27.2/js/jquery.tablesorter.js",function(){
    // add parser through the tablesorter addParser method
    $.tablesorter.addParser({
        // set a unique id
        id: 'rating',
        is: function(s) {
            // return false so this parser is not auto detected
            return false;
        },
        format: function(s) {
            // format your data for normalization
            return parseFloat(s);
        },
        // set type, either numeric or text
        type: 'numeric'
    });
    $("table").tablesorter({
          headers: {
              2: {
                  sorter:'rating'
              }
          },
          textExtraction: function (node){
            if($(node).find("i").length>0){
              var stars = $(node).find("i");
              //console.log(stars);
              var count = 0.0;
              stars.each(function(i){
                if($(this).hasClass("fa-star")){
                  count += 1.0;
                }else if($(this).hasClass("fa-star-half-o")){
                  count += 0.5;
                }
              });
              return ""+count;
            }
            return $(node).text();
          }
    });
  });
});
<|endoftext|>


<commit_before>define (['jquery', 'aggregate'], function ($, aggregate) {

    var stats = {};

    function build (statsParam) {
        stats = statsParam;
    }

    function getAgeText () {

    }

    function getEpochText () {

    }

    function getStyleText () {

    }

    function getSimilarText () {

    }

    return {
        build: build,
        getAgeText: getAgeText,
        getEpochText: getEpochText,
        getStyleText: getStyleText,
        getSimilarTex: getSimilarTex
    };
});

StatsAnalyzer.build(artistStats);

var ageText = StatsAnalyzer.getAgeText();
var epochText = StatsAnalyzer.getEpochText();
var styleText = StatsAnalyzer.getStyleText();
var similarText = StatsAnalyzer.getSimilarText();<commit_msg>fix StatsAnalyzer 1<commit_after>define (['jquery', 'aggregate'], function ($, aggregate) {

    var stats = {};

    function build (statsParam) {
        stats = statsParam;
    }

    function getAgeText () {

    }

    function getEpochText () {

    }

    function getStyleText () {

    }

    function getSimilarText () {

    }

    return {
        build: build,
        getAgeText: getAgeText,
        getEpochText: getEpochText,
        getStyleText: getStyleText,
        getSimilarText: getSimilarText
    };
});<|endoftext|>


<commit_before>'use strict';

obtain(['./src/server/express.js'], (hw)=> {
  exports.app = {};

  piFig.setupAutostart();

  exports.app.start = ()=> {
    console.log('started');

    document.onkeypress = (e)=> {
      if (e.key == ' ') console.log('Space pressed');
    };

  };

  provide(exports);
});
<commit_msg>remove pifig from main program<commit_after>'use strict';

obtain(['./src/server/express.js'], (hw)=> {
  exports.app = {};

  exports.app.start = ()=> {
    console.log('started');

    document.onkeypress = (e)=> {
      if (e.key == ' ') console.log('Space pressed');
    };

  };

  provide(exports);
});
<|endoftext|>