<commit_before>let utils = require('../utils/utils.js');
let RunCode = require('../core/runCode.js');

class Console {
  constructor(options) {
    this.events = options.events;
    this.plugins = options.plugins;
    this.version = options.version;
    this.contractsConfig = options.contractsConfig;
  }

  runCode(code) {
    RunCode.doEval(code);
  }

  processEmbarkCmd (cmd) {
    if (cmd === 'help' || cmd === __('help')) {
      let helpText = [
        __('Welcome to Embark') + ' ' + this.version,
        '',
        __('possible commands are:'),
        'versions - ' + __('display versions in use for libraries and tools like web3 and solc'),
        // TODO: only if the blockchain is actually active!
        // will need to pass te current embark state here
        'web3 - ' + __('instantiated web3.js object configured to the current environment'),
        'quit - ' + __('to immediatly exit (alias: exit)'),
        '',
        __('The web3 object and the interfaces for the deployed contracts and their methods are also available')
      ];
      return helpText.join('\n');
    } else if (['quit', 'exit', 'sair', 'sortir', __('quit')].indexOf(cmd) >= 0) {
      utils.exit();
    }
    return false;
  }

  executeCmd(cmd, callback) {
    var pluginCmds = this.plugins.getPluginsProperty('console', 'console');
    for (let pluginCmd of pluginCmds) {
      let pluginOutput = pluginCmd.call(this, cmd, {});
      if (pluginOutput !== false && pluginOutput !== 'false' && pluginOutput !== undefined) return callback(pluginOutput);
      //if (pluginOutput === undefined) return callback("");
    }

    let output = this.processEmbarkCmd(cmd);
    if (output) {
      return callback(output);
    }

    try {
      let result = RunCode.doEval(cmd);
      return callback(result);
    }
    catch (e) {
      if (e.message.indexOf('not defined') > 0) {
        return callback(("error: " + e.message).red + ("\n" + __("Type") + " " + "help".bold + " " + __("to see the list of available commands")).cyan);
      } else {
        return callback(e.message);
      }
    }
  }
}

module.exports = Console;
<commit_msg>remove unneeded code line<commit_after>let utils = require('../utils/utils.js');
let RunCode = require('../core/runCode.js');

class Console {
  constructor(options) {
    this.events = options.events;
    this.plugins = options.plugins;
    this.version = options.version;
    this.contractsConfig = options.contractsConfig;
  }

  runCode(code) {
    RunCode.doEval(code);
  }

  processEmbarkCmd (cmd) {
    if (cmd === 'help' || cmd === __('help')) {
      let helpText = [
        __('Welcome to Embark') + ' ' + this.version,
        '',
        __('possible commands are:'),
        'versions - ' + __('display versions in use for libraries and tools like web3 and solc'),
        // TODO: only if the blockchain is actually active!
        // will need to pass te current embark state here
        'web3 - ' + __('instantiated web3.js object configured to the current environment'),
        'quit - ' + __('to immediatly exit (alias: exit)'),
        '',
        __('The web3 object and the interfaces for the deployed contracts and their methods are also available')
      ];
      return helpText.join('\n');
    } else if (['quit', 'exit', 'sair', 'sortir', __('quit')].indexOf(cmd) >= 0) {
      utils.exit();
    }
    return false;
  }

  executeCmd(cmd, callback) {
    var pluginCmds = this.plugins.getPluginsProperty('console', 'console');
    for (let pluginCmd of pluginCmds) {
      let pluginOutput = pluginCmd.call(this, cmd, {});
      if (pluginOutput !== false && pluginOutput !== 'false' && pluginOutput !== undefined) return callback(pluginOutput);
    }

    let output = this.processEmbarkCmd(cmd);
    if (output) {
      return callback(output);
    }

    try {
      let result = RunCode.doEval(cmd);
      return callback(result);
    }
    catch (e) {
      if (e.message.indexOf('not defined') > 0) {
        return callback(("error: " + e.message).red + ("\n" + __("Type") + " " + "help".bold + " " + __("to see the list of available commands")).cyan);
      } else {
        return callback(e.message);
      }
    }
  }
}

module.exports = Console;
<|endoftext|>


<commit_before>import Underscore from 'underscore';
import d3 from 'd3';
import SettingsPanel from '../SettingsPanel';
import DatasetSettings from '../DatasetSettings';
import UploadView from './UploadView';
import myTemplate from './template.html';
import libraryFileIcon from '../../../images/light/library.svg';
import privateFileIcon from '../../../images/light/file_private.svg';
import publicFileIcon from '../../../images/light/file_public.svg';
import warningIcon from '../../../images/warning.svg';
import './style.scss';
let girder = window.girder;

let DatasetLibrary = DatasetSettings.extend({
  initialize: function () {
    DatasetSettings.prototype.initialize.apply(this, arguments);
    this.listenTo(window.mainPage.currentUser, 'rl:updateLibrary', () => {
      this.render();
    });
  },
  getSideMenu: function () {
    let sideMenu = DatasetSettings.prototype.getSideMenu.apply(this, arguments);
    // Override parts of the menu item from DatasetSettings
    sideMenu[0].items[2].focused = true;
    sideMenu[0].items[2].onclick = () => {
      window.mainPage.overlay.render('DatasetSettings');
    };
    return sideMenu;
  },
  createUploadSection: function () {
    if (window.mainPage.currentUser.isLoggedIn()) {
      this.uploadView = new UploadView({
        // Some girder views expect a parent, but
        // in this app, we just run them headless
        parentView: null,
        // Similar to girder's views, we want the
        // child to have access to this parent view
        // (but this has nothing to do with girder's
        // registerChild business)
        datasetLibrary: this
      });
      this.$el.find('#uploadSection')[0]
        .appendChild(this.uploadView.el);
      this.uploadView.delegateEvents();

      this.$el.find('#linkSection').show();
      this.$el.find('#loggedOutLinkSection').hide();
    } else {
      this.$el.find('#uploadSection')
        .append('
You must be logged in to upload files');

      this.$el.find('#linkSection').hide();
      this.$el.find('#loggedOutLinkSection').show();

      this.$el.find('.loginLink').on('click', () => {
        window.mainPage.overlay.render('LoginView');
      });
    }
  },
  attachLibraryListeners: function () {
    let self = this;

    // Listeners for existing dataset sections
    this.$el.find('#girderLink').on('click', () => {
      window.mainPage.router.openUserDirectoriesInGirder();
    });

    this.$el.find('#loginLink2').on('click', () => {
      window.mainPage.overlay.render('LoginView');
    });

    this.$el.find('#registerLink2').on('click', () => {
      window.mainPage.overlay.render('RegisterView');
    });

    // Listeners for new datset sections
    this.$el.find('#createLink').on('keyup', function () {
      // this refers to the DOM element
      // Validate the girder item ID (TODO: support other link types)
      self.validateGirderId(this.value);
    });

    this.$el.find('#createLinkButton').on('click', () => {
      let itemId = this.$el.find('#createLink').val();
      this.createGirderLink(itemId);
    });
  },
  startUpload: function () {
    console.log(this.$el.find('#uploadFile'));
  },
  createGirderLink: function (itemId) {
    window.mainPage.girderRequest({
      path: 'item/' + itemId + '/dataset',
      method: 'POST'
    }).then(datasetItem => {
      window.mainPage.getProject().then(project => {
        return project.setDataset(itemId, this.index);
      }).then(() => {
        window.mainPage.widgetPanels.toggleWidget({
          hashName: 'DatasetView' + this.index
        }, true);
        window.mainPage.overlay.closeOverlay();
      });
    });
  },
  validateGirderId: Underscore.debounce(function (itemId) {
    if (itemId) {
      this.linkToCreate = window.mainPage.girderRequest({
        path: 'item/' + itemId,
        type: 'GET'
      }).then(item => {
        if (!item || item['_modelType'] !== 'item') {
          return {
            errorMessage: '"' + this.value + '" is not a valid Girder item ID'
          };
        } else {
          return item;
        }
      }).catch(item => {
        return {
          errorMessage: '"' + this.value + '" is not a valid Girder item ID'
        };
      });
    } else {
      delete this.linkToCreate;
    }
    this.updateStaticSections();
  }, 600),
  updateStaticSections: function () {
    // Start out with all hideable form elements hidden
    this.$el.find('.newDatasetHideable').hide();

    // Update the upload interface
    if (this.uploadView) {
      this.uploadView.render();
    }

    // Set up the link interface
    // Start with the button disabled
    this.$el.find('#createLinkButton').prop('disabled', true);
    if (this.linkToCreate !== undefined) {
      // Show the spinner while we wait for link validation to finish
      this.$el.find('#linkSpinner').show();

      this.linkToCreate.then(linkResponse => {
        let errorMessage = null;
        if (!linkResponse) {
          errorMessage = 'Could not validate link';
        } else if ('errorMessage' in linkResponse) {
          errorMessage = linkResponse.errorMessage;
        }

        this.$el.find('#linkSpinner').hide();
        if (errorMessage !== null) {
          this.$el.find('#createLink').addClass('invalid');
          this.$el.find('#badLinkHelpText').text(errorMessage);
          this.$el.find('#badLinkHelp').show();
          this.$el.find('#createLinkHelp').show();
        } else {
          this.$el.find('#createLink').removeClass('invalid');
          this.$el.find('#createLinkButton').prop('disabled', false);
        }
      });
    }
  },
  showFileTypeWarning: function () {
    this.$el.find('#uploadFileFormatHelp').show();
  },
  hideFileTypeWarning: function () {
    this.$el.find('#uploadFileFormatHelp').hide();
  },
  updateDynamicSections: function () {
    // Get the set of datasets in the public library
    window.mainPage.girderRequest({
      path: 'resource/lookup?path=/collection/Resonant Lab Library/Data',
      type: 'GET'
    }).then(folder => {
      this.getFolderContents(folder, 'datasetLibrary', libraryFileIcon);
    }).catch(() => {
    }); // fail silently

    if (window.mainPage.currentUser.isLoggedIn()) {
      // The user is logged in

      // Get the set of the user's private datasets
      window.mainPage.girderRequest({
        path: 'folder/anonymousAccess/privateFolder',
        type: 'GET'
      }).then(folder => {
        this.getFolderContents(folder, 'privateDatasets', privateFileIcon);
      }).catch(() => {
      }); // fail silently

      // Get the set of the user's public projects
      window.mainPage.girderRequest({
        path: 'folder/anonymousAccess/publicFolder',
        type: 'GET'
      }).then(folder => {
        this.getFolderContents(folder, 'publicDatasets', publicFileIcon);
      }).catch(() => {
        // fail silently
      });
    } else {
      // The user is logged out
      // TODO: get the set of scratch datasets
      // "belonging" to this user
    }
  },
  render: Underscore.debounce(function () {
    DatasetSettings.prototype.updateBlurb.apply(this, []);
    // We use our own subtemplate, so only call
    // the grandparent superclass render function
    SettingsPanel.prototype.render.apply(this, arguments);
    if (!this.addedSubTemplate) {
      this.$el.find('#subclassContent').html(myTemplate);
      this.addedSubTemplate = true;

      // Only add the upload view from Girder once
      this.createUploadSection();

      // Only attach event listeners once
      this.attachLibraryListeners();

      // Because we debounce rendering, we need to add
      // the close listeners ourselves
      window.mainPage.overlay.addCloseListeners();

      // Start off with every hideable section hidden
      this.$el.find('.hideable').hide();
    }

    this.updateStaticSections();
    this.updateDynamicSections();
  }, 200),
  getFolderContents: function (folder, divId, icon) {
    let projects = new girder.collections.ItemCollection();
    projects.altUrl = 'item';
    projects.pageLimit = 100;
    projects.fetch({
      folderId: folder._id
    });
    projects.on('reset', (items) => {
      this.renderDatasets(items, divId, icon);
    });
  },
  renderDatasets: function (items, divId, icon) {
    let datasetModels = items.models.filter(d => {
      let meta = d.get('meta');
      return meta && meta.rlab && meta.rlab.itemType && meta.rlab.itemType === 'dataset';
    });

    if (datasetModels.length > 0) {
      this.$el.find('#' + divId + 'Section').show();
    }

    let libraryButtons = d3.select('#' + divId)
      .selectAll('.circleButton')
      .data(datasetModels, d => {
        return d.id + d.name();
      });

    let libraryButtonsEnter = libraryButtons.enter().append('div');
    libraryButtons.exit().remove();
    libraryButtons.attr('class', (d) => {
      if (window.mainPage.project &&
        d.id === window.mainPage.project.getDatasetId(this.index)) {
        return 'current circleButton';
      } else {
        return 'circleButton';
      }
    });

    libraryButtonsEnter.append('img')
      .attr('class', 'projectGlyph');
    libraryButtons.select('img.projectGlyph')
      .attr('src', icon);

    libraryButtonsEnter.append('img')
      .attr('class', 'badge')
      .style('display', 'none');
    window.mainPage.versionNumber.then(appVersion => {
      libraryButtons.select('img.badge')
        .attr('src', warningIcon)
        .style('display', d => {
          if (d.attributes.meta.rlab.versionNumber === appVersion) {
            return 'none';
          } else {
            return 'block';
          }
        })
        .attr('title', d => {
          return 'This dataset was created with version ' + d.attributes.meta.rlab.versionNumber +
            ' of Resonant Lab.\nYou are currently using version ' + appVersion;
        });
    });

    libraryButtonsEnter.append('span');
    libraryButtons.select('span')
      .text(d => d.name());

    d3.select('#' + divId).selectAll('.circleButton')
      .on('click', d => {
        window.mainPage.getProject().then(project => {
          return project.setDataset(d.get('_id'), this.index);
        }).then(() => {
          window.mainPage.widgetPanels.toggleWidget({
            hashName: 'DatasetView' + this.index
          }, true);
        });
        window.mainPage.overlay.closeOverlay();
      });
  }
});

export default DatasetLibrary;
<commit_msg>chore(resonantlab): disable version warnings on dataset items as well<commit_after>import Underscore from 'underscore';
import d3 from 'd3';
import SettingsPanel from '../SettingsPanel';
import DatasetSettings from '../DatasetSettings';
import UploadView from './UploadView';
import myTemplate from './template.html';
import libraryFileIcon from '../../../images/light/library.svg';
import privateFileIcon from '../../../images/light/file_private.svg';
import publicFileIcon from '../../../images/light/file_public.svg';
import warningIcon from '../../../images/warning.svg';
import './style.scss';
let girder = window.girder;

let DatasetLibrary = DatasetSettings.extend({
  initialize: function () {
    DatasetSettings.prototype.initialize.apply(this, arguments);
    this.listenTo(window.mainPage.currentUser, 'rl:updateLibrary', () => {
      this.render();
    });
  },
  getSideMenu: function () {
    let sideMenu = DatasetSettings.prototype.getSideMenu.apply(this, arguments);
    // Override parts of the menu item from DatasetSettings
    sideMenu[0].items[2].focused = true;
    sideMenu[0].items[2].onclick = () => {
      window.mainPage.overlay.render('DatasetSettings');
    };
    return sideMenu;
  },
  createUploadSection: function () {
    if (window.mainPage.currentUser.isLoggedIn()) {
      this.uploadView = new UploadView({
        // Some girder views expect a parent, but
        // in this app, we just run them headless
        parentView: null,
        // Similar to girder's views, we want the
        // child to have access to this parent view
        // (but this has nothing to do with girder's
        // registerChild business)
        datasetLibrary: this
      });
      this.$el.find('#uploadSection')[0]
        .appendChild(this.uploadView.el);
      this.uploadView.delegateEvents();

      this.$el.find('#linkSection').show();
      this.$el.find('#loggedOutLinkSection').hide();
    } else {
      this.$el.find('#uploadSection')
        .append('
You must be logged in to upload files');

      this.$el.find('#linkSection').hide();
      this.$el.find('#loggedOutLinkSection').show();

      this.$el.find('.loginLink').on('click', () => {
        window.mainPage.overlay.render('LoginView');
      });
    }
  },
  attachLibraryListeners: function () {
    let self = this;

    // Listeners for existing dataset sections
    this.$el.find('#girderLink').on('click', () => {
      window.mainPage.router.openUserDirectoriesInGirder();
    });

    this.$el.find('#loginLink2').on('click', () => {
      window.mainPage.overlay.render('LoginView');
    });

    this.$el.find('#registerLink2').on('click', () => {
      window.mainPage.overlay.render('RegisterView');
    });

    // Listeners for new datset sections
    this.$el.find('#createLink').on('keyup', function () {
      // this refers to the DOM element
      // Validate the girder item ID (TODO: support other link types)
      self.validateGirderId(this.value);
    });

    this.$el.find('#createLinkButton').on('click', () => {
      let itemId = this.$el.find('#createLink').val();
      this.createGirderLink(itemId);
    });
  },
  startUpload: function () {
    console.log(this.$el.find('#uploadFile'));
  },
  createGirderLink: function (itemId) {
    window.mainPage.girderRequest({
      path: 'item/' + itemId + '/dataset',
      method: 'POST'
    }).then(datasetItem => {
      window.mainPage.getProject().then(project => {
        return project.setDataset(itemId, this.index);
      }).then(() => {
        window.mainPage.widgetPanels.toggleWidget({
          hashName: 'DatasetView' + this.index
        }, true);
        window.mainPage.overlay.closeOverlay();
      });
    });
  },
  validateGirderId: Underscore.debounce(function (itemId) {
    if (itemId) {
      this.linkToCreate = window.mainPage.girderRequest({
        path: 'item/' + itemId,
        type: 'GET'
      }).then(item => {
        if (!item || item['_modelType'] !== 'item') {
          return {
            errorMessage: '"' + this.value + '" is not a valid Girder item ID'
          };
        } else {
          return item;
        }
      }).catch(item => {
        return {
          errorMessage: '"' + this.value + '" is not a valid Girder item ID'
        };
      });
    } else {
      delete this.linkToCreate;
    }
    this.updateStaticSections();
  }, 600),
  updateStaticSections: function () {
    // Start out with all hideable form elements hidden
    this.$el.find('.newDatasetHideable').hide();

    // Update the upload interface
    if (this.uploadView) {
      this.uploadView.render();
    }

    // Set up the link interface
    // Start with the button disabled
    this.$el.find('#createLinkButton').prop('disabled', true);
    if (this.linkToCreate !== undefined) {
      // Show the spinner while we wait for link validation to finish
      this.$el.find('#linkSpinner').show();

      this.linkToCreate.then(linkResponse => {
        let errorMessage = null;
        if (!linkResponse) {
          errorMessage = 'Could not validate link';
        } else if ('errorMessage' in linkResponse) {
          errorMessage = linkResponse.errorMessage;
        }

        this.$el.find('#linkSpinner').hide();
        if (errorMessage !== null) {
          this.$el.find('#createLink').addClass('invalid');
          this.$el.find('#badLinkHelpText').text(errorMessage);
          this.$el.find('#badLinkHelp').show();
          this.$el.find('#createLinkHelp').show();
        } else {
          this.$el.find('#createLink').removeClass('invalid');
          this.$el.find('#createLinkButton').prop('disabled', false);
        }
      });
    }
  },
  showFileTypeWarning: function () {
    this.$el.find('#uploadFileFormatHelp').show();
  },
  hideFileTypeWarning: function () {
    this.$el.find('#uploadFileFormatHelp').hide();
  },
  updateDynamicSections: function () {
    // Get the set of datasets in the public library
    window.mainPage.girderRequest({
      path: 'resource/lookup?path=/collection/Resonant Lab Library/Data',
      type: 'GET'
    }).then(folder => {
      this.getFolderContents(folder, 'datasetLibrary', libraryFileIcon);
    }).catch(() => {
    }); // fail silently

    if (window.mainPage.currentUser.isLoggedIn()) {
      // The user is logged in

      // Get the set of the user's private datasets
      window.mainPage.girderRequest({
        path: 'folder/anonymousAccess/privateFolder',
        type: 'GET'
      }).then(folder => {
        this.getFolderContents(folder, 'privateDatasets', privateFileIcon);
      }).catch(() => {
      }); // fail silently

      // Get the set of the user's public projects
      window.mainPage.girderRequest({
        path: 'folder/anonymousAccess/publicFolder',
        type: 'GET'
      }).then(folder => {
        this.getFolderContents(folder, 'publicDatasets', publicFileIcon);
      }).catch(() => {
        // fail silently
      });
    } else {
      // The user is logged out
      // TODO: get the set of scratch datasets
      // "belonging" to this user
    }
  },
  render: Underscore.debounce(function () {
    DatasetSettings.prototype.updateBlurb.apply(this, []);
    // We use our own subtemplate, so only call
    // the grandparent superclass render function
    SettingsPanel.prototype.render.apply(this, arguments);
    if (!this.addedSubTemplate) {
      this.$el.find('#subclassContent').html(myTemplate);
      this.addedSubTemplate = true;

      // Only add the upload view from Girder once
      this.createUploadSection();

      // Only attach event listeners once
      this.attachLibraryListeners();

      // Because we debounce rendering, we need to add
      // the close listeners ourselves
      window.mainPage.overlay.addCloseListeners();

      // Start off with every hideable section hidden
      this.$el.find('.hideable').hide();
    }

    this.updateStaticSections();
    this.updateDynamicSections();
  }, 200),
  getFolderContents: function (folder, divId, icon) {
    let projects = new girder.collections.ItemCollection();
    projects.altUrl = 'item';
    projects.pageLimit = 100;
    projects.fetch({
      folderId: folder._id
    });
    projects.on('reset', (items) => {
      this.renderDatasets(items, divId, icon);
    });
  },
  renderDatasets: function (items, divId, icon) {
    let datasetModels = items.models.filter(d => {
      let meta = d.get('meta');
      return meta && meta.rlab && meta.rlab.itemType && meta.rlab.itemType === 'dataset';
    });

    if (datasetModels.length > 0) {
      this.$el.find('#' + divId + 'Section').show();
    }

    let libraryButtons = d3.select('#' + divId)
      .selectAll('.circleButton')
      .data(datasetModels, d => {
        return d.id + d.name();
      });

    let libraryButtonsEnter = libraryButtons.enter().append('div');
    libraryButtons.exit().remove();
    libraryButtons.attr('class', (d) => {
      if (window.mainPage.project &&
        d.id === window.mainPage.project.getDatasetId(this.index)) {
        return 'current circleButton';
      } else {
        return 'circleButton';
      }
    });

    libraryButtonsEnter.append('img')
      .attr('class', 'projectGlyph');
    libraryButtons.select('img.projectGlyph')
      .attr('src', icon);

    libraryButtonsEnter.append('img')
      .attr('class', 'badge')
      .style('display', 'none');
    window.mainPage.versionNumber.then(appVersion => {
      libraryButtons.select('img.badge')
        .attr('src', warningIcon)
        .style('display', d => {
          if (d.attributes.meta.rlab.versionNumber === appVersion) {
            return 'none';
          } else {
            return 'none';
          }
        })
        .attr('title', d => {
          return 'This dataset was created with version ' + d.attributes.meta.rlab.versionNumber +
            ' of Resonant Lab.\nYou are currently using version ' + appVersion;
        });
    });

    libraryButtonsEnter.append('span');
    libraryButtons.select('span')
      .text(d => d.name());

    d3.select('#' + divId).selectAll('.circleButton')
      .on('click', d => {
        window.mainPage.getProject().then(project => {
          return project.setDataset(d.get('_id'), this.index);
        }).then(() => {
          window.mainPage.widgetPanels.toggleWidget({
            hashName: 'DatasetView' + this.index
          }, true);
        });
        window.mainPage.overlay.closeOverlay();
      });
  }
});

export default DatasetLibrary;
<|endoftext|>


<commit_before>(function() {

    dominator.extend('open', function(id, callback) {
        var self = this;

        // page is already open and an animation is not in progress
        if ('#' + self.window.$('.current').attr('id') === id && self.window.$('.current').length === 1) {
            callback();
            return;
        }

        // do not fire callback until the page is finished opening
        self.window.$(id).bind('pageAnimationEnd', function() {
            self.window.$(id).unbind(event);
            callback();
        });

        self.window.jQT.goTo(id, 'pop');
    });

    dominator.extend('click', function(selector, callback) {
        this.window.$(selector).trigger('click');
        callback();
    });

    dominator.extend('waitForPage', function(selector, callback) {
        var self = this;
        self.expect(1);

        // page is already loaded
        if (this.window.$('.current').attr('id') === self.window.$(selector).attr('id')) {
            ok(true, 'Page loaded for ' + selector);
            setTimeout(callback, 250);
            return;
        }

        // wait for the page to load
        self.window.$(selector).bind('pageAnimationEnd', function() {
            ok(true, 'Page loaded for ' + selector);
            self.window.$(selector).unbind('pageAnimationEnd');
            setTimeout(callback, 250);
        });
    });

    dominator.extend('waitForVisible', function(selector, callback) {
        var self = this;
        self.expect(1);

        var intervalId = setInterval(function() {
            var $element = self.window.$(selector);
            if ($element.is(':visible')) {
                QUnit.ok(true, selector + ' is visible');
                clearTimeout(intervalId);
                callback();
            }
        }, 100);
    });

    dominator.extend('waitForNotVisible', function(selector, callback) {
        var self = this;
        self.expect(1);

        var intervalId = setInterval(function() {
            var $element = self.window.$(selector);
            if ($element.is(':hidden')) {
                QUnit.ok(true, selector + ' is not visible');
                clearTimeout(intervalId);
                callback();
            }
        }, 100);
    });

    dominator.extend('waitForEvent', function(selector, event, callback) {
        var self = this;
        self.expect(1);

        self.window.$(selector).bind(event, function() {
            ok(true, event + ' event fired on ' + selector);
            self.window.$(selector).unbind(event);
            callback();
        });
    });

})();
<commit_msg>Add crude touch support for jQTouch.<commit_after>(function() {

    dominator.extend('open', function(id, callback) {
        var self = this;

        // page is already open and an animation is not in progress
        if ('#' + self.window.$('.current').attr('id') === id && self.window.$('.current').length === 1) {
            callback();
            return;
        }

        // do not fire callback until the page is finished opening
        self.window.$(id).bind('pageAnimationEnd', function() {
            self.window.$(id).unbind(event);
            callback();
        });

        self.window.jQT.goTo(id, 'pop');
    });

    dominator.extend('click', function(selector, callback) {
        var type = (this.window.jQT.support.touch) ? 'tap' : 'click';
        this.window.$(selector).trigger(type);
        callback();
    });

    dominator.extend('waitForPage', function(selector, callback) {
        var self = this;
        self.expect(1);

        // page is already loaded
        if (this.window.$('.current').attr('id') === self.window.$(selector).attr('id')) {
            ok(true, 'Page loaded for ' + selector);
            setTimeout(callback, 250);
            return;
        }

        // wait for the page to load
        self.window.$(selector).bind('pageAnimationEnd', function() {
            ok(true, 'Page loaded for ' + selector);
            self.window.$(selector).unbind('pageAnimationEnd');
            setTimeout(callback, 250);
        });
    });

    dominator.extend('waitForVisible', function(selector, callback) {
        var self = this;
        self.expect(1);

        var intervalId = setInterval(function() {
            var $element = self.window.$(selector);
            if ($element.is(':visible')) {
                QUnit.ok(true, selector + ' is visible');
                clearTimeout(intervalId);
                callback();
            }
        }, 100);
    });

    dominator.extend('waitForNotVisible', function(selector, callback) {
        var self = this;
        self.expect(1);

        var intervalId = setInterval(function() {
            var $element = self.window.$(selector);
            if ($element.is(':hidden')) {
                QUnit.ok(true, selector + ' is not visible');
                clearTimeout(intervalId);
                callback();
            }
        }, 100);
    });

    dominator.extend('waitForEvent', function(selector, event, callback) {
        var self = this;
        self.expect(1);

        if (event === 'click') {
            event = (self.window.jQT.support.touch) ? 'tap' : 'click';
        }

        self.window.$(selector).bind(event, function() {
            ok(true, event + ' event fired on ' + selector);
            self.window.$(selector).unbind(event);
            callback();
        });
    });

})();
<|endoftext|>


<commit_before>'use babel';

import ExemplatorPluginView from './exemplator-plugin-view';
import {CompositeDisposable} from 'atom';

const FUNCTION = 0;
const TYPE = 1;
const OTHER = 2;

var getCursorIndex = function () {
    var editor = atom.workspace.getActiveTextEditor();
    var text = editor.getText();

    var currentPosition = editor.getCursorBufferPosition();

    var row = 0;
    var col = 0;
    var index;
    // translate row and column into an index for text
    for (index = 0; index < text.length; index++) {
        if (row == currentPosition.row && col == currentPosition.column)
            break;

        if (text.charAt(index) == '\n') {
            row++;
            col = 0;
        } else {
            col++;
        }
    }

    return index;
}

var getCurrentSegment = function (index) {
    var editor = atom.workspace.getActiveTextEditor();
    var text = editor.getText();

    // is cursor on method or type/variable name?
    var currentSegmentStart;
    var currentSegmentEnd;

    for (var currentSegmentStart = Math.max(0, index - 1); currentSegmentStart >= 0; currentSegmentStart--) {
        var c = text.charAt(currentSegmentStart);

        if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')) {
            currentSegmentStart++;
            break;
        }
    }

    var type;

    for (var currentSegmentEnd = index; currentSegmentEnd < text.length; currentSegmentEnd++) {
        var c = text.charAt(currentSegmentEnd);

        if (c == '(') {
            type = FUNCTION;
            currentSegmentEnd--;
            break;
        } else if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')) {
            currentSegmentEnd--;
            break;
        }
    }

    if (type != FUNCTION) {
        // type declaration if capitalized
        if (text.charAt(currentSegmentStart) >= 'A' && text.charAt(currentSegmentStart) <= 'Z')
            type = TYPE;
        else
            type = OTHER;
    }

    return {
        "type": type,
        "str": text.substr(currentSegmentStart, (currentSegmentEnd - currentSegmentStart) + 1),
        "start": currentSegmentStart,
        "end": currentSegmentEnd
    };
}

var getPackage = function (index) {
    var editor = atom.workspace.getActiveTextEditor();
    var text = editor.getText();

    var segment = getCurrentSegment(index)
    var type = segment["type"]
    var str = segment["str"]

    if (type == OTHER)
        return null;
    else if (type == TYPE) {
        lines = text.split('\n');
        var simpleTypeName = str;
        // find package name
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].startsWith('import')) {
                var packageName = getPackageName(lines[i], simpleTypeName)
                if (packageName != null)
                    return {"package": packageName, "name": simpleTypeName};
            }
        }
    }

    return {"name": str};
}

String.prototype.regexIndexOf = function (regex, startpos) {
    var indexOf = this.substring(startpos || 0).search(regex);
    return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}

String.prototype.regexLastIndexOf = function (regex, startpos) {
    regex = (regex.global) ? regex : new RegExp(regex.source, "g" + (regex.ignoreCase ? "i" : "") + (regex.multiLine ? "m" : ""));
    if (typeof (startpos) == "undefined") {
        startpos = this.length;
    } else if (startpos < 0) {
        startpos = 0;
    }
    var stringToWorkWith = this.substring(0, startpos + 1);
    var lastIndexOf = -1;
    var nextStop = 0;
    while ((result = regex.exec(stringToWorkWith)) != null) {
        lastIndexOf = result.index;
        regex.lastIndex = ++nextStop;
    }
    return lastIndexOf;
}

var getFullClassNameForVariable = function (index) {
    var segment = getCurrentSegment(index)

    if (segment["str"].length == 0)
        return null;

    var editor = atom.workspace.getActiveTextEditor();
    var text = editor.getText();

    // go to declaration

    var regex = new RegExp("[A-Z][a-zA-Z]* " + segment["str"]);
    var declarationPos = text.regexLastIndexOf(regex, index);
    if (declarationPos == -1)
        return null;

    var fullClassName = getPackage(declarationPos);

    return fullClassName;
}

var getFullClassNameForFunction = function (index) {
    var editor = atom.workspace.getActiveTextEditor();
    var text = editor.getText();

    var segment = getCurrentSegment(index);
    var type = segment["type"];
    var str = segment["str"];

    if (type != FUNCTION)
        return null;

    if (text.charAt(segment["start"] - 1) != ".")
        return null;

    return getFullClassNameForVariable(segment["start"] - 2);
}

var getPackageName = function (importLine, typeName) {
    // only return if it matches typeName
    var packageStart = importLine.indexOf(' ');
    var p = importLine.substr(packageStart);
    var comps = p.split('.');
    var packageWithClass = comps[comps.length - 1];
    packageWithClass = packageWithClass.substr(0, packageWithClass.length - 1)
    if (packageWithClass !== typeName)
        return null;
    else {
        var packageWithClass = p.substr(0, p.length - 1);
        return packageWithClass.replace("." + typeName, "")
    }
}

var sendRequest = function (exemplatorPluginView, request, page = 0) {
    console.log("hi 1")
    var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance
    xmlhttp.open("POST", "http://localhost:4567/search");
    xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

    var dict = {}

    if (false)//request.class != null && request.class.package != null)
        dict["package"] = request.class.package.trim();
    if (request.class != null && request.class.name != null)
        dict["class"] = request.class.name.trim();
    if (request.method != null)
        dict["method"] = request.method.trim();
    if (request.token != null)
        dict["token"] = request.token.trim();
    dict["page"] = page;

    console.log("Dict to be sent: ");
    console.log(dict);

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {
            if (xmlhttp.status == 200) {
                handleResponse(exemplatorPluginView, xmlhttp.responseText);
            }
            else if (xmlhttp.status == 400) {
                console.log("Error 400 returned from server");
            }
            else {
                console.log("Error returned from server",xmlhttp.status);
            }
        }
    };

    var dict = {
    'class': 'List',
    'method': 'add',
    'page': 0
    }

    xmlhttp.send(JSON.stringify(dict));
}

var splitCode = function (codeString, startRow, endRow) {
    var array = codeString.match(/[^\r\n]+/g);

    var startString = "";
    var highlightedString = "";
    var endString = "";
    for (var i = 0; i < array.length; i++) {
        if (i < startRow) {
            startString += array[i];
        } else if (i < endRow) {
            highlightedString += array[i];
        } else {
            endString += array[i];
        }
    }

    return [startString, highlightedString, endString];
}

var handleResponse = function (exemplatorPluginView, responseText) {
    var response = JSON.parse(responseText);
    console.log("Response from server: ");
    console.log(response);

    var responseArray = response.occurrences;
    console.log(responseArray)

    var data = {
        examples: []
    }

    responseArray.forEach(item => {
        item.selections.forEach(selection => {
            let code = splitCode(item.code, 1, 2);
            if (selection.start.line != -1) {
                var element = {
                    user: 'bill',
                    score: item.userUrl,
                    userurl: item.userUrl,
                    rawUrl: item.rawUrl,
                    codeTop: code[0],
                    highlightedCode: code[1],
                    codeBottom:  code[2]
                }
                data.examples.push(element)
            }
        })
    })

    exemplatorPluginView.setData(data);
}

export default {

    exemplatorPluginView: null,
    modalPanel: null,
    subscriptions: null,

    activate(state) {
        this.exemplatorPluginView = new ExemplatorPluginView(state.exemplatorPluginViewState);
        this.modalPanel = atom.workspace.addRightPanel({
            item: this.exemplatorPluginView.getElement(),
            visible: true
        });

        // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
        this.subscriptions = new CompositeDisposable();

        // Register command that toggles this view
        this.subscriptions.add(atom.commands.add('atom-workspace', {
            'Exemplator:toggle': () => this.toggle()
        }));
        this.subscriptions.add(atom.commands.add('atom-workspace', {
            'Exemplator:showExamples': () => this.showExamples()
        }));
    },

    deactivate() {
        this.modalPanel.destroy();
        this.subscriptions.dispose();
        this.exemplatorPluginView.destroy();
    },

    serialize() {
        return {
            exemplatorPluginViewState: this.exemplatorPluginView.serialize()
        };
    },

    toggle() {
        console.log('ExemplatorPlugin was toggled!');
        return (
            this.modalPanel.isVisible() ?
                this.modalPanel.hide() :
                this.modalPanel.show()
        );
    },

    showExamples() {
        editor = atom.workspace.getActiveTextEditor();

        var request = {

        };

        // text selected? then search for plain string
        if (editor.getSelectedText().length > 0) {
            var plainStr = editor.getSelectedText();
            console.log("Found plain str: " + plainStr);
            request.token = plainStr;
        } else {
            var index = getCursorIndex();
            // function?
            var classNameForFunction = getFullClassNameForFunction(index);
            if (classNameForFunction != null) {
                var functionName = getCurrentSegment(index)["str"];
                console.log("found " + classNameForFunction + "." + functionName);
                request.class = classNameForFunction;
                request.method = functionName;
            } else {
                var classNameForVariable = getFullClassNameForVariable(index);
                if (classNameForVariable != null) {
                    console.log("found " + classNameForVariable);
                    request.class = classNameForVariable;
                } else {
                    // type?
                    var classNameForType = getPackage(index);
                    if (classNameForType != null) {
                        console.log("found " + classNameForType);
                        request.class = classNameForType;
                    } else {
                        console.log("Nothing found");
                    }
                }
            }
        }

        console.log(request)
        //this.exemplatorPluginView.setData();
        sendRequest(this.exemplatorPluginView, 'test');
    }
};
<commit_msg>Fixed bug<commit_after>'use babel';

import ExemplatorPluginView from './exemplator-plugin-view';
import {CompositeDisposable} from 'atom';

const FUNCTION = 0;
const TYPE = 1;
const OTHER = 2;

var getCursorIndex = function () {
    var editor = atom.workspace.getActiveTextEditor();
    var text = editor.getText();

    var currentPosition = editor.getCursorBufferPosition();

    var row = 0;
    var col = 0;
    var index;
    // translate row and column into an index for text
    for (index = 0; index < text.length; index++) {
        if (row == currentPosition.row && col == currentPosition.column)
            break;

        if (text.charAt(index) == '\n') {
            row++;
            col = 0;
        } else {
            col++;
        }
    }

    return index;
}

var getCurrentSegment = function (index) {
    var editor = atom.workspace.getActiveTextEditor();
    var text = editor.getText();

    // is cursor on method or type/variable name?
    var currentSegmentStart;
    var currentSegmentEnd;

    for (var currentSegmentStart = Math.max(0, index - 1); currentSegmentStart >= 0; currentSegmentStart--) {
        var c = text.charAt(currentSegmentStart);

        if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')) {
            currentSegmentStart++;
            break;
        }
    }

    var type;

    for (var currentSegmentEnd = index; currentSegmentEnd < text.length; currentSegmentEnd++) {
        var c = text.charAt(currentSegmentEnd);

        if (c == '(') {
            type = FUNCTION;
            currentSegmentEnd--;
            break;
        } else if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')) {
            currentSegmentEnd--;
            break;
        }
    }

    if (type != FUNCTION) {
        // type declaration if capitalized
        if (text.charAt(currentSegmentStart) >= 'A' && text.charAt(currentSegmentStart) <= 'Z')
            type = TYPE;
        else
            type = OTHER;
    }

    return {
        "type": type,
        "str": text.substr(currentSegmentStart, (currentSegmentEnd - currentSegmentStart) + 1),
        "start": currentSegmentStart,
        "end": currentSegmentEnd
    };
}

var getPackage = function (index) {
    var editor = atom.workspace.getActiveTextEditor();
    var text = editor.getText();

    var segment = getCurrentSegment(index)
    var type = segment["type"]
    var str = segment["str"]

    if (type == OTHER)
        return null;
    else if (type == TYPE) {
        lines = text.split('\n');
        var simpleTypeName = str;
        // find package name
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].startsWith('import')) {
                var packageName = getPackageName(lines[i], simpleTypeName)
                if (packageName != null)
                    return {"package": packageName, "name": simpleTypeName};
            }
        }
    }

    return {"name": str};
}

String.prototype.regexIndexOf = function (regex, startpos) {
    var indexOf = this.substring(startpos || 0).search(regex);
    return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}

String.prototype.regexLastIndexOf = function (regex, startpos) {
    regex = (regex.global) ? regex : new RegExp(regex.source, "g" + (regex.ignoreCase ? "i" : "") + (regex.multiLine ? "m" : ""));
    if (typeof (startpos) == "undefined") {
        startpos = this.length;
    } else if (startpos < 0) {
        startpos = 0;
    }
    var stringToWorkWith = this.substring(0, startpos + 1);
    var lastIndexOf = -1;
    var nextStop = 0;
    while ((result = regex.exec(stringToWorkWith)) != null) {
        lastIndexOf = result.index;
        regex.lastIndex = ++nextStop;
    }
    return lastIndexOf;
}

var getFullClassNameForVariable = function (index) {
    var segment = getCurrentSegment(index)

    if (segment["str"].length == 0)
        return null;

    var editor = atom.workspace.getActiveTextEditor();
    var text = editor.getText();

    // go to declaration

    var regex = new RegExp("[A-Z][a-zA-Z]* " + segment["str"]);
    var declarationPos = text.regexLastIndexOf(regex, index);
    if (declarationPos == -1)
        return null;

    var fullClassName = getPackage(declarationPos);

    return fullClassName;
}

var getFullClassNameForFunction = function (index) {
    var editor = atom.workspace.getActiveTextEditor();
    var text = editor.getText();

    var segment = getCurrentSegment(index);
    var type = segment["type"];
    var str = segment["str"];

    if (type != FUNCTION)
        return null;

    if (text.charAt(segment["start"] - 1) != ".")
        return null;

    return getFullClassNameForVariable(segment["start"] - 2);
}

var getPackageName = function (importLine, typeName) {
    // only return if it matches typeName
    var packageStart = importLine.indexOf(' ');
    var p = importLine.substr(packageStart);
    var comps = p.split('.');
    var packageWithClass = comps[comps.length - 1];
    packageWithClass = packageWithClass.substr(0, packageWithClass.length - 1)
    if (packageWithClass !== typeName)
        return null;
    else {
        var packageWithClass = p.substr(0, p.length - 1);
        return packageWithClass.replace("." + typeName, "")
    }
}

var sendRequest = function (exemplatorPluginView, request, page = 0) {
    console.log("hi 1")
    var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance
    xmlhttp.open("POST", "http://localhost:4567/search");
    xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

    var dict = {}

    if (false)//request.class != null && request.class.package != null)
        dict["package"] = request.class.package.trim();
    if (request.class != null && request.class.name != null)
        dict["class"] = request.class.name.trim();
    if (request.method != null)
        dict["method"] = request.method.trim();
    if (request.token != null)
        dict["token"] = request.token.trim();
    dict["page"] = page;

    console.log("Dict to be sent: ");
    console.log(dict);

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {
            if (xmlhttp.status == 200) {
                handleResponse(exemplatorPluginView, xmlhttp.responseText);
            }
            else if (xmlhttp.status == 400) {
                console.log("Error 400 returned from server");
            }
            else {
                console.log("Error returned from server",xmlhttp.status);
            }
        }
    };

    var dict = {
    'class': 'List',
    'method': 'add',
    'page': 0
    }

    xmlhttp.send(JSON.stringify(dict));
}

var splitCode = function (codeString, startRow, endRow) {
    var array = codeString.match(/[^\r\n]+/g);

    var startString = "";
    var highlightedString = "";
    var endString = "";
    for (var i = 0; i < array.length; i++) {
        if (i < startRow) {
            startString += array[i];
        } else if (i < endRow) {
            highlightedString += array[i];
        } else {
            endString += array[i];
        }
    }

    return [startString, highlightedString, endString];
}

var handleResponse = function (exemplatorPluginView, responseText) {
    var response = JSON.parse(responseText);
    console.log("Response from server: ");
    console.log(response);

    var responseArray = response.occurrences;
    console.log(responseArray)

    var data = {
        examples: []
    }

    responseArray.forEach(item => {
        item.selections.forEach(selection => {
            let code = splitCode(item.code, 1, 2);
            if (selection.start.line != -1) {
                var element = {
                    user: 'bill',
                    score: item.userUrl,
                    userurl: item.userUrl,
                    rawUrl: item.rawUrl,
                    codeTop: code[0],
                    highlightedCode: code[1],
                    codeBottom:  code[2]
                }
                data.examples.push(element)
            }
        })
    })

    exemplatorPluginView.setData(data);
}

export default {

    exemplatorPluginView: null,
    modalPanel: null,
    subscriptions: null,

    activate(state) {
        this.exemplatorPluginView = new ExemplatorPluginView(state.exemplatorPluginViewState);
        this.modalPanel = atom.workspace.addRightPanel({
            item: this.exemplatorPluginView.getElement(),
            visible: true
        });

        // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
        this.subscriptions = new CompositeDisposable();

        // Register command that toggles this view
        this.subscriptions.add(atom.commands.add('atom-workspace', {
            'Exemplator:toggle': () => this.toggle()
        }));
        this.subscriptions.add(atom.commands.add('atom-workspace', {
            'Exemplator:showExamples': () => this.showExamples()
        }));
    },

    deactivate() {
        this.modalPanel.destroy();
        this.subscriptions.dispose();
        this.exemplatorPluginView.destroy();
    },

    serialize() {
        return {
            exemplatorPluginViewState: this.exemplatorPluginView.serialize()
        };
    },

    toggle() {
        console.log('ExemplatorPlugin was toggled!');
        return (
            this.modalPanel.isVisible() ?
                this.modalPanel.hide() :
                this.modalPanel.show()
        );
    },

    showExamples() {
        editor = atom.workspace.getActiveTextEditor();

        var request = {

        };

        // text selected? then search for plain string
        if (editor.getSelectedText().length > 0) {
            var plainStr = editor.getSelectedText();
            console.log("Found plain str: " + plainStr);
            request.token = plainStr;
        } else {
            var index = getCursorIndex();
            // function?
            var classNameForFunction = getFullClassNameForFunction(index);
            if (classNameForFunction != null) {
                var functionName = getCurrentSegment(index)["str"];
                console.log("found " + classNameForFunction + "." + functionName);
                request.class = classNameForFunction;
                request.method = functionName;
            } else {
                var classNameForVariable = getFullClassNameForVariable(index);
                if (classNameForVariable != null) {
                    console.log("found " + classNameForVariable);
                    request.class = classNameForVariable;
                } else {
                    // type?
                    var classNameForType = getPackage(index);
                    if (classNameForType != null) {
                        console.log("found " + classNameForType);
                        request.class = classNameForType;
                    } else {
                        console.log("Nothing found");
                    }
                }
            }
        }

        console.log(request)
        //this.exemplatorPluginView.setData();
        sendRequest(this.exemplatorPluginView, request);
    }
};
<|endoftext|>


<commit_before>const config = require('config'),
  _ = require('lodash'),
  Promise = require('bluebird'),
  request = Promise.promisifyAll(require('request')),
  parse = require('../../parse'),
  apps = require('../../db/apps'),
  log = require('../../logger');

exports.init = function init(env) {
  return apps
    .init('code')
    .then((ret) => {
      const newEnv = env;
      newEnv.ids.code = ret;
      return newEnv;
    });
};

function getSmaliQuery(query) {
  let queryObj = parse(query);
  const lines = [];
  if (queryObj instanceof Array === false) {
    queryObj = [queryObj];
  }
  _.forEach(queryObj, (v) => {
    let line = '';
    _.forEach(v.attributes, (attrib) => {
      if (attrib.name.toLowerCase() === 'class') {
        line += `L${attrib.value.replace(/\./g, '/')}`;
      }
      else if (attrib.name.toLowerCase() === 'method') {
        line += `;->${attrib.value}`;
      }
    });
    if (line !== '') {
      lines.push(line);
    }
  });
  return lines;
}

exports.find = function find(env, query, options) {
  // If query is not specified, return everything in scope
  if (!query) {
    return Promise.resolve(options.scope);
  }
  const codeQueries = getSmaliQuery(query),
    solrConfig = config.get('dbConfig.solr'),
    reqURL = `http://${solrConfig.host}:${solrConfig.port}/solr/${solrConfig.codeCollection}/query`,
    terms = _.map(codeQueries, (codeQuery) => {
      const escapedQuery = _escapeSpecialCharacters(codeQuery);
      return `"${escapedQuery}"`;
    }),
    _text_ = terms.join(' && '),
    scope = options.scope.join(' OR '),
    reqObj = {
      url: reqURL,
      qs: {
        q: `_text_: ${_text_} AND (id: ${scope} )`,
        wt: 'json',
        rows: config.get('dbConfig.solr.maxRows'),
        fl: 'id'
      }
    };
  // search the code collection in Solr
  function clientError(e) {
    return e.code >= 400 && e.code < 500;
  }
  return request.getAsync(reqObj)
    .get(1)
    .then((body) => {
      const docs = JSON.parse(body).response.docs,
        solrResults = _.pluck(docs, 'id');
      return Promise.resolve(solrResults);
    })
    .catch(clientError, (e) => {
      log.error('Solr client error has occurred when submitting code query %o',
        query, e);
      return Promise.reject(e);
    })
    .catch((e) => {
      log.error('Error in find by code when submitting code query %o', query, e);
      return Promise.reject(e);
    });
};

/**
 * Escape a string that uses any of Solr's special characters.
 * + - && || ! ( ) { } [ ] ^ " ~ * ? : /
 * @param str a String that may use any of the meta-characters
 * @returns {String} The escaped string with a single backslash proceeding the
 * special character.
 * @private
 */
function _escapeSpecialCharacters(str) {
  let escaped = str.replace(/([\+\-!\(\)\{}\[\]\^"~\*\?:\/])/g, '\\$1');
  escaped = escaped.replace('&&', '\\&&');
  escaped = escaped.replace('||', '\\||');
  return escaped;
}
<commit_msg>refactor<commit_after>const config = require('config'),
  _ = require('lodash'),
  Promise = require('bluebird'),
  request = Promise.promisifyAll(require('request')),
  parse = require('../../parse'),
  apps = require('../../db/apps'),
  log = require('../../logger');

exports.init = function init(env) {
  return apps
    .init('code')
    .then((ret) => {
      const newEnv = env;
      newEnv.ids.code = ret;
      return newEnv;
    });
};

function getSmaliQuery(query) {
  'use strict';
  let queryObj = parse(query);
  const lines = [];
  if (queryObj instanceof Array === false) {
    queryObj = [queryObj];
  }
  _.forEach(queryObj, (v) => {
    let line = '';
    _.forEach(v.attributes, (attrib) => {
      if (attrib.name.toLowerCase() === 'class') {
        line += `L${attrib.value.replace(/\./g, '/')}`;
      }
      else if (attrib.name.toLowerCase() === 'method') {
        line += `;->${attrib.value}`;
      }
    });
    if (line !== '') {
      lines.push(line);
    }
  });
  return lines;
}

exports.find = function find(env, query, options) {
  // If query is not specified, return everything in scope
  if (!query) {
    return Promise.resolve(options.scope);
  }
  const codeQueries = getSmaliQuery(query),
    solrConfig = config.get('dbConfig.solr'),
    reqURL = `http://${solrConfig.host}:${solrConfig.port}/solr/${solrConfig.codeCollection}/query`,
    terms = _.map(codeQueries, (codeQuery) => {
      const escapedQuery = _escapeSpecialCharacters(codeQuery);
      return `"${escapedQuery}"`;
    }),
    _text_ = terms.join(' && '),
    scope = options.scope.join(' OR '),
    reqObj = {
      url: reqURL,
      qs: {
        q: `_text_: ${_text_} AND (id: ${scope} )`,
        wt: 'json',
        rows: config.get('dbConfig.solr.maxRows'),
        fl: 'id'
      }
    };
  // search the code collection in Solr
  function clientError(e) {
    return e.code >= 400 && e.code < 500;
  }
  return request.getAsync(reqObj)
    .get(1)
    .then((body) => {
      const docs = JSON.parse(body).response.docs,
        solrResults = _.pluck(docs, 'id');
      return Promise.resolve(solrResults);
    })
    .catch(clientError, (e) => {
      log.error('Solr client error has occurred when submitting code query %o',
        query, e);
      return Promise.reject(e);
    })
    .catch((e) => {
      log.error('Error in find by code when submitting code query %o', query, e);
      return Promise.reject(e);
    });
};

/**
 * Escape a string that uses any of Solr's special characters.
 * + - && || ! ( ) { } [ ] ^ " ~ * ? : /
 * @param str a String that may use any of the meta-characters
 * @returns {String} The escaped string with a single backslash proceeding the
 * special character.
 * @private
 */
function _escapeSpecialCharacters(str) {
  'use strict';
  let escaped = str.replace(/([\+\-!\(\)\{}\[\]\^"~\*\?:\/])/g, '\\$1');
  escaped = escaped.replace('&&', '\\&&');
  escaped = escaped.replace('||', '\\||');
  return escaped;
}
<|endoftext|>


<commit_before>import React, { Component } from 'react'

import icons from '../../icons/css/icons.css'
import { fetchTaxonomies } from '../../core/firebaseRestAPI'
import { taxonomiesWithIcons } from '../../lib/taxonomies'

import Home from '../../components/Home'
import Layout from '../../components/Layout'

class HomePage extends Component {
  constructor(props) {
    super(props)
    this.state = {
      taxonomies: [],
    }
  }

  componentWillMount() {
    fetchTaxonomies()
      .then(taxonomies => {
        this.setState({
          taxonomies: taxonomiesWithIcons(taxonomies)
        })
      })
  }

  componentDidMount() {
    document.title = 'Link-SF'
  }

  render() {
    const { taxonomies } = this.state

    return (
      <Layout>
        <Home categories={taxonomies} />
      </Layout>
    )
  }
}

export default HomePage
<commit_msg>Added a loading icon to the home screen<commit_after>import React, { Component } from 'react'

import icons from '../../icons/css/icons.css'
import { fetchTaxonomies } from '../../core/firebaseRestAPI'
import { taxonomiesWithIcons } from '../../lib/taxonomies'

import Home from '../../components/Home'
import Layout from '../../components/Layout'
import Loading from '../../components/Loading'

class HomePage extends Component {
  constructor(props) {
    super(props)
    this.state = {
      taxonomies: [],
    }
  }

  componentWillMount() {
    fetchTaxonomies()
      .then(taxonomies => {
        this.setState({
          taxonomies: taxonomiesWithIcons(taxonomies)
        })
      })
  }

  componentDidMount() {
    document.title = 'Link-SF'
  }

  render() {
    const { taxonomies } = this.state

    return (
      <Layout>
        { taxonomies.length ? <Home categories={taxonomies} /> : <Loading /> }
      </Layout>
    )
  }
}

export default HomePage
<|endoftext|>


<commit_before>module.exports = function (sails) {

  /**
   * Module dependencies
   */
   var Err          = require('../../../errors');
   var path         = require('path');
   var ChildProcess = require('child_process');
   var _            = require('lodash');

   return {

    /**
     * Initialize this project's Grunt tasks
     * and execute the environment-specific gruntfile
     *
     */
     initialize: function (cb) {

      sails.log.verbose('Loading app Gruntfile...');

      // Start task depending on environment
      if(sails.config.environment === 'production'){
        return this.runTask('prod', cb);
      }
      this.runTask('default', cb);
    },

    /**
     * Fork Grunt child process
     *
     * @param {String} taskName - grunt task to run
     * @param {Function} cb - optional, fires when the Grunt task has been started (non-production) or finished (production)
     */
     runTask: function (taskName, cb_afterTaskStarted) {
      cb_afterTaskStarted = cb_afterTaskStarted || function () {};

      var environment = sails.config.environment;
      var pathToSails = path.resolve(__dirname, '../../../');

      // Only relevant in a development environment:
      // (unfortunately, cannot use sails.getBaseurl() because it is not calculatable yet)
      var baseurl = 'http://' + (sails.config.host || 'localhost') + ':' + sails.config.port;

      if (!taskName) {
        taskName = '';
      }

      var child;

      // Plugins Grunt file
      // Run the default task
      // TODO: Use Async to run tasks in parallel
      _.forEach(sails.config.paths.plugins, function(plugin){
        process.chdir(plugin);
        child = ChildProcess.fork(
          // cwd for child process
          path.join(plugin,'node_modules/grunt-cli/bin/grunt'),

          // opts to pass to node's `child_process` logic
          {
            silent: true,
            stdio: 'pipe'
          }
          );
      });

      // Fork Grunt child process
      child = ChildProcess.fork(

        // cwd for child process
        path.join(pathToSails,'node_modules/grunt-cli/bin/grunt'),

        // cmd args+opts for child process
        [
        taskName,
        '--pathToSails='+pathToSails,

          // Backwards compatibility for v0.9.x
          '--gdsrc='+ pathToSails + '/node_modules'
          ],

        // opts to pass to node's `child_process` logic
        {
          silent: true,
          stdio: 'pipe'
        }
        );

      var errorMsg = '';
      var stackTrace = '';

      // Log output as it comes in to the appropriate log channel
      child.stdout.on('data', function (consoleMsg) {

        // store all the output
        consoleMsg = consoleMsg.toString();
        errorMsg += consoleMsg;

        // Clean out all the whitespace
        var trimmedStackTrace = (typeof stackTrace === 'string') ? stackTrace : '';
        trimmedStackTrace = trimmedStackTrace.replace(/[\n\s]*$/,'');
        trimmedStackTrace = trimmedStackTrace.replace(/^[\n\s]*/,'');
        var trimmedConsoleMsg = (typeof consoleMsg === 'string') ? consoleMsg : '';
        trimmedConsoleMsg = trimmedConsoleMsg.replace(/[\n\s]*$/,'');
        trimmedConsoleMsg = trimmedConsoleMsg.replace(/^[\n\s]*/,'');

        // Remove '--force to continue' message since it makes no sense
        // in this context:
        trimmedConsoleMsg = trimmedConsoleMsg.replace(/Use --force to continue\./i, '');
        trimmedStackTrace = trimmedStackTrace.replace(/Use --force to continue\./i, '');

        // Find the Stack Trace related to this warning
        stackTrace = errorMsg.substring(errorMsg.lastIndexOf('Running "'));

    //     if (consoleMsg.match(/Use --force to continue/)) {
        // //   sails.log.warn('** Grunt :: Warning **');
        // //   sails.log.warn(errorMsg,trimmedStackTrace);
        // }

        // Handle fatal errors, like missing grunt dependency, etc.
        if (consoleMsg.match(/Fatal error/g)) {

          // If no Gruntfile exists, don't crash- just display a warning.
          if (consoleMsg.match(/Unable to find Gruntfile/i)) {
            sails.log.info('Gruntfile could not be found.');
            sails.log.info('(no grunt tasks will be run.)');
            return;
          }

          Err.fatal.__GruntAborted__(trimmedConsoleMsg, trimmedStackTrace);
          return;
        }

        // Handle fatal Grunt errors by killing Sails process as well
        if (consoleMsg.match(/Aborted due to warnings/)) {
          sails.log.error('** Grunt :: An error occurred. **');
          // sails.log.warn(trimmedStackTrace);
          // sails.emit('hook:grunt:error', trimmedStackTrace);
          Err.fatal.__GruntAborted__(trimmedConsoleMsg, trimmedStackTrace);
          return;
        }

        if (consoleMsg.match(/ParseError/)) {
          sails.log.warn('** Grunt :: Parse Warning **');
          sails.log.warn(trimmedStackTrace);
        }

        // Only display console message if it has content besides whitespace
        else if ( !consoleMsg.match(/^\s*$/) ) {
          sails.log.verbose('Grunt :: ' + trimmedConsoleMsg);
        }
      });

      // Handle general-case grunt output:
      child.stdout.on('error', function (gruntOutput) {
        sails.log.error('Grunt ::', _sanitize(gruntOutput));
      });
      child.stderr.on('data', function (gruntOutput) {
        sails.log.error('Grunt ::', _sanitize(gruntOutput));
      });
      child.stderr.on('error', function (gruntOutput) {
        sails.log.error('Grunt ::', _sanitize(gruntOutput));
      });

      // When process is complete, fire event on `sails`
      child.on('exit', function (code, s) {
        if ( code !== 0 ) return sails.emit('hook:grunt:error');
        sails.emit('hook:grunt:done');

        // Fire finish after grunt is done in production
        if(sails.config.environment === 'production'){
          cb_afterTaskStarted();
        }
      });

      // Since there's likely a watch task involved, and we may need
      // to flush the whole thing, we need a way to grab hold of the child process
      // So we save a reference to it
      sails.log.verbose('Tracking new grunt child process...');
      sails.childProcesses.push(child);

      // Go ahead and get out of here, since Grunt might sit there backgrounded
      if(sails.config.environment !== 'production'){
       cb_afterTaskStarted();
     }
   }
 };
};

/**
 * After ensuring a chunk is a string, trim any leading or
 * trailing whitespace.  If chunk cannot be nicely casted to a string,
 * pass it straight through.
 *
 * @param  {*} chunk
 * @return {*}
 */
 function _sanitize (chunk) {

  if (chunk && typeof chunk === 'object' && chunk.toString) {
    chunk = chunk.toString();
  }
  if (typeof chunk === 'string') {
    chunk = chunk.replace(/^[\s\n]*/, '');
    chunk = chunk.replace(/[\s\n]*$/, '');
  }
  return chunk;
}
<commit_msg>used grunt sails path to run plugins tasks<commit_after>module.exports = function (sails) {

  /**
   * Module dependencies
   */
   var Err          = require('../../../errors');
   var path         = require('path');
   var ChildProcess = require('child_process');
   var _            = require('lodash');

   return {

    /**
     * Initialize this project's Grunt tasks
     * and execute the environment-specific gruntfile
     *
     */
     initialize: function (cb) {

      sails.log.verbose('Loading app Gruntfile...');

      // Start task depending on environment
      if(sails.config.environment === 'production'){
        return this.runTask('prod', cb);
      }
      this.runTask('default', cb);
    },

    /**
     * Fork Grunt child process
     *
     * @param {String} taskName - grunt task to run
     * @param {Function} cb - optional, fires when the Grunt task has been started (non-production) or finished (production)
     */
     runTask: function (taskName, cb_afterTaskStarted) {
      cb_afterTaskStarted = cb_afterTaskStarted || function () {};

      var environment = sails.config.environment;
      var pathToSails = path.resolve(__dirname, '../../../');

      // Only relevant in a development environment:
      // (unfortunately, cannot use sails.getBaseurl() because it is not calculatable yet)
      var baseurl = 'http://' + (sails.config.host || 'localhost') + ':' + sails.config.port;

      if (!taskName) {
        taskName = '';
      }

      var child;

      // Plugins Grunt file
      // Run the default task
      // TODO: REFACTOR AND MERGE IN ONE METHOD
      _.forEach(sails.config.paths.plugins, function(plugin){
        process.chdir(plugin);
        // console.log(pathToSails);
        child = ChildProcess.fork(
          // cwd for child process
          path.join(pathToSails,'node_modules/grunt-cli/bin/grunt'),

          // opts to pass to node's `child_process` logic
          {
            silent: true,
            stdio: 'pipe'
          }
          );
      });

      // Fork Grunt child process
      child = ChildProcess.fork(

        // cwd for child process
        path.join(pathToSails,'node_modules/grunt-cli/bin/grunt'),

        // cmd args+opts for child process
        [
        taskName,
        '--pathToSails='+pathToSails,

          // Backwards compatibility for v0.9.x
          '--gdsrc='+ pathToSails + '/node_modules'
          ],

        // opts to pass to node's `child_process` logic
        {
          silent: true,
          stdio: 'pipe'
        }
        );

      var errorMsg = '';
      var stackTrace = '';

      // Log output as it comes in to the appropriate log channel
      child.stdout.on('data', function (consoleMsg) {

        // store all the output
        consoleMsg = consoleMsg.toString();
        errorMsg += consoleMsg;

        // Clean out all the whitespace
        var trimmedStackTrace = (typeof stackTrace === 'string') ? stackTrace : '';
        trimmedStackTrace = trimmedStackTrace.replace(/[\n\s]*$/,'');
        trimmedStackTrace = trimmedStackTrace.replace(/^[\n\s]*/,'');
        var trimmedConsoleMsg = (typeof consoleMsg === 'string') ? consoleMsg : '';
        trimmedConsoleMsg = trimmedConsoleMsg.replace(/[\n\s]*$/,'');
        trimmedConsoleMsg = trimmedConsoleMsg.replace(/^[\n\s]*/,'');

        // Remove '--force to continue' message since it makes no sense
        // in this context:
        trimmedConsoleMsg = trimmedConsoleMsg.replace(/Use --force to continue\./i, '');
        trimmedStackTrace = trimmedStackTrace.replace(/Use --force to continue\./i, '');

        // Find the Stack Trace related to this warning
        stackTrace = errorMsg.substring(errorMsg.lastIndexOf('Running "'));

    //     if (consoleMsg.match(/Use --force to continue/)) {
        // //   sails.log.warn('** Grunt :: Warning **');
        // //   sails.log.warn(errorMsg,trimmedStackTrace);
        // }

        // Handle fatal errors, like missing grunt dependency, etc.
        if (consoleMsg.match(/Fatal error/g)) {

          // If no Gruntfile exists, don't crash- just display a warning.
          if (consoleMsg.match(/Unable to find Gruntfile/i)) {
            sails.log.info('Gruntfile could not be found.');
            sails.log.info('(no grunt tasks will be run.)');
            return;
          }

          Err.fatal.__GruntAborted__(trimmedConsoleMsg, trimmedStackTrace);
          return;
        }

        // Handle fatal Grunt errors by killing Sails process as well
        if (consoleMsg.match(/Aborted due to warnings/)) {
          sails.log.error('** Grunt :: An error occurred. **');
          // sails.log.warn(trimmedStackTrace);
          // sails.emit('hook:grunt:error', trimmedStackTrace);
          Err.fatal.__GruntAborted__(trimmedConsoleMsg, trimmedStackTrace);
          return;
        }

        if (consoleMsg.match(/ParseError/)) {
          sails.log.warn('** Grunt :: Parse Warning **');
          sails.log.warn(trimmedStackTrace);
        }

        // Only display console message if it has content besides whitespace
        else if ( !consoleMsg.match(/^\s*$/) ) {
          sails.log.verbose('Grunt :: ' + trimmedConsoleMsg);
        }
      });

      // Handle general-case grunt output:
      child.stdout.on('error', function (gruntOutput) {
        sails.log.error('Grunt ::', _sanitize(gruntOutput));
      });
      child.stderr.on('data', function (gruntOutput) {
        sails.log.error('Grunt ::', _sanitize(gruntOutput));
      });
      child.stderr.on('error', function (gruntOutput) {
        sails.log.error('Grunt ::', _sanitize(gruntOutput));
      });

      // When process is complete, fire event on `sails`
      child.on('exit', function (code, s) {
        if ( code !== 0 ) return sails.emit('hook:grunt:error');
        sails.emit('hook:grunt:done');

        // Fire finish after grunt is done in production
        if(sails.config.environment === 'production'){
          cb_afterTaskStarted();
        }
      });

      // Since there's likely a watch task involved, and we may need
      // to flush the whole thing, we need a way to grab hold of the child process
      // So we save a reference to it
      sails.log.verbose('Tracking new grunt child process...');
      sails.childProcesses.push(child);

      // Go ahead and get out of here, since Grunt might sit there backgrounded
      if(sails.config.environment !== 'production'){
       cb_afterTaskStarted();
     }
   }
 };
};

/**
 * After ensuring a chunk is a string, trim any leading or
 * trailing whitespace.  If chunk cannot be nicely casted to a string,
 * pass it straight through.
 *
 * @param  {*} chunk
 * @return {*}
 */
 function _sanitize (chunk) {

  if (chunk && typeof chunk === 'object' && chunk.toString) {
    chunk = chunk.toString();
  }
  if (typeof chunk === 'string') {
    chunk = chunk.replace(/^[\s\n]*/, '');
    chunk = chunk.replace(/[\s\n]*$/, '');
  }
  return chunk;
}
<|endoftext|>


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

var Validate = exports;

function InvalidValueError(message) {
  this.message = message;
  this.name = 'InvalidValueError';
  Error.captureStackTrace(this, InvalidValueError);
}
InvalidValueError.prototype = Object.create(Error.prototype);
InvalidValueError.prototype.constructor = InvalidValueError;

InvalidValueError.prepend = function(message, error) {
  if (error instanceof InvalidValueError) {
    return new InvalidValueError(message + ': ' + error.message);
  }
  return error;
};

Validate.InvalidValueError = InvalidValueError;

Validate.acceptAll = function(value) {
  return value;
};

Validate.optional = function(validator) {
  return function(value) {
    return (value == undefined) ? value : validator(value);
  };
};

Validate.that = function(predicate, message) {
  return function(value) {
    if (predicate(value)) return value;
    throw new InvalidValueError(message);
  };
};

Validate.number = Validate.that(function(value) {
  return typeof value === 'number';
}, 'not a number');

Validate.string = Validate.that(function(value) {
  return typeof value === 'string';
}, 'not a string');

Validate.object = function(propertyValidators) {
  return function(object) {
    var result = {};

    if (!object || typeof object !== 'object') {
      throw new InvalidValueError('not an Object');
    }

    // Validate all properties.
    for (key in propertyValidators) {
      var validator = propertyValidators[key];
      try {
        var valid = validator(object[key]);
      } catch (error) {
        if (key in object) {
          throw InvalidValueError.prepend('in property "' + key + '"', error);
        } else {
          throw new InvalidValueError('missing property "' + key + '"');
        }
      }
      if (key in object || valid !== undefined) {
        result[key] = valid;
      }
    }

    // Check for unexpected properties.
    for (var key in object) {
      if (!propertyValidators[key]) {
        throw new InvalidValueError('unexpected property "' + key + '"');
      }
    }

    return result;
  };
};

Validate.array = function(validator) {
  return function(array) {
    var result = [];

    if (Object.prototype.toString.call(array) !== '[object Array]') {
      throw new InvalidValueError('not an Array');
    }

    for (var i = 0; i < array.length; ++i) {
      try {
        result[i] = validator(array[i]);
      } catch (error) {
        throw InvalidValueError.prepend('at index ' + i, error);
      }
    }

    return result;
  };
};

Validate.oneOf = function(names) {
  var myObject = {};
  var quotedNames = [];
  names.forEach(function(name) {
    myObject[name] = true;
    quotedNames.push('"' + name + '"');
  });

  return function(value) {
    if (myObject[value]) return value;
    throw new InvalidValueError('not one of ' + quotedNames.join(', '));
  };
};

Validate.mutuallyExclusiveProperties = function(names) {
  return function(value) {
    if (!value) return value;

    var present = [];
    names.forEach(function(name) {
      if (name in value) {
        present.push('"' + name + '"');
      }
    });

    if (present.length > 1) {
      throw new InvalidValueError(
          'cannot specify properties '
          + present.slice(0, -1).join(', ')
          + ' and '
          + present.slice(-1)
          + ' together');
    }

    return value;
  };
};

Validate.compose = function(validators) {
  return function(value) {
    validators.forEach(function(validate) {
      value = validate(value);
    });
    return value;
  };
};

Validate.boolean = Validate.compose([
  Validate.that(function(value) {
    return typeof value === 'boolean';
  }, 'not a boolean'),
  function(value) {
    // In each API, boolean fields default to false, and the presence of
    // a querystring value indicates true, so we omit the value if
    // explicitly set to false.
    return value ? value : undefined;
  }
]);<commit_msg>Fix validation<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var Validate = exports;

function InvalidValueError(message) {
  this.message = message;
  this.name = 'InvalidValueError';
  Error.captureStackTrace(this, InvalidValueError);
}
InvalidValueError.prototype = Object.create(Error.prototype);
InvalidValueError.prototype.constructor = InvalidValueError;

InvalidValueError.prepend = function(message, error) {
  if (error instanceof InvalidValueError) {
    return new InvalidValueError(message + ': ' + error.message);
  }
  return error;
};

Validate.InvalidValueError = InvalidValueError;

Validate.acceptAll = function(value) {
  return value;
};

Validate.optional = function(validator) {
  return function(value) {
    return (value == undefined) ? value : validator(value);
  };
};

Validate.that = function(predicate, message) {
  return function(value) {
    if (predicate(value)) return value;
    throw new InvalidValueError(message);
  };
};

Validate.number = Validate.that(function(value) {
  return typeof value === 'number';
}, 'not a number');

Validate.string = Validate.that(function(value) {
  return typeof value === 'string';
}, 'not a string');

Validate.object = function(propertyValidators) {
  return function(object) {
    var result = {};

    if (!object || typeof object !== 'object') {
      throw new InvalidValueError('not an Object');
    }

    // Validate all properties.
    for (key in propertyValidators) {
      var validator = propertyValidators[key];
      try {
        var valid = validator(object[key]);
      } catch (error) {
        if (key in object) {
          throw InvalidValueError.prepend('in property "' + key + '"', error);
        } else {
          throw new InvalidValueError('missing property "' + key + '"');
        }
      }
      if (valid !== undefined) {
        result[key] = valid;
      }
    }

    // Check for unexpected properties.
    for (var key in object) {
      if (!propertyValidators[key]) {
        throw new InvalidValueError('unexpected property "' + key + '"');
      }
    }

    return result;
  };
};

Validate.array = function(validator) {
  return function(array) {
    var result = [];

    if (Object.prototype.toString.call(array) !== '[object Array]') {
      throw new InvalidValueError('not an Array');
    }

    for (var i = 0; i < array.length; ++i) {
      try {
        result[i] = validator(array[i]);
      } catch (error) {
        throw InvalidValueError.prepend('at index ' + i, error);
      }
    }

    return result;
  };
};

Validate.oneOf = function(names) {
  var myObject = {};
  var quotedNames = [];
  names.forEach(function(name) {
    myObject[name] = true;
    quotedNames.push('"' + name + '"');
  });

  return function(value) {
    if (myObject[value]) return value;
    throw new InvalidValueError('not one of ' + quotedNames.join(', '));
  };
};

Validate.mutuallyExclusiveProperties = function(names) {
  return function(value) {
    if (!value) return value;

    var present = [];
    names.forEach(function(name) {
      if (name in value) {
        present.push('"' + name + '"');
      }
    });

    if (present.length > 1) {
      throw new InvalidValueError(
          'cannot specify properties '
          + present.slice(0, -1).join(', ')
          + ' and '
          + present.slice(-1)
          + ' together');
    }

    return value;
  };
};

Validate.compose = function(validators) {
  return function(value) {
    validators.forEach(function(validate) {
      value = validate(value);
    });
    return value;
  };
};

Validate.boolean = Validate.compose([
  Validate.that(function(value) {
    return typeof value === 'boolean';
  }, 'not a boolean'),
  function(value) {
    // In each API, boolean fields default to false, and the presence of
    // a querystring value indicates true, so we omit the value if
    // explicitly set to false.
    return value ? value : undefined;
  }
]);<|endoftext|>


<commit_before>const weekday = (date) => {
  if(!(date instanceof Date)) {
    throw new Error("Enter a date object")
  } else {
    const dayName = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
    return dayName[date.getDay()]
  }
}

const capitalizeFourth = (orgStr) => {
  if(typeof orgStr !== 'string') {
    throw new Error('Enter a String')
  } else {
  let setup = orgStr.toLowerCase().split("");
  for(i=3; i < setup.length; i+=4) {
    setup[i] = setup[i].toUpperCase()
  } return setup.join('')
}}

const filterAround = (array, lower, upper) => {
  let outliar = []
  for (i = 0; i < array.length; i++ ) {
    if (typeof array[i] !== 'string'){
      throw new Error("Enter an array of Strings")
    } if(array[i] < lower || array[i] > upper) {
      outliar.push(array[i])
    }
  }return outliar
}

const getValues = (obj) => {
  if (Array.isArray(obj) || typeof obj !== 'object') {
    throw new Error("Enter an Object")
  }return Object.keys(obj).map(function(values) {
    return obj[values];
})}

module.exports = {weekday, capitalizeFourth, getValues, filterAround}
<commit_msg>syntax cleanup<commit_after>const weekday = (date) => {
  if (!(date instanceof Date)) {
    throw new Error("Enter a date object")
  } else {
    const dayName = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
    return dayName[date.getDay()]
  }
}

const capitalizeFourth = (orgStr) => {
  if (typeof orgStr !== 'string') {
    throw new Error('Enter a String')
  } else {
    let setup = orgStr.toLowerCase().split("");
    for (i=3; i < setup.length; i+=4) {
      setup[i] = setup[i].toUpperCase()
    } return setup.join('')
}}

const filterAround = (array, lower, upper) => {
  let outliars = []
  for (i = 0; i < array.length; i++ ) {
    if (typeof array[i] !== 'string'){
      throw new Error("Enter an array of Strings")
    } if (array[i] < lower || array[i] > upper) {
      outliars.push(array[i])
    }
  } return outliars
}

const getValues = (obj) => {
  if (Array.isArray(obj) || typeof obj !== 'object') {
    throw new Error("Enter an Object")
  } return Object.keys(obj).map(function(values) {
    return obj[values]
})}

module.exports = {weekday, capitalizeFourth, getValues, filterAround}
<|endoftext|>


<commit_before>/* eslint-disable react/no-multi-comp */

import React, { Component } from 'react';
import FlybaseDataGrid from 'react-flybase-datagrid';

const doLink = (name, row) => (
  <a href={`http://www.disease-ontology.org/?id=${row.do_id}`}>{name}
);

const headers = [
  {id:'do_name', name:'Disease Name', render: doLink},
  {id:'associationType', name:'Association'},
  {id:'evidence', name:'Evidence Code'},
  {id:'dataProvider', name:'Association Source'},
  {id:'ref', name:'References'}
];

class DiseaseTable extends Component {
  constructor(props) {
    super(props);

    // var diseases = [
    //   {
    //     'associationType': 'contributes_to_condition',
    //     'dataProvider': 'ZFIN',
    //     'do_name': [
    //       'cardiomyopathy'
    //     ],
    //     'evidence': [
    //       {
    //         'evidenceCode': 'TAS',
    //         'pubs': [
    //           {
    //             'pubMedId': '27642634',
    //             'publicationModId': 'ZFIN:ZDB-PUB-160920-5'
    //           },
    //           {
    //             'pubMedId': '1233',
    //             'publicationModId': 'ZFIN:ZDB-PUB-170406-10'
    //           }
    //         ]
    //       }
    //     ],
    //   },
    //   {
    //     'associationType': 'contributes_to_condition',
    //     'dataProvider': 'flybase',
    //     'do_name': [
    //       'cancer'
    //     ],
    //     'evidence': [
    //       {
    //         'evidenceCode': 'TAS',
    //         'pubs': [
    //           {
    //             'pubMedId': '987654',
    //             'publicationModId': 'ZFIN:ZDB-PUB-160920-5'
    //           },
    //           {
    //             'pubMedId': '',
    //             'publicationModId': 'ZFIN:ZDB-PUB-170406-10'
    //           }
    //         ]
    //       }
    //     ],
    //   }
    // ];

  }

  render() {
    const diseases = this.props.data;

    var data = diseases.map((disease) => {
      const {
        associationType: associationType,
        dataProvider: dataProvider,
        do_id: do_id,
        do_name: do_name,
        evidence: [
          {
            evidenceCode: evidenceCode,
            pubs: [ ...pubs ]
          }
        ],
      } = disease;

      return {
        do_id : do_id,
        do_name : do_name,
        associationType: associationType,
        evidence: evidenceCode,
        dataProvider: dataProvider,
        ref: pubs.map((pub) => { return pub['pubMedId']; }).filter((pub) => { return (pub!=undefined); }).join()
      };
    });

    return (

       <FlybaseDataGrid
         columns={headers}
         data={data}
         downloadButton={['tsv']}
         showColumnFilter
         width={1110}
       />

    );
  }
}

DiseaseTable.propTypes = {
  data: React.PropTypes.array.isRequired,
};

export default DiseaseTable;
<commit_msg>set maxHeight to avoid scrolling<commit_after>/* eslint-disable react/no-multi-comp */

import React, { Component } from 'react';
import FlybaseDataGrid from 'react-flybase-datagrid';

const doLink = (name, row) => (
  <a href={`http://www.disease-ontology.org/?id=${row.do_id}`}>{name}
);

const headers = [
  {id:'do_name', name:'Disease Name', render: doLink},
  {id:'associationType', name:'Association'},
  {id:'evidence', name:'Evidence Code'},
  {id:'dataProvider', name:'Association Source'},
  {id:'ref', name:'References'}
];

class DiseaseTable extends Component {
  constructor(props) {
    super(props);

    // var diseases = [
    //   {
    //     'associationType': 'contributes_to_condition',
    //     'dataProvider': 'ZFIN',
    //     'do_name': [
    //       'cardiomyopathy'
    //     ],
    //     'evidence': [
    //       {
    //         'evidenceCode': 'TAS',
    //         'pubs': [
    //           {
    //             'pubMedId': '27642634',
    //             'publicationModId': 'ZFIN:ZDB-PUB-160920-5'
    //           },
    //           {
    //             'pubMedId': '1233',
    //             'publicationModId': 'ZFIN:ZDB-PUB-170406-10'
    //           }
    //         ]
    //       }
    //     ],
    //   },
    //   {
    //     'associationType': 'contributes_to_condition',
    //     'dataProvider': 'flybase',
    //     'do_name': [
    //       'cancer'
    //     ],
    //     'evidence': [
    //       {
    //         'evidenceCode': 'TAS',
    //         'pubs': [
    //           {
    //             'pubMedId': '987654',
    //             'publicationModId': 'ZFIN:ZDB-PUB-160920-5'
    //           },
    //           {
    //             'pubMedId': '',
    //             'publicationModId': 'ZFIN:ZDB-PUB-170406-10'
    //           }
    //         ]
    //       }
    //     ],
    //   }
    // ];

  }

  render() {
    const diseases = this.props.data;

    var data = diseases.map((disease) => {
      const {
        associationType: associationType,
        dataProvider: dataProvider,
        do_id: do_id,
        do_name: do_name,
        evidence: [
          {
            evidenceCode: evidenceCode,
            pubs: [ ...pubs ]
          }
        ],
      } = disease;

      return {
        do_id : do_id,
        do_name : do_name,
        associationType: associationType,
        evidence: evidenceCode,
        dataProvider: dataProvider,
        ref: pubs.map((pub) => { return pub['pubMedId']; }).filter((pub) => { return (pub!=undefined); }).join()
      };
    });

    return (

       <FlybaseDataGrid
         columns={headers}
         data={data}
         downloadButton={['tsv']}
         showColumnFilter
         maxHeight={1000}
         width={1110}
       />

    );
  }
}

DiseaseTable.propTypes = {
  data: React.PropTypes.array.isRequired,
};

export default DiseaseTable;
<|endoftext|>