<commit_before>/**
 * @fileOverview This file provides for posting new links generated by the
 * extension to a host page.
 *
 * Posting Process:
 *
 * 1. The user selects an editable element with a right click
 * 2. The user clicks a Privly posting application in the resultant context
 *    menu.
 * 3. This script records the host page the link will be posted to
 * 4. The script opens a posting window and records its ID
 * 5. The posting application will complete and send this script
 *    a message with the Privly URL
 * 6. The script sends the host page's content script,
 *    post_new_link.js, the URL
 */

/**
 * @namespace Functionality for posting new links to pages.
 */
var postingProcess = {

  /**
   * The secret that should be included in messages to the application.
   */
  messageSecret: null,

  /**
   * Handles right click on form event by opening posting window.
   *
   * @param {OnClickData} info Information on the context menu generating
   * this event.
   * @param {tab} sourceTab The tab that was clicked for the context menu
   * @param {string} postingApplicationName the name of the posting application.
   * for examples, see the creation of the context menus below. Current values
   * include PlainPost and ZeroBin
   *
   */
  postingHandler: function(info, sourceTab, postingApplicationName) {

    // only open a new posting window
    if (postingProcess.postingApplicationTabId === undefined) {

      var postingDomain = localStorage["posting_content_server_url"];
      if ( postingDomain === undefined ) {
        postingDomain = "https://privlyalpha.org";
        localStorage["posting_content_server_url"] = postingDomain;
      }

      var postingApplicationUrl = chrome.extension.getURL("privly-applications/" +
                                                           postingApplicationName +
                                                           "/new.html");

      if( info.selectionText !== undefined ) {
        postingProcess.postingApplicationStartingValue = info.selectionText;
      } else {
        postingProcess.postingApplicationStartingValue = "";
      }

      // Open a new window.
      chrome.windows.create({url: postingApplicationUrl, focused: true,
                             top: 0, left: 0,
                             type: "normal"},
        function(newWindow){

          //Get the window's tab
          var tab = newWindow.tabs[0];

          //remember the posting tab id
          postingProcess.postingApplicationTabId = tab.id;

          //remember the tab id where the post will be placed. The content script
          //will remember which form element was clicked
          postingProcess.postingResultTab = sourceTab;

          //tell the host page not to change the posting location on subsequent
          //right click events
          chrome.tabs.sendMessage(postingProcess.postingResultTab.id,
            {pendingPost: true});
        }
      );
    } else {
      var notification = new Notification("There is already a pending post",
        {icon: "images/logo_48.png"});
    }
  },

  /**
   * Handles the receipt of Privly URLs from the posting application
   * for addition to the host page.
   *
   * @param {object} request The request object's JSON document.
   * The request object should contain the privlyUrl.
   * @param {object} sender Information on the sending posting application
   * @param {function} sendResponse The callback function for replying to message
   *
   * @return {null} The function does not return anything, but it does call the
   * response function.
   */
  receiveNewPrivlyUrl: function(request, sender, sendResponse) {

    if (request.handler === "privlyUrl" &&
      postingProcess.postingResultTab !== undefined) {

      //Switches current tab to the page receiving the URL
      chrome.tabs.update(postingProcess.postingResultTab.id, {selected: true});

      //sends URL to host page
      chrome.tabs.sendMessage(postingProcess.postingResultTab.id,
        {privlyUrl: request.data, pendingPost: false});

      //close the posting application
      chrome.tabs.remove(sender.tab.id);
      postingProcess.postingApplicationTabId = undefined;

      //remove the record of where we are posting to
      postingProcess.postingResultTab = undefined;
    }
  },

  /**
   * Receives the secret message from the privly-application so
   * it can send messages in the future with the secret token.
   * Otherwise the applications will not trust the origin of the
   * messages.
   *
   * @param {object} request The request object's JSON document.
   * The request object should contain the privlyUrl.
   * @param {object} sender Information on the sending posting application
   * @param {function} sendResponse The callback function for replying to message
   *
   * @return {null} The function does not return anything, but it does call the
   * response function.
   */
  initializeMessagePathway: function(request, sender, sendResponse) {

    if (request.handler === "messageSecret" &&
                 sender.tab.url.indexOf("chrome-extension://") === 0) {
      postingProcess.messageSecret = request.data;
      sendResponse({secret: postingProcess.messageSecret,
                    handler: "messageSecret"});
    } else if (request.handler === "initialContent" &&
               sender.tab.id === postingProcess.postingApplicationTabId) {
      sendResponse({secret: postingProcess.messageSecret, initialContent:
                    postingProcess.postingApplicationStartingValue, handler: "initialContent"});
    }
  },

  /**
   * Send the privly-application the initial content, if there is any.
   *
   * @param {object} request The request object's JSON document.
   * The request object should contain the privlyUrl.
   * @param {object} sender Information on the sending posting application
   * @param {function} sendResponse The callback function for replying to message
   *
   * @return {null} The function does not return anything, but it does call the
   * response function.
   */
  sendInitialContent: function(request, sender, sendResponse) {

    if (request.handler === "initialContent" &&
               sender.tab.id === postingProcess.postingApplicationTabId) {
      sendResponse({secret: postingProcess.messageSecret, initialContent:
                    postingProcess.postingApplicationStartingValue, handler: "initialContent"});
    } else if(request.handler === "initialContent") {
      sendResponse({secret: postingProcess.messageSecret, initialContent: "",
        handler: "initialContent"});
    }
  },

  /**
   * Handle closure of posting application tabs. If the posting application
   * or host page closes, the state should reset. The posting form will close
   * as well.
   *
   * @param {integer} tabId The ID of the tab removed.
   * @param {removeInfo} removeInfo Information on the removal.
   *
   */
  tabRemoved: function(tabId, removeInfo) {

    if (postingProcess.postingResultTab === undefined ||
        postingProcess.postingApplicationTabId === undefined) {
      return;
    }

    // The tab generating the URL closed
    if (tabId === postingProcess.postingApplicationTabId) {
      chrome.tabs.sendMessage(postingProcess.postingResultTab.id, {pendingPost: false});
    } else if (tabId === postingProcess.postingResultTab.id) {
      // The tab receiving the URL Closed
      chrome.tabs.remove(postingProcess.postingApplicationTabId);
    }
    postingProcess.postingResultTab = undefined;
    postingProcess.postingApplicationTabId = undefined;
    postingProcess.postingApplicationStartingValue = "";
  },

  // Remembers where the PrivlyUrl will be placed based on the context menu
  postingResultTab: undefined,
  postingApplicationTabId: undefined,
  postingApplicationStartingValue: ""

}

// Informs the user that they must have a developer account to post new content
chrome.contextMenus.create({
    "title": "Privly is in Alpha. Do not assume your privacy.",
    "contexts": ["editable"],
    "enabled": false
  });

// Creates the ZeroBin context menu
chrome.contextMenus.create({
    "title": "Post with ZeroBin",
    "contexts": ["editable"],
    "onclick" : function(info, tab) {
        postingProcess.postingHandler(info, tab, "ZeroBin");
    }
  });

// Creates the PlainPost context menu
chrome.contextMenus.create({
    "title": "Post with PlainPost",
    "contexts": ["editable"],
    "onclick" : function(info, tab) {
        postingProcess.postingHandler(info, tab, "PlainPost");
    }
  });

// Creates the History context menu
chrome.contextMenus.create({
    "title": "View History",
    "contexts": ["editable"],
    "onclick" : function(info, tab) {
        postingProcess.postingHandler(info, tab, "History");
    }
  });

// Initialize message listeners
chrome.extension.onMessage.addListener(postingProcess.initializeMessagePathway);
chrome.extension.onMessage.addListener(postingProcess.receiveNewPrivlyUrl);
chrome.extension.onMessage.addListener(postingProcess.sendInitialContent);

// Handle the request sent from post_new_link.js when clicking the Privly button
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.ask === "newPost") {

      // The info parameter is 0
      postingProcess.postingHandler(0, sender.tab, "Help");
    }
  });

// Handle the request sent from post_new_link.js to display a notfication
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.ask === "showNotification") {
      var notification = new Notification("There is already an open window of a pending Privly post",
        {icon: "images/logo_48.png"});
      notification.show();
    }
  });

// Handle closure of posting application tabs
chrome.tabs.onRemoved.addListener(postingProcess.tabRemoved);
<commit_msg>changed Chrome context menu<commit_after>/**
 * @fileOverview This file provides for posting new links generated by the
 * extension to a host page.
 *
 * Posting Process:
 *
 * 1. The user selects an editable element with a right click
 * 2. The user clicks a Privly posting application in the resultant context
 *    menu.
 * 3. This script records the host page the link will be posted to
 * 4. The script opens a posting window and records its ID
 * 5. The posting application will complete and send this script
 *    a message with the Privly URL
 * 6. The script sends the host page's content script,
 *    post_new_link.js, the URL
 */

/**
 * @namespace Functionality for posting new links to pages.
 */
var postingProcess = {

  /**
   * The secret that should be included in messages to the application.
   */
  messageSecret: null,

  /**
   * Handles right click on form event by opening posting window.
   *
   * @param {OnClickData} info Information on the context menu generating
   * this event.
   * @param {tab} sourceTab The tab that was clicked for the context menu
   * @param {string} postingApplicationName the name of the posting application.
   * for examples, see the creation of the context menus below. Current values
   * include PlainPost and ZeroBin
   *
   */
  postingHandler: function(info, sourceTab, postingApplicationName) {

    // only open a new posting window
    if (postingProcess.postingApplicationTabId === undefined) {

      var postingDomain = localStorage["posting_content_server_url"];
      if ( postingDomain === undefined ) {
        postingDomain = "https://privlyalpha.org";
        localStorage["posting_content_server_url"] = postingDomain;
      }

      var postingApplicationUrl = chrome.extension.getURL("privly-applications/" +
                                                           postingApplicationName +
                                                           "/new.html");

      if( info.selectionText !== undefined ) {
        postingProcess.postingApplicationStartingValue = info.selectionText;
      } else {
        postingProcess.postingApplicationStartingValue = "";
      }

      // Open a new window.
      chrome.windows.create({url: postingApplicationUrl, focused: true,
                             top: 0, left: 0,
                             type: "normal"},
        function(newWindow){

          //Get the window's tab
          var tab = newWindow.tabs[0];

          //remember the posting tab id
          postingProcess.postingApplicationTabId = tab.id;

          //remember the tab id where the post will be placed. The content script
          //will remember which form element was clicked
          postingProcess.postingResultTab = sourceTab;

          //tell the host page not to change the posting location on subsequent
          //right click events
          chrome.tabs.sendMessage(postingProcess.postingResultTab.id,
            {pendingPost: true});
        }
      );
    } else {
      var notification = new Notification("There is already a pending post",
        {icon: "images/logo_48.png"});
    }
  },

  /**
   * Handles the receipt of Privly URLs from the posting application
   * for addition to the host page.
   *
   * @param {object} request The request object's JSON document.
   * The request object should contain the privlyUrl.
   * @param {object} sender Information on the sending posting application
   * @param {function} sendResponse The callback function for replying to message
   *
   * @return {null} The function does not return anything, but it does call the
   * response function.
   */
  receiveNewPrivlyUrl: function(request, sender, sendResponse) {

    if (request.handler === "privlyUrl" &&
      postingProcess.postingResultTab !== undefined) {

      //Switches current tab to the page receiving the URL
      chrome.tabs.update(postingProcess.postingResultTab.id, {selected: true});

      //sends URL to host page
      chrome.tabs.sendMessage(postingProcess.postingResultTab.id,
        {privlyUrl: request.data, pendingPost: false});

      //close the posting application
      chrome.tabs.remove(sender.tab.id);
      postingProcess.postingApplicationTabId = undefined;

      //remove the record of where we are posting to
      postingProcess.postingResultTab = undefined;
    }
  },

  /**
   * Receives the secret message from the privly-application so
   * it can send messages in the future with the secret token.
   * Otherwise the applications will not trust the origin of the
   * messages.
   *
   * @param {object} request The request object's JSON document.
   * The request object should contain the privlyUrl.
   * @param {object} sender Information on the sending posting application
   * @param {function} sendResponse The callback function for replying to message
   *
   * @return {null} The function does not return anything, but it does call the
   * response function.
   */
  initializeMessagePathway: function(request, sender, sendResponse) {

    if (request.handler === "messageSecret" &&
                 sender.tab.url.indexOf("chrome-extension://") === 0) {
      postingProcess.messageSecret = request.data;
      sendResponse({secret: postingProcess.messageSecret,
                    handler: "messageSecret"});
    } else if (request.handler === "initialContent" &&
               sender.tab.id === postingProcess.postingApplicationTabId) {
      sendResponse({secret: postingProcess.messageSecret, initialContent:
                    postingProcess.postingApplicationStartingValue, handler: "initialContent"});
    }
  },

  /**
   * Send the privly-application the initial content, if there is any.
   *
   * @param {object} request The request object's JSON document.
   * The request object should contain the privlyUrl.
   * @param {object} sender Information on the sending posting application
   * @param {function} sendResponse The callback function for replying to message
   *
   * @return {null} The function does not return anything, but it does call the
   * response function.
   */
  sendInitialContent: function(request, sender, sendResponse) {

    if (request.handler === "initialContent" &&
               sender.tab.id === postingProcess.postingApplicationTabId) {
      sendResponse({secret: postingProcess.messageSecret, initialContent:
                    postingProcess.postingApplicationStartingValue, handler: "initialContent"});
    } else if(request.handler === "initialContent") {
      sendResponse({secret: postingProcess.messageSecret, initialContent: "",
        handler: "initialContent"});
    }
  },

  /**
   * Handle closure of posting application tabs. If the posting application
   * or host page closes, the state should reset. The posting form will close
   * as well.
   *
   * @param {integer} tabId The ID of the tab removed.
   * @param {removeInfo} removeInfo Information on the removal.
   *
   */
  tabRemoved: function(tabId, removeInfo) {

    if (postingProcess.postingResultTab === undefined ||
        postingProcess.postingApplicationTabId === undefined) {
      return;
    }

    // The tab generating the URL closed
    if (tabId === postingProcess.postingApplicationTabId) {
      chrome.tabs.sendMessage(postingProcess.postingResultTab.id, {pendingPost: false});
    } else if (tabId === postingProcess.postingResultTab.id) {
      // The tab receiving the URL Closed
      chrome.tabs.remove(postingProcess.postingApplicationTabId);
    }
    postingProcess.postingResultTab = undefined;
    postingProcess.postingApplicationTabId = undefined;
    postingProcess.postingApplicationStartingValue = "";
  },

  // Remembers where the PrivlyUrl will be placed based on the context menu
  postingResultTab: undefined,
  postingApplicationTabId: undefined,
  postingApplicationStartingValue: ""

}

// Informs the user that they must have a developer account to post new content
chrome.contextMenus.create({
    "title": "Privly is in Alpha. Do not assume your privacy.",
    "contexts": ["editable"],
    "enabled": false
  });

// Creates the PlainPost context menu
chrome.contextMenus.create({
    "title": "New unencrypted message - PlainPost",
    "contexts": ["editable"],
    "onclick" : function(info, tab) {
        postingProcess.postingHandler(info, tab, "PlainPost");
    }
  });

// Creates the ZeroBin context menu
chrome.contextMenus.create({
    "title": "New encrypted message - ZeroBin",
    "contexts": ["editable"],
    "onclick" : function(info, tab) {
        postingProcess.postingHandler(info, tab, "ZeroBin");
    }
  });

// Creates the History context menu
chrome.contextMenus.create({
    "title": "View History",
    "contexts": ["editable"],
    "onclick" : function(info, tab) {
        postingProcess.postingHandler(info, tab, "History");
    }
  });

// Initialize message listeners
chrome.extension.onMessage.addListener(postingProcess.initializeMessagePathway);
chrome.extension.onMessage.addListener(postingProcess.receiveNewPrivlyUrl);
chrome.extension.onMessage.addListener(postingProcess.sendInitialContent);

// Handle the request sent from post_new_link.js when clicking the Privly button
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.ask === "newPost") {

      // The info parameter is 0
      postingProcess.postingHandler(0, sender.tab, "Help");
    }
  });

// Handle the request sent from post_new_link.js to display a notfication
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.ask === "showNotification") {
      var notification = new Notification("There is already an open window of a pending Privly post",
        {icon: "images/logo_48.png"});
      notification.show();
    }
  });

// Handle closure of posting application tabs
chrome.tabs.onRemoved.addListener(postingProcess.tabRemoved);
<|endoftext|>


<commit_before>function showhideCategories(hdr,on) {
  var table = hdr.parentNode.parentNode.parentNode,
      newDisplay = on ? '' : 'none',
      nameList = new Array(), name;
  for (var i = 1; i < table.rows.length; i++) {
    if (on || table.rows[i].cells.length == 1)
      table.rows[i].style.display = newDisplay;
     else {
      // Hide duplicate rows for a plugin when not viewing by-category
      name = table.rows[i].cells[1].getAttribute('data');
      if (nameList[name] == 1) table.rows[i].style.display = 'none';
      nameList[name] = 1;
    }
  }
}
function showhideCategory(col) {
  var row = col.parentNode.nextSibling;
  var newDisplay = row && row.style.display == 'none' ? '' : 'none';
  for (; row && row.cells.length > 1; row = row.nextSibling)
    row.style.display = newDisplay;
}

Behaviour.specify("#filter-box", '_table', 0, function(e) {
      function applyFilter() {
          var filter = e.value.toLowerCase();
          ["TR.plugin","TR.plugin-category"].each(function(clz) {
            var items = document.getElementsBySelector(clz);
            for (var i=0; i<items.length; i++) {
                var visible = (filter=="" || items[i].innerHTML.toLowerCase().indexOf(filter)>=0);
                items[i].style.display = (visible ? "" : "none");
            }
          });

          layoutUpdateCallback.call();
      }

      e.onkeyup = applyFilter;
  });
<commit_msg>Indentation to make diff smaller.<commit_after>function showhideCategories(hdr,on) {
  var table = hdr.parentNode.parentNode.parentNode,
      newDisplay = on ? '' : 'none',
      nameList = new Array(), name;
  for (var i = 1; i < table.rows.length; i++) {
    if (on || table.rows[i].cells.length == 1)
      table.rows[i].style.display = newDisplay;
     else {
      // Hide duplicate rows for a plugin when not viewing by-category
      name = table.rows[i].cells[1].getAttribute('data');
      if (nameList[name] == 1) table.rows[i].style.display = 'none';
      nameList[name] = 1;
    }
  }
}
function showhideCategory(col) {
  var row = col.parentNode.nextSibling;
  var newDisplay = row && row.style.display == 'none' ? '' : 'none';
  for (; row && row.cells.length > 1; row = row.nextSibling)
    row.style.display = newDisplay;
}

Behaviour.specify("#filter-box", '_table', 0, function(e) {
      function applyFilter() {
          var filter = e.value.toLowerCase();
          ["TR.plugin","TR.plugin-category"].each(function(clz) {
            var items = document.getElementsBySelector(clz);
            for (var i=0; i<items.length; i++) {
                var visible = (filter=="" || items[i].innerHTML.toLowerCase().indexOf(filter)>=0);
                items[i].style.display = (visible ? "" : "none");
            }
          });

          layoutUpdateCallback.call();
      }

      e.onkeyup = applyFilter;
});
<|endoftext|>


<commit_before>import { PureComponent, createElement } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router';
import { getLocationParamUpdated } from 'utils/navigation';
import qs from 'query-string';

import NdcSdgLinkagesTableComponent from './ndc-sdg-linkages-table-component';
import {
  getParsedGoals,
  getGoalSelected
} from './ndc-sdg-linkages-table-selectors';

const mapStateToProps = (state, { location }) => {
  const { ndcsSdgsMeta } = state;
  const selectedGoal = qs.parse(location.search).goal;
  const sdgData = {
    selectedGoal,
    meta: ndcsSdgsMeta.data
  };
  return {
    goals: getParsedGoals(sdgData),
    selectedGoal: getGoalSelected(sdgData)
  };
};

class NdcSdgLinkagesTableContainer extends PureComponent {
  updateUrlParam(param, clear) {
    const { history, location } = this.props;
    history.replace(getLocationParamUpdated(location, param, clear));
  }

  handleClickGoal = sdgNumber => {
    this.updateUrlParam({ name: 'goal', value: sdgNumber });
  };

  handleClickClose = () => {
    this.updateUrlParam({ name: 'goal', value: '' });
  };

  render() {
    return createElement(NdcSdgLinkagesTableComponent, {
      ...this.props,
      handleClickGoal: this.handleClickGoal,
      handleClickClose: this.handleClickClose
    });
  }
}

NdcSdgLinkagesTableContainer.propTypes = {
  history: PropTypes.object.isRequired,
  location: PropTypes.object.isRequired
};

export { default as component } from './ndc-sdg-linkages-table-component';
export { default as styles } from './ndc-sdg-linkages-table-styles';

export default withRouter(
  connect(mapStateToProps, null)(NdcSdgLinkagesTableContainer)
);
<commit_msg>Clear target on close<commit_after>import { PureComponent, createElement } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router';
import { getLocationParamUpdated } from 'utils/navigation';
import qs from 'query-string';

import NdcSdgLinkagesTableComponent from './ndc-sdg-linkages-table-component';
import {
  getParsedGoals,
  getGoalSelected
} from './ndc-sdg-linkages-table-selectors';

const mapStateToProps = (state, { location }) => {
  const { ndcsSdgsMeta } = state;
  const selectedGoal = qs.parse(location.search).goal;
  const sdgData = {
    selectedGoal,
    meta: ndcsSdgsMeta.data
  };
  return {
    goals: getParsedGoals(sdgData),
    selectedGoal: getGoalSelected(sdgData)
  };
};

class NdcSdgLinkagesTableContainer extends PureComponent {
  updateUrlParam(param, clear) {
    const { history, location } = this.props;
    history.replace(getLocationParamUpdated(location, param, clear));
  }

  handleClickGoal = sdgNumber => {
    this.updateUrlParam({ name: 'goal', value: sdgNumber });
  };

  handleClickClose = () => {
    this.props.onTargetHover(null);
    this.updateUrlParam({ name: 'goal', value: '' });
  };

  render() {
    return createElement(NdcSdgLinkagesTableComponent, {
      ...this.props,
      handleClickGoal: this.handleClickGoal,
      handleClickClose: this.handleClickClose
    });
  }
}

NdcSdgLinkagesTableContainer.propTypes = {
  history: PropTypes.object.isRequired,
  location: PropTypes.object.isRequired,
  onTargetHover: PropTypes.func.isRequired
};

export { default as component } from './ndc-sdg-linkages-table-component';
export { default as styles } from './ndc-sdg-linkages-table-styles';

export default withRouter(
  connect(mapStateToProps, null)(NdcSdgLinkagesTableContainer)
);
<|endoftext|>


<commit_before>/**
 * Instance of class created
 * @type Object
 */
const invIndex = new InvertedIndex();
/**
 * Controller handling basic features of app
 * @param  {Object} $scope Binds the view with the controller
 * @return {Object}        [description]
 */
const MainController = ($scope) => {
  $scope.message = 'Please upload a valid .json file.';
  $scope.word = 'info';
  $scope.fileNames = [];
  $scope.fileObjects = {};
  $scope.showIndex = true;
  $scope.fileUpload = (event) => {
    const allUploads = event.target;
    for (let count = 0; count < allUploads.files.length; count += 1) {
      const uploadedFile = allUploads.files[count],
        singleFileName = uploadedFile.name;
      invIndex.readFile(uploadedFile).then((content) => {
        if (!invIndex.validateFile(singleFileName, JSON.parse(content))) {
          $scope.$apply(() => {
            $scope.message = `${singleFileName} is not a valid .json file.`;
            $scope.word = 'danger';
            return $scope.message;
          });
        } else {
          $scope.message = 'Upload successfull';
          $scope.word = 'success';
          $scope.fileObjects[singleFileName] = JSON
            .parse(content);
          if ((!$scope.fileNames
              .includes(uploadedFile.name))) {
            $scope.$apply(() => $scope.fileNames.push(uploadedFile.name));
          }
        }
      });
    }
    return $scope.fileObjects;
  };
  document.querySelector('#all-files')
  .addEventListener('change', $scope.fileUpload);

  $scope.createIndex = (selectFile) => {
    $scope.showIndex = true;
    const fileContent = $scope.fileObjects[selectFile],
      fileName = selectFile;
    if (invIndex.createIndex(fileName, fileContent)) {
      $scope.allIndicies = {};
      const indexed = invIndex.getIndex(fileName),
        uniqueWords = Object.keys(indexed),
        numOfBook = $scope.getNumOfBooks(fileName);
      $scope.allIndicies[fileName] = {
        uniqueWords,
        numOfBook,
        indexed
      };
    }
    if ($scope.allIndicies[fileName]) {
      $scope.message = `Index created for ${fileName}`;
      $scope.word = 'success';
      return true;
    }
    $scope.message = 'No index created';
    $scope.word = 'info';
    $scope.allIndicies = {};
  };
  /**
   * Function to get book count in a file
   * @param  {Object} fileName
   * @return {Array} An array of all files
   */
  $scope.getNumOfBooks = (fileName) => {
    const fileContent = $scope.fileObjects[fileName],
      arr = [];
    for (let i = 0; i < fileContent.length; i += 1) {
      arr.push(i);
    }
    return arr;
  };
  /**
   * Function to search through index created
   * @param  {Object} fileName Object pointing to file
   * @param  {String} query    Search term
   * @return {Object}          Object containing search result
   */
  $scope.searchIndex = (fileName, query) => {
    const fileArr = [];
    const queriedWords = invIndex.tokenize(query).toString();
    fileArr.push(fileName);
    if ($scope.createIndex) {
      $scope.showIndex = false;
      $scope.searchedIndices = {};
      const searched = invIndex.searchIndex(fileArr, query),
        books = Object.keys(searched),
        totalBooks = $scope.getNumOfBooks(fileName);
      $scope.searchedIndices = {
        books,
        totalBooks,
        searched
      };
    }
    if ($scope.searchedIndices) {
      $scope.message = `Search Index created for word(s) '${queriedWords}'`;
      $scope.word = 'success';
      return true;
    }
  };
};
/**
 * Function to handle icon display inside table
 * @return {String} String referencing and icon name.
 */
const tableIcon = () => (input, arr) => {
  if (arr.includes(input)) {
    return 'check';
  }
  return 'dash';
};
MainController.$inject = ['$scope'];
/**
 * Module declaration
 */
angular.module('mainApp', [])
.controller('MainController', MainController)
.filter('iconCheck', tableIcon);
<commit_msg>function renamed<commit_after>/**
 * Instance of class created
 * @type Object
 */
const invIndex = new InvertedIndex();
/**
 * Controller handling basic features of app
 * @param  {Object} $scope Binds the view with the controller
 * @return {Object}        [description]
 */
const MainController = ($scope) => {
  $scope.message = 'Please upload a valid .json file.';
  $scope.word = 'info';
  $scope.fileNames = [];
  $scope.fileObjects = {};
  $scope.showIndex = true;
  $scope.fileUpload = (event) => {
    const allUploads = event.target;
    for (let count = 0; count < allUploads.files.length; count += 1) {
      const uploadedFile = allUploads.files[count],
        singleFileName = uploadedFile.name;
      invIndex.readFile(uploadedFile).then((content) => {
        if (!invIndex.validateFile(singleFileName, JSON.parse(content))) {
          $scope.$apply(() => {
            $scope.message = `${singleFileName} is not a valid .json file.`;
            $scope.word = 'danger';
            return $scope.message;
          });
        } else {
          $scope.message = 'Upload successfull';
          $scope.word = 'success';
          $scope.fileObjects[singleFileName] = JSON
            .parse(content);
          if ((!$scope.fileNames
              .includes(uploadedFile.name))) {
            $scope.$apply(() => $scope.fileNames.push(uploadedFile.name));
          }
        }
      });
    }
    return $scope.fileObjects;
  };
  document.querySelector('#all-files')
  .addEventListener('change', $scope.fileUpload);

  $scope.createIndex = (selectFile) => {
    $scope.showIndex = true;
    const fileContent = $scope.fileObjects[selectFile],
      fileName = selectFile;
    if (invIndex.createIndex(fileName, fileContent)) {
      $scope.allIndicies = {};
      const indexed = invIndex.getIndex(fileName),
        uniqueWords = Object.keys(indexed),
        totalBooks = $scope.getTotalBooks(fileName);
      $scope.allIndicies[fileName] = {
        uniqueWords,
        totalBooks,
        indexed
      };
    }
    if ($scope.allIndicies[fileName]) {
      $scope.message = `Index created for ${fileName}`;
      $scope.word = 'success';
      return true;
    }
    $scope.message = 'No index created';
    $scope.word = 'info';
    $scope.allIndicies = {};
  };
  /**
   * Function to get book count in a file
   * @param  {Object} fileName
   * @return {Array} An array of all files
   */
  $scope.getTotalBooks = (fileName) => {
    const fileContent = $scope.fileObjects[fileName],
      arr = [];
    for (let i = 0; i < fileContent.length; i += 1) {
      arr.push(i);
    }
    return arr;
  };
  /**
   * Function to search through index created
   * @param  {Object} fileName Object pointing to file
   * @param  {String} query    Search term
   * @return {Object}          Object containing search result
   */
  $scope.searchIndex = (fileName, query) => {
    const fileArr = [];
    const queriedWords = invIndex.tokenize(query).toString();
    fileArr.push(fileName);
    if ($scope.createIndex) {
      $scope.showIndex = false;
      $scope.searchedIndices = {};
      const searched = invIndex.searchIndex(fileArr, query),
        books = Object.keys(searched),
        totalBooks = $scope.getTotalBooks(fileName);
      $scope.searchedIndices = {
        books,
        totalBooks,
        searched
      };
    }
    if ($scope.searchedIndices) {
      $scope.message = `Search Index created for word(s) '${queriedWords}'`;
      $scope.word = 'success';
      return true;
    }
  };
};
/**
 * Function to handle icon display inside table
 * @return {String} String referencing and icon name.
 */
const tableIcon = () => (input, arr) => {
  if (arr.includes(input)) {
    return 'check';
  }
  return 'dash';
};
MainController.$inject = ['$scope'];
/**
 * Module declaration
 */
angular.module('mainApp', [])
.controller('MainController', MainController)
.filter('iconCheck', tableIcon);
<|endoftext|>


<commit_before>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'

/* eslint-disable no-new */
new Vue({
  el: '#app',
  template: '<App/>',
  components: { App }
})
<commit_msg>Import router<commit_after>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import { VueRouter, router } from './router'
import App from './App'

Vue.use(VueRouter)

/* eslint-disable no-new */
new Vue({
  router,
  el: '#app',
  template: '<App/>',
  components: { App }
})
<|endoftext|>


<commit_before>describe("clear authorship colors button", function(){
  //create a new pad before each test run
  beforeEach(function(cb){
    helper.newPad(cb);
    this.timeout(60000);
  });

  it("makes text clear authorship colors", function(done) {
    var inner$ = helper.padInner$;
    var chrome$ = helper.padChrome$;

    // override the confirm dialogue functioon
    helper.padChrome$.window.confirm = function(){
      return true;
    }

    //get the first text element out of the inner iframe
    var $firstTextElement = inner$("div").first();

    // Get the original text
    var originalText = inner$("div").first().text();

    // Set some new text
    var sentText = "Hello";

    //select this text element
    $firstTextElement.sendkeys('{selectall}');
    $firstTextElement.sendkeys(sentText);
    $firstTextElement.sendkeys('{rightarrow}');

    helper.waitFor(function(){
      return inner$("div span").first().attr("class").indexOf("author") !== -1; // wait until we have the full value available
    }).done(function(){
      //IE hates you if you don't give focus to the inner frame bevore you do a clearAuthorship
      inner$("div").first().focus();

      //get the clear authorship colors button and click it
      var $clearauthorshipcolorsButton = chrome$(".buttonicon-clearauthorship");
      $clearauthorshipcolorsButton.click();

      // does the first divs span include an author class?
      console.log(inner$("div span").first().attr("class"));
      var hasAuthorClass = inner$("div span").first().attr("class").indexOf("author") !== -1;
      //expect(hasAuthorClass).to.be(false);

      // does the first div include an author class?
      var hasAuthorClass = inner$("div").first().attr("class").indexOf("author") !== -1;
      expect(hasAuthorClass).to.be(false);

      done();
    });

  });
});
<commit_msg>recognize reconnect in clear_authorship_colors test<commit_after>describe("clear authorship colors button", function(){
  //create a new pad before each test run
  beforeEach(function(cb){
    helper.newPad(cb);
    this.timeout(60000);
  });

  it("makes text clear authorship colors", function(done) {
    var inner$ = helper.padInner$;
    var chrome$ = helper.padChrome$;

    // override the confirm dialogue functioon
    helper.padChrome$.window.confirm = function(){
      return true;
    }

    //get the first text element out of the inner iframe
    var $firstTextElement = inner$("div").first();

    // Get the original text
    var originalText = inner$("div").first().text();

    // Set some new text
    var sentText = "Hello";

    //select this text element
    $firstTextElement.sendkeys('{selectall}');
    $firstTextElement.sendkeys(sentText);
    $firstTextElement.sendkeys('{rightarrow}');

    helper.waitFor(function(){
      return inner$("div span").first().attr("class").indexOf("author") !== -1; // wait until we have the full value available
    }).done(function(){
      //IE hates you if you don't give focus to the inner frame bevore you do a clearAuthorship
      inner$("div").first().focus();

      //get the clear authorship colors button and click it
      var $clearauthorshipcolorsButton = chrome$(".buttonicon-clearauthorship");
      $clearauthorshipcolorsButton.click();

      // does the first divs span include an author class?
      console.log(inner$("div span").first().attr("class"));
      var hasAuthorClass = inner$("div span").first().attr("class").indexOf("author") !== -1;
      //expect(hasAuthorClass).to.be(false);

      // does the first div include an author class?
      var hasAuthorClass = inner$("div").first().attr("class").indexOf("author") !== -1;
      expect(hasAuthorClass).to.be(false);

      var disconnectVisible = chrome$("div.disconnected").attr("class").indexOf("visible") === -1
      expect(disconnectVisible).to.be(false);

      done();
    });

  });
});
<|endoftext|>


<commit_before>(function(angular){

	'use strict';

	/**
	 * @author Arslan Anjum
	 */

	var apiWrapperModule = angular.module('apiWrapper',[]);

	apiWrapperModule.service('apiWrapper',['$http','api','$timeout','$q',function($http,api,$timeout,$q){

		var projection;

		var $scope;
		var page
		var size
		var sort;
		var order;
		var totalPages;
		var totalElements;
		var hasNext;
		var hasPrevious;
		var doNotUseProjection;

		/*
		    Passive api means:
		        1- None Found wont be toasted
		        2- Received Data wont be set on a $scope variable
		*/
		var isItAPassiveApi;

        var resetOnNoneFound;

		var entityName;
		var searchEntity;
		var searchParams;
		var variableName;

		var apiWrapper = function($scope){
			this.$scope = $scope;
			this.projection = 'detail';
			this.searchParams = [];
		}

		apiWrapper.prototype.configPagination = function(page,size,sort,order){
			this.page=page;
			this.size=size;
			this.sort=sort;
			this.order=order;
			return this;
		}
		/*
		    Configures apiWrapper for fetching reference data
		    page=0;size=200;sort=entityId;order=asc
		*/
		apiWrapper.prototype.configFor200Records = function(collection){
		    this.page=0;
		    this.size=200;
		    this.sort=this.getSingular(collection) + 'Id';
		    this.order='asc';
		    this.entityName = collection;
		    return this;
		}

		/*
		    Configures apiWrapper for fetching data with following params
            page=0;size=20;sort=entityId;order=asc
		*/
		apiWrapper.prototype.configFor20Records = function(collection){
		    this.page=0;
            this.size=20;
            this.sort=this.getSingular(collection) + 'Id';
            this.order='asc';
            this.entityName = collection;
            return this;
		}
		apiWrapper.prototype.withOrder = function(order){
		    this.order = order;
		    return this;
		}
		apiWrapper.prototype.passiveApi = function(){
		    this.isItAPassiveApi = true;
		    return this;
		}
		apiWrapper.prototype.withResetOnNoneFound = function(){
		    this.resetOnNoneFound = true;
		    return this;
		}
		apiWrapper.prototype.withNoProjection = function(){
		    this.doNotUseProjection = true;
		    return this;
		}
		apiWrapper.prototype.setVariableName = function(variableName){
		    this.variableName = variableName;
		    return this;
		}
		apiWrapper.prototype.setSearchEntity = function(searchEntity){
			this.searchEntity = searchEntity;
			return this;
		}
		apiWrapper.prototype.setSearchParams = function (searchParam, searchParamValue){
		    var obj = {};
		    obj[searchParam] = searchParamValue;
			this.searchParams.push(obj);
			return this;
		}
		apiWrapper.prototype.withSearchParams = function (searchParams){
		    this.searchParams = angular.copy(searchParams);
		    return this;
		}
		apiWrapper.prototype.resetSearchParams = function(){
		    this.searchParams = [];
		    return this;
		}
		apiWrapper.prototype.resetPage = function(){
		    this.page=0;
		    return this;
		}
		apiWrapper.prototype.resetSearchEntity = function(){
		    this.searchEntity = null;
		    return this;
		}
		apiWrapper.prototype.setProjection = function (projection){
			this.projection = projection;
			return this;
		}
		apiWrapper.prototype.setEntityName = function(entityName){
			this.entityName = entityName;
			return this;
		}
		apiWrapper.prototype.applyMaterialSelect = function(){
			$timeout(function(){
				$('select').material_select();
			},500);
		}
		apiWrapper.prototype.applyInitDatePicker = function(){
			var that = this;
			$timeout(function(){
				$('.datepicker').pickadate({
                    selectMonths : true,
                    selectYears : 15,
                    format : 'yyyy-mm-dd',
                    closeOnSelect: true
                });
			},500);
		}
		apiWrapper.prototype.toast = function(msg){
			Materialize.toast(msg, 2500,'blue rounded');
		}
		apiWrapper.prototype.isValid = function(argument){
			if (	argument === undefined ||
					argument === null ||
					argument === '' ||
					argument.length === 0){
				return false;
			}
			else
				return true;
		}

		/*
		    Fetches reference data for drop downs etc
		    Would check if that data is already present on $scope
		    Would set the data at $scope[entityName]
		*/
		apiWrapper.prototype.fetchReferenceData = function(entityName,onSuccess){

			var that = this;
			if (!that.isValid(that.$scope[entityName])){
			    api.getReferenceData(entityName,function(response){
                    response = response.data;
                    that.$scope[entityName] = response._embedded[entityName];
                    if (that.isValid(onSuccess)){
                        onSuccess(response,entityName);
                    }
                });
			}
		}

		/*
		    Fetches collection with entityName
		    arguments can be
		        page
		        size
		        sort
		        order
		        projection
		        search arguments -> set using setSearchParams
		*/
		apiWrapper.prototype.fetchSortedPage = function(onSuccess,onNoneFound,onError){
			var that=this;

			var args = [];

			if (!this.doNotUseProjection)
			    args.push({'projection':this.projection});
            if (this.isValid(this.page))
                args.push({'page':that.page});
            if (this.isValid(this.size))
                args.push({'size':that.size});
            if (this.isValid(this.sort) && this.isValid(this.order))
                args.push({'sort':that.sort + ',' + that.order});

            for (var i=0;i<this.searchParams.length;i++){
                args.push(this.searchParams[i]);
            }

            api.fetchSortedPage(
                that.entityName,
                that.searchEntity,
                args,
                that.$scope,
                function(response){
                   response = response.data;
                   var noneFound = false;
                   if (!that.isValid(response._embedded[that.entityName])){
                       if (!that.isItAPassiveApi){
                            that.toast("None Found");
                            if (that.resetOnNoneFound){
                                if (that.isValid(that.variableName))
                                    that.$scope[that.variableName] = [];
                                else
                                    that.$scope[that.entityName] = [];
                            }
                        }
                       noneFound = true;
                   }else{
                       if (!that.isItAPassiveApi){
                           if (that.isValid(that.variableName))
                                that.$scope[that.variableName] = response._embedded[that.entityName];
                           else
                                that.$scope[that.entityName] = response._embedded[that.entityName];
                       }
                   }

                   if (!that.isItAPassiveApi){
                       that.totalPages = response.page.totalPages;
                       that.totalElements = response.page.totalElements;
                       that.hasNext = (response._links.next != null);
                       that.hasPrevious = (response._links.prev != null);
                       that.applyMaterialSelect();
                       that.applyInitDatePicker();
                   }

                   if (noneFound){
                        if (that.isValid(onNoneFound)) onNoneFound(response,that.$scope,that);
                   }else{
                        if (that.isValid(onSuccess)) onSuccess(response,that.$scope,that);
                   }
               },
               function(error){
                   if (!that.isItAPassiveApi){
                       that.totalPages = null;
                       that.totalElements = null;
                       that.hasNext = null;
                       that.hasPrevious = null
                       that.applyMaterialSelect();
                       that.applyInitDatePicker();
                   }
                   if (that.isValid(onError)) onError(error,$scope,that);
               }
            );
		}

		/*Pagination Functions*/
		apiWrapper.prototype.fetchNextPage = function(){
			if (this.page + 1 < this.totalPages){
				this.page = this.page + 1;
				this.fetchSortedPage();
			}
		}
		apiWrapper.prototype.fetchPreviousPage = function(){
			if (this.page > 0){
				this.page = this.page - 1;
				this.fetchSortedPage();
			}
		}
		apiWrapper.prototype.firstPage = function(){
			this.page = 0;
			this.fetchSortedPage();
		}
		apiWrapper.prototype.lastPage = function(){
			this.page = this.totalPages - 1;
			this.fetchSortedPage();
		}
        /*************************************/

		apiWrapper.prototype.getProfile = function(onSuccess,onError){

            var that = this;

            api.getProfile(
                    that.entityName,
                    function(response){onSuccess(response,that.$scope,that)},
                    function(error){onError(error)}
                    );
        }

        apiWrapper.prototype.create = function(entity,$scope,callBack,errorCallBack){
            var scope = this.$scope;
            var that = this;
            api.create(
                that.entityName,
                entity,
                $scope,
                function(response){
                    if (that.isValid(callBack))
			    callBack(response,scope);
                },
                function(response){
	            if (that.isValid(errorCallBack))
                           errorCallBack(response,scope);
                }
                );
        }

        apiWrapper.prototype.update = function(entity,$scope,callBack,errorCallBack){
            var that = this;
            api.update(
                that.entityName,
                entity,
                $scope,
                function(response){
                    if (that.isValid(callBack))
			    callBack(response,that.$scope);
                },
                errorCallBack);
        }

		apiWrapper.prototype.delete = function(object,onSuccess,onError){

			var that = this;

			if (!this.isValid(object)){
				this.toast('Invalid');
				return;
			}

			api.delete(
					object,
					that.$scope,
					function(){
						that.toast('Deleted');
						if (that.isValid(onSuccess))
							onSuccess(that.$scope);
					},
					function(){
						that.toast('Cannot Delete');
					}
				)
		}

		apiWrapper.prototype.getSingular = function (entity){
            var iesIndex = entity.lastIndexOf('ies');
            var esIndex = entity.lastIndexOf('es');
            var length = entity.length;

            if (iesIndex != -1 && iesIndex + 3 == length){
                return entity.substring(0,iesIndex) + 'y';
            }else if (esIndex != -1 && iesIndex + 2 == length){
                return entity.substring(0,esIndex);
            }else{
                return entity.substring(0,entity.length-1);
            }
        }

		return apiWrapper;
}]);
}(window.angular));
<commit_msg>Update apiWrapper.js<commit_after>(function(angular){

	'use strict';

	/**
	 * @author Arslan Anjum
	 */

	var apiWrapperModule = angular.module('apiWrapper',[]);

	apiWrapperModule.service('apiWrapper',['$http','api','$timeout','$q',function($http,api,$timeout,$q){

		var projection;

		var $scope;
		var page
		var size
		var sort;
		var order;
		var totalPages;
		var totalElements;
		var hasNext;
		var hasPrevious;
		var doNotUseProjection;
		var selectId;

		/*
		    Passive api means:
		        1- None Found wont be toasted
		        2- Received Data wont be set on a $scope variable
		*/
		var isItAPassiveApi;

        var resetOnNoneFound;

		var entityName;
		var searchEntity;
		var searchParams;
		var variableName;

		var apiWrapper = function($scope){
			this.$scope = $scope;
			this.projection = 'detail';
			this.searchParams = [];
			this.selectId = 'select';
		}

		apiWrapper.prototype.configPagination = function(page,size,sort,order){
			this.page=page;
			this.size=size;
			this.sort=sort;
			this.order=order;
			return this;
		}
		/*
		    Configures apiWrapper for fetching reference data
		    page=0;size=200;sort=entityId;order=asc
		*/
		apiWrapper.prototype.configFor200Records = function(collection){
		    this.page=0;
		    this.size=200;
		    this.sort=this.getSingular(collection) + 'Id';
		    this.order='asc';
		    this.entityName = collection;
		    return this;
		}

		/*
		    Configures apiWrapper for fetching data with following params
            page=0;size=20;sort=entityId;order=asc
		*/
		apiWrapper.prototype.configFor20Records = function(collection){
		    this.page=0;
            this.size=20;
            this.sort=this.getSingular(collection) + 'Id';
            this.order='asc';
            this.entityName = collection;
            return this;
		}
		apiWrapper.prototype.withOrder = function(order){
		    this.order = order;
		    return this;
		}
		apiWrapper.prototype.passiveApi = function(){
		    this.isItAPassiveApi = true;
		    return this;
		}
		apiWrapper.prototype.withResetOnNoneFound = function(){
		    this.resetOnNoneFound = true;
		    return this;
		}
		apiWrapper.prototype.withNoProjection = function(){
		    this.doNotUseProjection = true;
		    return this;
		}
		apiWrapper.prototype.setVariableName = function(variableName){
		    this.variableName = variableName;
		    return this;
		}
		apiWrapper.prototype.setSearchEntity = function(searchEntity){
			this.searchEntity = searchEntity;
			return this;
		}
		apiWrapper.prototype.setSearchParams = function (searchParam, searchParamValue){
		    var obj = {};
		    obj[searchParam] = searchParamValue;
			this.searchParams.push(obj);
			return this;
		}
		apiWrapper.prototype.withSearchParams = function (searchParams){
		    this.searchParams = angular.copy(searchParams);
		    return this;
		}
		apiWrapper.prototype.resetSearchParams = function(){
		    this.searchParams = [];
		    return this;
		}
		apiWrapper.prototype.resetPage = function(){
		    this.page=0;
		    return this;
		}
		apiWrapper.prototype.resetSearchEntity = function(){
		    this.searchEntity = null;
		    return this;
		}
		apiWrapper.prototype.setProjection = function (projection){
			this.projection = projection;
			return this;
		}
		apiWrapper.prototype.setEntityName = function(entityName){
			this.entityName = entityName;
			return this;
		}
		apiWrapper.prototype.setSelectId = function(selectId){
			this.selectId = selectId;
			return this;
		}
		apiWrapper.prototype.applyMaterialSelect = function(){
			$timeout(function(){
				$(this.selectId).material_select();
			},500);
		}
		apiWrapper.prototype.applyInitDatePicker = function(){
			var that = this;
			$timeout(function(){
				$('.datepicker').pickadate({
                    selectMonths : true,
                    selectYears : 15,
                    format : 'yyyy-mm-dd',
                    closeOnSelect: true
                });
			},500);
		}
		apiWrapper.prototype.toast = function(msg){
			Materialize.toast(msg, 2500,'blue rounded');
		}
		apiWrapper.prototype.isValid = function(argument){
			if (	argument === undefined ||
					argument === null ||
					argument === '' ||
					argument.length === 0){
				return false;
			}
			else
				return true;
		}

		/*
		    Fetches reference data for drop downs etc
		    Would check if that data is already present on $scope
		    Would set the data at $scope[entityName]
		*/
		apiWrapper.prototype.fetchReferenceData = function(entityName,onSuccess){

			var that = this;
			if (!that.isValid(that.$scope[entityName])){
			    api.getReferenceData(entityName,function(response){
                    response = response.data;
                    that.$scope[entityName] = response._embedded[entityName];
                    if (that.isValid(onSuccess)){
                        onSuccess(response,entityName);
                    }
                });
			}
		}

		/*
		    Fetches collection with entityName
		    arguments can be
		        page
		        size
		        sort
		        order
		        projection
		        search arguments -> set using setSearchParams
		*/
		apiWrapper.prototype.fetchSortedPage = function(onSuccess,onNoneFound,onError){
			var that=this;

			var args = [];

			if (!this.doNotUseProjection)
			    args.push({'projection':this.projection});
            if (this.isValid(this.page))
                args.push({'page':that.page});
            if (this.isValid(this.size))
                args.push({'size':that.size});
            if (this.isValid(this.sort) && this.isValid(this.order))
                args.push({'sort':that.sort + ',' + that.order});

            for (var i=0;i<this.searchParams.length;i++){
                args.push(this.searchParams[i]);
            }

            api.fetchSortedPage(
                that.entityName,
                that.searchEntity,
                args,
                that.$scope,
                function(response){
                   response = response.data;
                   var noneFound = false;
                   if (!that.isValid(response._embedded[that.entityName])){
                       if (!that.isItAPassiveApi){
                            that.toast("None Found");
                            if (that.resetOnNoneFound){
                                if (that.isValid(that.variableName))
                                    that.$scope[that.variableName] = [];
                                else
                                    that.$scope[that.entityName] = [];
                            }
                        }
                       noneFound = true;
                   }else{
                       if (!that.isItAPassiveApi){
                           if (that.isValid(that.variableName))
                                that.$scope[that.variableName] = response._embedded[that.entityName];
                           else
                                that.$scope[that.entityName] = response._embedded[that.entityName];
                       }
                   }

                   if (!that.isItAPassiveApi){
                       that.totalPages = response.page.totalPages;
                       that.totalElements = response.page.totalElements;
                       that.hasNext = (response._links.next != null);
                       that.hasPrevious = (response._links.prev != null);
                       that.applyMaterialSelect();
                       that.applyInitDatePicker();
                   }

                   if (noneFound){
                        if (that.isValid(onNoneFound)) onNoneFound(response,that.$scope,that);
                   }else{
                        if (that.isValid(onSuccess)) onSuccess(response,that.$scope,that);
                   }
               },
               function(error){
                   if (!that.isItAPassiveApi){
                       that.totalPages = null;
                       that.totalElements = null;
                       that.hasNext = null;
                       that.hasPrevious = null
                       that.applyMaterialSelect();
                       that.applyInitDatePicker();
                   }
                   if (that.isValid(onError)) onError(error,$scope,that);
               }
            );
		}

		/*Pagination Functions*/
		apiWrapper.prototype.fetchNextPage = function(){
			if (this.page + 1 < this.totalPages){
				this.page = this.page + 1;
				this.fetchSortedPage();
			}
		}
		apiWrapper.prototype.fetchPreviousPage = function(){
			if (this.page > 0){
				this.page = this.page - 1;
				this.fetchSortedPage();
			}
		}
		apiWrapper.prototype.firstPage = function(){
			this.page = 0;
			this.fetchSortedPage();
		}
		apiWrapper.prototype.lastPage = function(){
			this.page = this.totalPages - 1;
			this.fetchSortedPage();
		}
        /*************************************/

		apiWrapper.prototype.getProfile = function(onSuccess,onError){

            var that = this;

            api.getProfile(
                    that.entityName,
                    function(response){onSuccess(response,that.$scope,that)},
                    function(error){onError(error)}
                    );
        }

        apiWrapper.prototype.create = function(entity,$scope,callBack,errorCallBack){
            var scope = this.$scope;
            var that = this;
            api.create(
                that.entityName,
                entity,
                $scope,
                function(response){
                    if (that.isValid(callBack))
			    callBack(response,scope);
                },
                function(response){
	            if (that.isValid(errorCallBack))
                           errorCallBack(response,scope);
                }
                );
        }

        apiWrapper.prototype.update = function(entity,$scope,callBack,errorCallBack){
            var that = this;
            api.update(
                that.entityName,
                entity,
                $scope,
                function(response){
                    if (that.isValid(callBack))
			    callBack(response,that.$scope);
                },
                errorCallBack);
        }

		apiWrapper.prototype.delete = function(object,onSuccess,onError){

			var that = this;

			if (!this.isValid(object)){
				this.toast('Invalid');
				return;
			}

			api.delete(
					object,
					that.$scope,
					function(){
						that.toast('Deleted');
						if (that.isValid(onSuccess))
							onSuccess(that.$scope);
					},
					function(){
						that.toast('Cannot Delete');
					}
				)
		}

		apiWrapper.prototype.getSingular = function (entity){
            var iesIndex = entity.lastIndexOf('ies');
            var esIndex = entity.lastIndexOf('es');
            var length = entity.length;

            if (iesIndex != -1 && iesIndex + 3 == length){
                return entity.substring(0,iesIndex) + 'y';
            }else if (esIndex != -1 && iesIndex + 2 == length){
                return entity.substring(0,esIndex);
            }else{
                return entity.substring(0,entity.length-1);
            }
        }

		return apiWrapper;
}]);
}(window.angular));
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

// Perf measurements
global.perfStartTime = Date.now();

var app = require('electron').app;
var fs = require('fs');
var path = require('path');
var minimist = require('minimist');
var paths = require('./paths');

var args = minimist(process.argv, {
	string: ['user-data-dir', 'locale']
});

function stripComments(content) {
	var regexp = /("(?:[^\\\"]*(?:\\.)?)*")|('(?:[^\\\']*(?:\\.)?)*')|(\/\*(?:\r?\n|.)*?\*\/)|(\/{2,}.*?(?:(?:\r?\n)|$))/g;
	var result = content.replace(regexp, function (match, m1, m2, m3, m4) {
		// Only one of m1, m2, m3, m4 matches
		if (m3) {
			// A block comment. Replace with nothing
			return '';
		}
		else if (m4) {
			// A line comment. If it ends in \r?\n then keep it.
			var length_1 = m4.length;
			if (length_1 > 2 && m4[length_1 - 1] === '\n') {
				return m4[length_1 - 2] === '\r' ? '\r\n' : '\n';
			}
			else {
				return '';
			}
		}
		else {
			// We match a string
			return match;
		}
	});
	return result;
}

function getNLSConfiguration() {
	var locale = args['locale'];

	if (!locale) {
		var userData = app.getPath('userData');
		var localeConfig = path.join(userData, 'User', 'locale.json');
		if (fs.existsSync(localeConfig)) {
			try {
				var content = stripComments(fs.readFileSync(localeConfig, 'utf8'));
				var value = JSON.parse(content).locale;
				if (value && typeof value === 'string') {
					locale = value;
				}
			} catch (e) {
				// noop
			}
		}
	}

	var appLocale = app.getLocale();
	locale = locale || appLocale;
	// Language tags are case insensitve however an amd loader is case sensitive
	// To make this work on case preserving & insensitive FS we do the following:
	// the language bundles have lower case language tags and we always lower case
	// the locale we receive from the user or OS.
	locale = locale ? locale.toLowerCase() : locale;
	if (locale === 'pseudo') {
		return { locale: locale, availableLanguages: {}, pseudo: true };
	}
	var initialLocale = locale;
	if (process.env['VSCODE_DEV']) {
		return { locale: locale, availableLanguages: {} };
	}

	// We have a built version so we have extracted nls file. Try to find
	// the right file to use.

	// Check if we have an English locale. If so fall to default since that is our
	// English translation (we don't ship *.nls.en.json files)
	if (locale && (locale == 'en' || locale.startsWith('en-'))) {
		return { locale: locale, availableLanguages: {} };
	}

	function resolveLocale(locale) {
		while (locale) {
			var candidate = path.join(__dirname, 'vs', 'code', 'electron-main', 'main.nls.') + locale + '.js';
			if (fs.existsSync(candidate)) {
				return { locale: initialLocale, availableLanguages: { '*': locale } };
			} else {
				var index = locale.lastIndexOf('-');
				if (index > 0) {
					locale = locale.substring(0, index);
				} else {
					locale = null;
				}
			}
		}
		return null;
	}

	var resolvedLocale = resolveLocale(locale);
	if (!resolvedLocale && appLocale && appLocale !== locale) {
		resolvedLocale = resolveLocale(appLocale);
	}
	return resolvedLocale ? resolvedLocale : { locale: initialLocale, availableLanguages: {} };
}

function getNodeCachedDataDir() {

	// IEnvironmentService.isBuilt
	if (process.env['VSCODE_DEV']) {
		return Promise.resolve(undefined);
	}

	var dir = path.join(app.getPath('userData'), 'CachedData');

	return mkdirp(dir).then(undefined, err => { /*ignore*/ });
}

function mkdirp(dir) {
	return mkdir(dir)
		.then(null, function (err) {
			if (err && err.code === 'ENOENT') {
				var parent = path.dirname(dir);
				if (parent !== dir) { // if not arrived at root
					return mkdirp(parent)
						.then(function () {
							return mkdir(dir);
						});
				}
			}
			throw err;
		});
}

function mkdir(dir) {
	return new Promise(function (resolve, reject) {
		fs.mkdir(dir, function (err) {
			if (err && err.code !== 'EEXIST') {
				reject(err);
			} else {
				resolve(dir);
			}
		});
	});
}

// Set userData path before app 'ready' event and call to process.chdir
var userData = path.resolve(args['user-data-dir'] || paths.getDefaultUserDataPath(process.platform));
app.setPath('userData', userData);

// Update cwd based on environment and platform
try {
	if (process.platform === 'win32') {
		process.env['VSCODE_CWD'] = process.cwd(); // remember as environment variable
		process.chdir(path.dirname(app.getPath('exe'))); // always set application folder as cwd
	} else if (process.env['VSCODE_CWD']) {
		process.chdir(process.env['VSCODE_CWD']);
	}
} catch (err) {
	console.error(err);
}

// Mac: when someone drops a file to the not-yet running VSCode, the open-file event fires even before
// the app-ready event. We listen very early for open-file and remember this upon startup as path to open.
global.macOpenFiles = [];
app.on('open-file', function (event, path) {
	global.macOpenFiles.push(path);
});

var openUrls = [];
var onOpenUrl = function (event, url) {
	event.preventDefault();
	openUrls.push(url);
};

app.on('will-finish-launching', function () {
	app.on('open-url', onOpenUrl);
});

global.getOpenUrls = function () {
	app.removeListener('open-url', onOpenUrl);
	return openUrls;
};

// use '<UserData>/CachedData'-directory to store
// node/v8 cached data.
var nodeCachedDataDir = getNodeCachedDataDir().then(function (value) {
	if (value) {
		process.env['VSCODE_NODE_CACHED_DATA_DIR_' + process.pid] = value;
	}
});

// Load our code once ready
app.once('ready', function () {
	global.perfAppReady = Date.now();
	var nlsConfig = getNLSConfiguration();
	process.env['VSCODE_NLS_CONFIG'] = JSON.stringify(nlsConfig);

	nodeCachedDataDir.then(function () {
		require('./bootstrap-amd').bootstrap('vs/code/electron-main/main');
	}, console.error);
});
<commit_msg>uglify is ugly!<commit_after>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

// Perf measurements
global.perfStartTime = Date.now();

var app = require('electron').app;
var fs = require('fs');
var path = require('path');
var minimist = require('minimist');
var paths = require('./paths');

var args = minimist(process.argv, {
	string: ['user-data-dir', 'locale']
});

function stripComments(content) {
	var regexp = /("(?:[^\\\"]*(?:\\.)?)*")|('(?:[^\\\']*(?:\\.)?)*')|(\/\*(?:\r?\n|.)*?\*\/)|(\/{2,}.*?(?:(?:\r?\n)|$))/g;
	var result = content.replace(regexp, function (match, m1, m2, m3, m4) {
		// Only one of m1, m2, m3, m4 matches
		if (m3) {
			// A block comment. Replace with nothing
			return '';
		}
		else if (m4) {
			// A line comment. If it ends in \r?\n then keep it.
			var length_1 = m4.length;
			if (length_1 > 2 && m4[length_1 - 1] === '\n') {
				return m4[length_1 - 2] === '\r' ? '\r\n' : '\n';
			}
			else {
				return '';
			}
		}
		else {
			// We match a string
			return match;
		}
	});
	return result;
}

function getNLSConfiguration() {
	var locale = args['locale'];

	if (!locale) {
		var userData = app.getPath('userData');
		var localeConfig = path.join(userData, 'User', 'locale.json');
		if (fs.existsSync(localeConfig)) {
			try {
				var content = stripComments(fs.readFileSync(localeConfig, 'utf8'));
				var value = JSON.parse(content).locale;
				if (value && typeof value === 'string') {
					locale = value;
				}
			} catch (e) {
				// noop
			}
		}
	}

	var appLocale = app.getLocale();
	locale = locale || appLocale;
	// Language tags are case insensitve however an amd loader is case sensitive
	// To make this work on case preserving & insensitive FS we do the following:
	// the language bundles have lower case language tags and we always lower case
	// the locale we receive from the user or OS.
	locale = locale ? locale.toLowerCase() : locale;
	if (locale === 'pseudo') {
		return { locale: locale, availableLanguages: {}, pseudo: true };
	}
	var initialLocale = locale;
	if (process.env['VSCODE_DEV']) {
		return { locale: locale, availableLanguages: {} };
	}

	// We have a built version so we have extracted nls file. Try to find
	// the right file to use.

	// Check if we have an English locale. If so fall to default since that is our
	// English translation (we don't ship *.nls.en.json files)
	if (locale && (locale == 'en' || locale.startsWith('en-'))) {
		return { locale: locale, availableLanguages: {} };
	}

	function resolveLocale(locale) {
		while (locale) {
			var candidate = path.join(__dirname, 'vs', 'code', 'electron-main', 'main.nls.') + locale + '.js';
			if (fs.existsSync(candidate)) {
				return { locale: initialLocale, availableLanguages: { '*': locale } };
			} else {
				var index = locale.lastIndexOf('-');
				if (index > 0) {
					locale = locale.substring(0, index);
				} else {
					locale = null;
				}
			}
		}
		return null;
	}

	var resolvedLocale = resolveLocale(locale);
	if (!resolvedLocale && appLocale && appLocale !== locale) {
		resolvedLocale = resolveLocale(appLocale);
	}
	return resolvedLocale ? resolvedLocale : { locale: initialLocale, availableLanguages: {} };
}

function getNodeCachedDataDir() {

	// IEnvironmentService.isBuilt
	if (process.env['VSCODE_DEV']) {
		return Promise.resolve(undefined);
	}

	var dir = path.join(app.getPath('userData'), 'CachedData');

	return mkdirp(dir).then(undefined, function (err) { /*ignore*/ });
}

function mkdirp(dir) {
	return mkdir(dir)
		.then(null, function (err) {
			if (err && err.code === 'ENOENT') {
				var parent = path.dirname(dir);
				if (parent !== dir) { // if not arrived at root
					return mkdirp(parent)
						.then(function () {
							return mkdir(dir);
						});
				}
			}
			throw err;
		});
}

function mkdir(dir) {
	return new Promise(function (resolve, reject) {
		fs.mkdir(dir, function (err) {
			if (err && err.code !== 'EEXIST') {
				reject(err);
			} else {
				resolve(dir);
			}
		});
	});
}

// Set userData path before app 'ready' event and call to process.chdir
var userData = path.resolve(args['user-data-dir'] || paths.getDefaultUserDataPath(process.platform));
app.setPath('userData', userData);

// Update cwd based on environment and platform
try {
	if (process.platform === 'win32') {
		process.env['VSCODE_CWD'] = process.cwd(); // remember as environment variable
		process.chdir(path.dirname(app.getPath('exe'))); // always set application folder as cwd
	} else if (process.env['VSCODE_CWD']) {
		process.chdir(process.env['VSCODE_CWD']);
	}
} catch (err) {
	console.error(err);
}

// Mac: when someone drops a file to the not-yet running VSCode, the open-file event fires even before
// the app-ready event. We listen very early for open-file and remember this upon startup as path to open.
global.macOpenFiles = [];
app.on('open-file', function (event, path) {
	global.macOpenFiles.push(path);
});

var openUrls = [];
var onOpenUrl = function (event, url) {
	event.preventDefault();
	openUrls.push(url);
};

app.on('will-finish-launching', function () {
	app.on('open-url', onOpenUrl);
});

global.getOpenUrls = function () {
	app.removeListener('open-url', onOpenUrl);
	return openUrls;
};

// use '<UserData>/CachedData'-directory to store
// node/v8 cached data.
var nodeCachedDataDir = getNodeCachedDataDir().then(function (value) {
	if (value) {
		process.env['VSCODE_NODE_CACHED_DATA_DIR_' + process.pid] = value;
	}
});

// Load our code once ready
app.once('ready', function () {
	global.perfAppReady = Date.now();
	var nlsConfig = getNLSConfiguration();
	process.env['VSCODE_NLS_CONFIG'] = JSON.stringify(nlsConfig);

	nodeCachedDataDir.then(function () {
		require('./bootstrap-amd').bootstrap('vs/code/electron-main/main');
	}, console.error);
});
<|endoftext|>


<commit_before>import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';

module('Integration | Component | index-info', function (hooks) {
  setupRenderingTest(hooks);

  test('it renders', async function (assert) {
    await render(hbs`{{index-info}}`);

    assert
      .dom(this.element)
      .hasText(
        'Members by year 0 20112022 Repositories by year 0 20112021 DOIs by year 0 in 2021 20112021'
      );
  });
});
<commit_msg>Issue-516 - enable cypress tests to run on merge to master. (fix regressions)<commit_after>import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';

module('Integration | Component | index-info', function (hooks) {
  setupRenderingTest(hooks);

  test('it renders', async function (assert) {
    await render(hbs`{{index-info}}`);

    assert
      .dom(this.element)
      .hasText(
        'Members by year 0 20112021 Repositories by year 0 20112021 DOIs by year 0 in 2021 20112021'
      );
  });
});
<|endoftext|>