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

import Table from 'src/Table';
import Switcher from 'src/Switcher';
import IconButton from 'src/IconButton';
import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';
import RaisedButton from 'src/RaisedButton';

import PropTypeDescTable from 'components/PropTypeDescTable';
import doc from 'assets/propTypes/Table.json';

import 'scss/containers/app/modules/layout/TableExamples.scss';

class TableExamples extends Component {

    constructor(props) {

        super(props);

        this.columns = [{
            header: 'ID',
            sortable: true,
            sortProp: 'id',
            renderer: 'id',
            headerClassName: 'test-header',
            cellClassName: 'test-cell'
        }, {
            header: 'Name',
            sortable: true,
            sortProp: 'firstName',
            renderer: '${firstName} - ${lastName}'
        }, {
            header: 'Status',
            renderer: rowData =>
                <Switcher value={!rowData.disabled}
                          size="small"
                          onClick={e => e.stopPropagation()}/>
        }];

        this.pageSizes = [{
            value: 10,
            text: '10 / page'
        }, {
            value: 20,
            text: '20 / page'
        }, {
            value: 30,
            text: '30 / page'
        }, {
            value: 40,
            text: '40 / page'
        }, {
            value: 50,
            text: '50 / page'
        }];

        this.state = {
            data: this.generateData(),
            sort: null
        };

    }

    generateData = (size = 100) => {

        let data = [];
        for (let i = 0; i < size; i++) {
            data.push({
                id: i,
                firstName: `firstName ${i}`,
                lastName: `lastName ${i}`
            });
        }

        return data;

    };

    deleteRow = id => {

        const {data} = this.state,
            newData = data.filter(item => item.id !== id);

        this.setState({
            data: newData
        });

    };

    sortHandler = sort => {
        this.setState({
            sort
        });
        console.log('Sort Change Value: ', sort);
    };

    pageChangeHandler = (page, pageSize) => {
        console.log(`page: ${page}, pageSize: ${pageSize}`);
    };

    dataUpdateHandler = currentPageData => {
        console.log('Data Update Value: ', currentPageData);
    };

    selectAllHandler = value => {
        console.log('Select All Value: ', value);
    };

    deselectAllHandler = value => {
        console.log('Deselect All Value: ', value);
    };

    changeHandler = value => {
        console.log('Changed Value: ', value);
    };

    clearSort = () => {
        this.setState({
            sort: null
        });
    };

    render() {

        const {data, sort} = this.state;

        return (

Table

                    Tables
                    are used to display data and to organize it.

Examples

                <Widget>

                    <WidgetHeader className="example-header" title="With isPagging"/>

A simple Table example.

                                           <IconButton iconCls="fas fa-trash-alt"
                                                       onClick={() => this.deleteRow(rowData.id)}/>
                                   }]}
                                   sort={sort}
                                   paggingCountRenderer={count => Self Defined Total Count: {count}}
                                   onSort={this.sortHandler}
                                   onPageChange={this.pageChangeHandler}
                                   onDataUpdate={this.dataUpdateHandler}/>

                            <RaisedButton className="table-action"
                                          theme={RaisedButton.Theme.PRIMARY}
                                          value="Clear Table Sort"
                                          onClick={this.clearSort}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="With hasLineNumber and isMultiSelect"/>

A more complex example.Set the hasLineNumber and isMultiSelect
                                to true for showLineNumber and checkbox.

                            <Table data={data}
                                   columns={this.columns}
                                   selectMode={Table.SelectMode.MULTI_SELECT}
                                   selectAllMode={Table.SelectAllMode.CURRENT_PAGE}
                                   paggingSelectedCountVisible={true}
                                   defaultPageSize={20}
                                   pageSizes={this.pageSizes}
                                   useFullPagging={true}
                                   sortAscIconCls="fas fa-caret-up"
                                   sortDescIconCls="fas fa-caret-down"
                                   onPageChange={this.pageChangeHandler}
                                   onSelectAll={this.selectAllHandler}
                                   onDeselectAll={this.deselectAllHandler}
                                   onChange={this.changeHandler}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="Empty"/>

                </Widget>

Properties

                <PropTypeDescTable data={doc}/>

        );
    }
};

export default TableExamples;
<commit_msg>update TableExamples<commit_after>import React, {Component} from 'react';

import Table from 'src/Table';
import Switcher from 'src/Switcher';
import IconButton from 'src/IconButton';
import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';
import RaisedButton from 'src/RaisedButton';

import PropTypeDescTable from 'components/PropTypeDescTable';
import doc from 'assets/propTypes/Table.json';

import 'scss/containers/app/modules/layout/TableExamples.scss';

class TableExamples extends Component {

    constructor(props) {

        super(props);

        this.columns = [{
            header: 'ID',
            sortable: true,
            sortProp: 'id',
            renderer: 'id',
            headerClassName: 'test-header',
            cellClassName: 'test-cell'
        }, {
            header: 'Name',
            sortable: true,
            sortProp: 'firstName',
            renderer: '${firstName} - ${lastName}'
        }, {
            header: 'Status',
            renderer: rowData =>
                <Switcher value={!rowData.disabled}
                          size="small"
                          onClick={e => e.stopPropagation()}/>
        }];

        this.pageSizes = [{
            value: 10,
            text: '10 / page'
        }, {
            value: 20,
            text: '20 / page'
        }, {
            value: 30,
            text: '30 / page'
        }, {
            value: 40,
            text: '40 / page'
        }, {
            value: 50,
            text: '50 / page'
        }];

        this.state = {
            data: this.generateData(),
            sort: null
        };

    }

    generateData = (size = 100) => {

        let data = [];
        for (let i = 0; i < size; i++) {
            data.push({
                id: i,
                firstName: `firstName ${i}`,
                lastName: `lastName ${i}`
            });
        }

        return data;

    };

    deleteRow = id => {

        const {data} = this.state,
            newData = data.filter(item => item.id !== id);

        this.setState({
            data: newData
        });

    };

    sortHandler = sort => {
        this.setState({
            sort
        });
        console.log('Sort Change Value: ', sort);
    };

    pageChangeHandler = (page, pageSize) => {
        console.log(`page: ${page}, pageSize: ${pageSize}`);
    };

    dataUpdateHandler = currentPageData => {
        console.log('Data Update Value: ', currentPageData);
    };

    selectHandler = value => {
        console.log('Select Value: ', value);
    };

    deselectHandler = value => {
        console.log('Deselect Value: ', value);
    };

    selectAllHandler = value => {
        console.log('Select All Value: ', value);
    };

    deselectAllHandler = value => {
        console.log('Deselect All Value: ', value);
    };

    changeHandler = value => {
        console.log('Changed Value: ', value);
    };

    clearSort = () => {
        this.setState({
            sort: null
        });
    };

    render() {

        const {data, sort} = this.state;

        return (

Table

                    Tables
                    are used to display data and to organize it.

Examples

                <Widget>

                    <WidgetHeader className="example-header" title="With isPagging"/>

A simple Table example.

                                           <IconButton iconCls="fas fa-trash-alt"
                                                       onClick={() => this.deleteRow(rowData.id)}/>
                                   }]}
                                   sort={sort}
                                   paggingCountRenderer={count => Self Defined Total Count: {count}}
                                   onSort={this.sortHandler}
                                   onPageChange={this.pageChangeHandler}
                                   onDataUpdate={this.dataUpdateHandler}/>

                            <RaisedButton className="table-action"
                                          theme={RaisedButton.Theme.PRIMARY}
                                          value="Clear Table Sort"
                                          onClick={this.clearSort}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="With hasLineNumber and isMultiSelect"/>

A more complex example.Set the hasLineNumber and isMultiSelect
                                to true for showLineNumber and checkbox.

                            <Table data={data}
                                   columns={this.columns}
                                   selectMode={Table.SelectMode.MULTI_SELECT}
                                   selectAllMode={Table.SelectAllMode.CURRENT_PAGE}
                                   paggingSelectedCountVisible={true}
                                   defaultPageSize={20}
                                   pageSizes={this.pageSizes}
                                   useFullPagging={true}
                                   sortAscIconCls="fas fa-caret-up"
                                   sortDescIconCls="fas fa-caret-down"
                                   onPageChange={this.pageChangeHandler}
                                   onSelect={this.selectHandler}
                                   onDeselect={this.deselectHandler}
                                   onSelectAll={this.selectAllHandler}
                                   onDeselectAll={this.deselectAllHandler}
                                   onChange={this.changeHandler}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="Empty"/>

                </Widget>

Properties

                <PropTypeDescTable data={doc}/>

        );
    }
};

export default TableExamples;
<|endoftext|>


<commit_before>const Twit = require('twit');

const T = new Twit({
	consumer_key: process.env.TWITTER_CONSUMER_KEY,
	consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
	access_token: process.env.TWITTER_ACCESS_TOKEN,
	access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
	timeout_ms: 60 * 1000,
});

// Private functions

function handleDonation(text) {
	const count = text.split('💰')
		.length - 1;
	console.log(`[Bot] Thanks for donating ${count} money bags! 👍`);
}

function handleStatus() {
	console.log('[Bot] Still going strong, thanks!');
}

function handleMention(tweet) {
	const text = tweet.text;
	console.log(`[Bot] Somebody mentioned me in the following tweet:\n ${text}`);
	if (text.includes('💰')) handleDonation(text);
	if (text.include('status')) handleStatus();
}

// Public functions

exports.listen = () => {
	const stream = T.stream('statuses/filter', {
		track: ['@HelpTerence'],
	});

	stream.on('connected', () => {
		console.log('[Bot] Connected to stream. Listening...');
	});

	stream.on('tweet', handleMention);

	stream.on('reconnecting', (req, res, connectInterval) => {
		console.log('[Bot] Got disconnected. Scheduling reconnect! statusCode:',
			res.statusCode,
			'connectInterval',
			connectInterval);
	});

	stream.on('error', (err) => {
		console.log('[Bot] Stream emitted an error', err);
	});

	stream.on('disconnected', () => {
		console.log('[Bot] Disconnected from stream.');
	});
};

// Exports for tests
exports.__tests.handleMention = handleMention;
exports.__tests.handleStatus = handleStatus;
exports.__tests.handleDonation = handleDonation;
<commit_msg>fixes bugs<commit_after>const Twit = require('twit');

const T = new Twit({
	consumer_key: process.env.TWITTER_CONSUMER_KEY,
	consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
	access_token: process.env.TWITTER_ACCESS_TOKEN,
	access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
	timeout_ms: 60 * 1000,
});

// Private functions

function handleDonation(tweet) {
	const text = tweet.text;
	// Get donation count
	// Get user Id
	// Save donation
	// Create a thank you string
	// Tweet string
	const count = text.split('💰')
		.length - 1;
	console.log(`[Bot] Thanks for donating ${count} money bags! 👍`);
}

function handleStatus() {
	console.log('[Bot] Still going strong, thanks!');
}

function handleMention(tweet) {
	const text = tweet.text;
	console.log(`[Bot] Somebody mentioned me in the following tweet:\n ${text}`);
	if (text.includes('💰')) handleDonation(tweet);
	if (text.includes('status')) handleStatus();
}

// Public functions

exports.listen = () => {
	const stream = T.stream('statuses/filter', {
		track: ['@HelpTerence'],
	});

	stream.on('connected', () => {
		console.log('[Bot] Connected to stream. Listening...');
	});

	stream.on('tweet', handleMention);

	stream.on('reconnecting', (req, res, connectInterval) => {
		console.log('[Bot] Got disconnected. Scheduling reconnect! statusCode:',
			res.statusCode,
			'connectInterval',
			connectInterval);
	});

	stream.on('error', (err) => {
		console.log('[Bot] Stream emitted an error', err);
	});

	stream.on('disconnected', () => {
		console.log('[Bot] Disconnected from stream.');
	});
};

// Exports for tests
const __tests = {};
__tests.handleMention = handleMention;
__tests.handleStatus = handleStatus;
__tests.handleDonation = handleDonation;
exports.__tests = __tests;
<|endoftext|>


<commit_before>'use strict';
const _ = require('lodash'),
  log = require('../../logger'),
  Promise = require('bluebird'),
  request = Promise.promisifyAll(require('request')),
  xmldom = require('xmldom'),
  config = require('config');

let suffixArray = [],
  tagNames = [];

exports.find = function find(env, query, queryType, options) {
  suffixArray = [];
  tagNames = [];
  // If query is not specified, return everything in scope
  if (!query) {
    return Promise.resolve(options.scope);
  }
  if (queryType === 'ui') {
    _extractTags(query);
    if (suffixArray.length > 0 && tagNames.length > 0) {
      return Promise.all([getSolrRequest('uiTagCollection', suffixArray, options.scope),
                getSolrRequest('uiSuffixCollection', tagNames, options.scope)])
        .then((ids) => {
          return Promise.resolve(_.intersection(ids[0], ids[1]));
        })
        .catch(() => {
          return Promise.reject(new Error('Failed to get index ' +
            'results from the uiTagCollection and uiSuffixCollection'));
        });
    }
    else if (suffixArray.length > 0 && tagNames.length === 0) {
      return getSolrRequest('uiSuffixCollection', suffixArray, options.scope)
        .then((ids) => {
          return Promise.resolve(ids);
        })
        .catch(() => {
          return Promise.reject(new Error('Failed to get index ' +
            'results from the uiSuffixCollection'));
        });
    }
    else if (tagNames.length > 0 && suffixArray.length === 0) {
      return getSolrRequest('uiTagCollection', tagNames, options.scope)
        .then((ids) => {
          return Promise.resolve(ids);
        })
        .catch(() => {
          return Promise.reject(new Error(
            'Failed to get index results from the uiTagCollection'));
        });
    }
    return Promise.reject(new Error(
        'IndexSearchError: No tags are found for the given query'));
  }
  else if (queryType === 'manifest') {
    _extractTags(query);
    if (tagNames.length === 0 && suffixArray.length > 0) {
      _.forEach(suffixArray, (item) => {
        tagNames.push(item.split('$'));
      });
      tagNames = _.flattenDeep(tagNames);
      tagNames = _.unique(tagNames);
    }
    return getSolrRequest('manifestCollection', tagNames, options.scope)
      .then((ids) => {
        return Promise.resolve(ids);
      })
      .catch(() => {
        return Promise.reject(new Error(
          'Failed to get index results from the manifestCollection'));
      });
  }
  return Promise.reject(new Error('Unknown index type'));
};

function getSolrRequest(collectionName, arrValues, ids) {
  const solrConfig = config.get('dbConfig.solr'),
    reqURL = `http://${solrConfig.host}:${solrConfig.port}/solr/${solrConfig[collectionName]}/query`,
    terms = _.map(arrValues, (val) => {
      if (val.indexOf('*') > -1 && val.indexOf('*$') === -1 &&
        val.indexOf('$*') === -1) {
        return _escapeSpecialCharacters(val);
      }
      return `"${_escapeSpecialCharacters(val)}"`;
    }),
    scope = ids.join(' OR '),
    _text_ = terms.join(' && '),
    reqObj = {
      url: reqURL,
      qs: {
        q: `_text_:${_text_} AND (id: ${scope} )`,
        wt: 'json',
        rows: config.get('dbConfig.solr.maxRows'),
        fl: 'id'
      }
    };

  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;
      return Promise.resolve(_.pluck(docs, 'id'));
    })
    .catch(clientError, (e) => {
      log.error(e);
      return Promise.reject(e);
    });
}

function _extractTags(queryText) {
  const doc = new xmldom.DOMParser()
    .parseFromString(queryText, 'text/xml'),
    rootElementList = _.filter(doc.childNodes, (child) => {
      return child.nodeType === 1;
    });
  // Add xml tags that have star e.g.,(<com.myview.* />, <com.myview.* attr="2"/>)
  _.forEach(doc.childNodes, (child) => {
    if (child.nodeType === 3 && child.data.indexOf('*') > -1) {
      const tagWithStar = child.data.split('/>')[0];
      if (tagWithStar && tagWithStar.indexOf(' ') > -1) {
        tagNames.push(tagWithStar.split(' ')[0]);
      }
      else {
        tagNames.push(tagWithStar);
      }
    }
  });
  _.forEach(rootElementList, (root) => {
    const children = _.filter(root.childNodes, (child) => {
      return child.nodeType === 1;
    });
    if (children.length === 0) {
      addTagName(root);
    }
    _.forEach(children, (child) => {
      addChildren(child, root);
    });
  });
}

function addChildren(element, parent) {
  let parentName = parent.localName,
    elementName = element.localName;
  if (parentName === '_') {
    parentName = '*';
  }
  if (elementName === '_') {
    elementName = '*';
  }
  if (element.hasChildNodes()) {
    suffixArray.push(`${parentName}$${elementName}`);
    const children = _.filter(element.childNodes, (child) => {
      return child.nodeType === 1;
    });
    _.forEach(children, (child) => {
      addChildren(child, element);
    });
  }
  else {
    suffixArray.push(`${parentName}$${elementName}`);
  }
}

function addTagName(element) {
  let elementName = element.localName;
  // Skip anonymous tags
  if (element.localName === '_') {
    elementName = '*';
  }
  // Add element name and attributes
  if (element.attributes.length > 0) {
    _.forEach(element.attributes, (attr) => {
      const attrName = _ExtractReturnParameters(attr.nodeName),
        attrVal = _ExtractReturnParameters(attr.nodeValue);
      let searchTerm = elementName;
      if (attrName && attrVal) {
        if (attrVal.indexOf('*') > -1) {
          searchTerm += ` AND ${attrVal}`;
        }
        else {
          searchTerm += `(${attrName}="${attrVal}")`;
        }
      }
      else {
        if (attrName) {
          searchTerm += `(${attrName}`;
        }
      }
      tagNames.push(searchTerm);
    });
  } // Only add element tag name
  else {
    tagNames.push(elementName);
  }
}

/**
 * Escape a string that uses any of Solr's special characters except the *.
 * + - && || ! ( ) { } [ ] ^ " ~ ? : /
 * @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;
}

// e.g. <element>(app*)</element> and <element="(*)">(*)</element>
function _ExtractReturnParameters(value) {
  let newValue;
  if (value && value.trim()
    .indexOf('(') === 0) {
    if (value.trim()[value.length - 1] === ')') {
      newValue = value.trim()
        .substring(1, value.length - 1);
    }
  }
  if (value === '*') {
    return null;
  }
  return newValue;
}
<commit_msg>Revert "refactor"<commit_after>'use strict';
const _ = require('lodash'),
  log = require('../../logger'),
  Promise = require('bluebird'),
  request = Promise.promisifyAll(require('request')),
  xmldom = require('xmldom'),
  config = require('config');

let suffixArray = [],
  tagNames = [];

exports.find = function find(env, query, queryType, options) {
  suffixArray = [];
  tagNames = [];
  // If query is not specified, return everything in scope
  if (!query) {
    return Promise.resolve(options.scope);
  }
  if (queryType === 'ui') {
    _extractTags(query);
    if (suffixArray.length > 0 && tagNames.length > 0) {
      return Promise.all([getSolrRequest('uiTagCollection', suffixArray),
                getSolrRequest('uiSuffixCollection', tagNames)])
        .then((ids) => {
          const inter = _.intersection(ids[0], options.scope);
          return Promise.resolve(_.intersection(ids[1], inter));
        })
        .catch(() => {
          return Promise.reject(new Error('Failed to get index ' +
            'results from the uiTagCollection and uiSuffixCollection'));
        });
    }
    else if (suffixArray.length > 0 && tagNames.length === 0) {
      return getSolrRequest('uiSuffixCollection', suffixArray)
        .then((ids) => {
          return Promise.resolve(_.intersection(ids, options.scope));
        })
        .catch(() => {
          return Promise.reject(new Error('Failed to get index ' +
            'results from the uiSuffixCollection'));
        });
    }
    else if (tagNames.length > 0 && suffixArray.length === 0) {
      return getSolrRequest('uiTagCollection', tagNames)
        .then((ids) => {
          return Promise.resolve(_.intersection(ids, options.scope));
        })
        .catch(() => {
          return Promise.reject(new Error('Failed to get index ' +
            'results from the uiTagCollection'));
        });
    }
    else {
      return Promise.reject(new Error('IndexSearchError: No tags are ' +
        'found for the given query'));
    }
  }
  else if (queryType === 'manifest') {
    _extractTags(query);
    if (tagNames.length === 0 && suffixArray.length > 0) {
      _.forEach(suffixArray, (item) => {
        tagNames.push(item.split('$'));
      });
      tagNames = _.flattenDeep(tagNames);
      tagNames = _.unique(tagNames);
    }
    return getSolrRequest('manifestCollection', tagNames)
      .then((ids) => {
        return Promise.resolve(_.intersection(ids, options.scope));
      })
      .catch(() => {
        return Promise.reject(new Error('Failed to get index ' +
          'results from the manifestCollection'));
      });
  }
  else {
    return Promise.reject(new Error('Unknown index type'));
  }
};

function getSolrRequest(collectionName, arrValues) {
  const solrConfig = config.get('dbConfig.solr'),
    reqURL = 'http://' + solrConfig.host + ':' + solrConfig.port +
    '/solr/' + solrConfig[collectionName] + '/query';
  const terms = _.map(arrValues, (val) => {
    if (val.indexOf('*') > -1 && val.indexOf('*$') === -1 &&
      val.indexOf('$*') === -1) {
      return _escapeSpecialCharacters(val);
    }
    return '"' + _escapeSpecialCharacters(val) + '"';
  });
  const _text_ = terms.join(' && '),
    reqObj = {
      url: reqURL,
      qs: {
        q: '_text_:' + _text_,
        wt: 'json',
        rows: config.get('dbConfig.solr.maxRows'),
        fl: 'id'
      }
    };

  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;
      return Promise.resolve(_.pluck(docs, 'id'));
    })
    .catch(clientError, (e) => {
      log.error(e);
      return Promise.reject(e);
    });
}

function _extractTags(queryText) {
  const doc = new xmldom.DOMParser()
    .parseFromString(queryText, 'text/xml'),
    rootElementList = _.filter(doc.childNodes, (child) => {
      return child.nodeType === 1;
    });
  // Add xml tags that have star e.g.,(<com.myview.* />, <com.myview.* attr="2"/>)
  _.forEach(doc.childNodes, (child) => {
    if (child.nodeType === 3 && child.data.indexOf('*') > -1) {
      const tagWithStar = child.data.split('/>')[0];
      if (tagWithStar && tagWithStar.indexOf(' ') > -1) {
        tagNames.push(tagWithStar.split(' ')[0]);
      }
      else {
        tagNames.push(tagWithStar);
      }
    }
  });
  _.forEach(rootElementList, (root) => {
    const children = _.filter(root.childNodes, (child) => {
      return child.nodeType === 1;
    });
    if (children.length === 0) {
      addTagName(root);
    }
    _.forEach(children, (child) => {
      addChildren(child, root);
    });
  });
}

function addChildren(element, parent) {
  let parentName = parent.localName,
    elementName = element.localName;
  if (parentName === '_') {
    parentName = '*';
  }
  if (elementName === '_') {
    elementName = '*';
  }
  if (element.hasChildNodes()) {
    suffixArray.push(parentName + '$' + elementName);
    const children = _.filter(element.childNodes, (child) => {
      return child.nodeType === 1;
    });
    _.forEach(children, (child) => {
      addChildren(child, element);
    });
  }
  else {
    suffixArray.push(parentName + '$' + elementName);
  }
}

function addTagName(element) {
  let elementName = element.localName;
  // Skip anonymous tags
  if (element.localName === '_') {
    elementName = '*';
  }
  // Add element name and attributes
  if (element.attributes.length > 0) {
    _.forEach(element.attributes, (attr) => {
      const attrName = _ExtractReturnParameters(attr.nodeName),
        attrVal = _ExtractReturnParameters(attr.nodeValue);
      let searchTerm = elementName;
      if (attrName && attrVal) {
        if (attrVal.indexOf('*') > -1) {
          searchTerm += ' AND ' + attrVal;
        }
        else {
          searchTerm += '(' + attrName + '="' +
            attrVal + '")';
        }
      }
      else {
        if (attrName) {
          searchTerm += '(' + attrName;
        }
      }
      tagNames.push(searchTerm);
    });
  } // Only add element tag name
  else {
    tagNames.push(elementName);
  }
}

/**
 * Escape a string that uses any of Solr's special characters except the *.
 * + - && || ! ( ) { } [ ] ^ " ~ ? : /
 * @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;
}

// e.g. <element>(app*)</element> and <element="(*)">(*)</element>
function _ExtractReturnParameters(value) {
  let newValue;
  if (value && value.trim()
    .indexOf('(') === 0) {
    if (value.trim()[value.length - 1] === ')') {
      newValue = value.trim()
        .substring(1, value.length - 1);
    }
  }
  if (value === '*') {
    return null;
  }
  return newValue;
}
<|endoftext|>


<commit_before>'use strict';

module.exports = {
    width: 15,
    height: 16,
    tiles: [
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1],
        [1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1],
        [0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0],
        [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
        [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1],
        [1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1],
        [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1],
        [1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1],
        [1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
    ],
    respawnPoints: [
        {y: 1, x: 1},
        {y: 1, x: 13},
        {y: 3, x: 7},
        {y: 12, x: 7},
        {y: 14, x: 1},
        {y: 14, x: 13}
    ],
    bgm: 1
};
<commit_msg>fix map tile<commit_after>'use strict';

module.exports = {
    width: 15,
    height: 16,
    tiles: [
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1],
        [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1],
        [1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1],
        [0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0],
        [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
        [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1],
        [1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1],
        [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1],
        [1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1],
        [1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
    ],
    respawnPoints: [
        {y: 1, x: 1},
        {y: 1, x: 13},
        {y: 3, x: 7},
        {y: 12, x: 7},
        {y: 14, x: 1},
        {y: 14, x: 13}
    ],
    bgm: 1
};
<|endoftext|>


<commit_before>'use strict';

var child = require('child_process');

/**
 * getCurrentNpmLs get actual version of packages via running npm list command
 * @param  {Object} options
 * @return {Promise}
 */
function getCurrentNpmLs(options) {
    return new Promise(function(resolve, reject) {
        child.exec('npm list --depth=0 --json' +
            (options.prod ? ' --prod' : '') +
            (options.dev ? ' --dev' : ''), {
                cwd: options.directory
            }, function(error, stdout, stderr) {
            var curDeps = JSON.parse(stdout).dependencies;
            resolve(curDeps);
        });
    });
}

module.exports = getCurrentNpmLs;
<commit_msg>reject if npm isnt installed<commit_after>'use strict';

var child = require('child_process');

/**
 * getCurrentNpmLs get actual version of packages via running npm list command
 * @param  {Object} options
 * @return {Promise}
 */
function getCurrentNpmLs(options) {
    return new Promise(function(resolve, reject) {
        child.exec('npm list --depth=0 --json' +
            (options.prod ? ' --prod' : '') +
            (options.dev ? ' --dev' : ''), {
                cwd: options.directory
            }, function(error, stdout, stderr) {
            var curDeps;

            // if `npm` command not found
            if (error && error.code === 127) {
                reject(stderr);
                return;
            }

            curDeps = JSON.parse(stdout).dependencies;
            resolve(curDeps);
        });
    });
}

module.exports = getCurrentNpmLs;
<|endoftext|>


<commit_before>var jQuery = require('jquery');
var inherits = require('util').inherits;
var EventEmitter = require('events').EventEmitter;
var extend = require('extend');
var forEach = require('foreach');
var globi = require('globi');
var globiData = globi.globiData;
var TypeSelector = require('./lib/TypeSelector.js');
var TaxonSelector = require('./lib/TaxonSelector.js');
var SearchResult = require('./lib/SearchResult.js');
var taxaprisma = require('taxaprisma');

module.exports = Plugin;

inherits(Plugin, EventEmitter);

Plugin.Result = SearchResult;
var ItemData = {
    source: {
        set: false
    },
    target: {
        set: false
    },
    link: {
        set: false
    }
};

var FilterElementContainer = null;

function Plugin(settings) {
    if (!(this instanceof Plugin)) {
        return new Plugin(settings);
    }
    this.settings = extend({
        filterContainer: null,
        resultContainer: null
    }, settings);

    this.searchContext = this.settings.searchContext;
    this.init();
}

extend(Plugin.prototype, {
    init: function () {
        var me = this;
        me.el = null;
        me.sourceSelector = null;
        me.targetSelector = null;
        me.typeSelector = null;
        me.searchResult = null;

        me.buildUi();
        me.events();
    },

    appendTo: function (target) {
        var me = this;
        if (typeof target === 'string') target = document.querySelector(target);

        if (FilterElementContainer === null) {
            FilterElementContainer = target.parentNode;
            target.parentNode.insertBefore(me.filterElement, target);
        }
        this.emit('append', target);
    },

    events: function () {
        var me = this;
        me.searchContext.on('taxonselector:selected', proxy(me.taxonSelected, me));
        me.searchContext.on('typeselector:selected', proxy(me.typeSelected, me));
        me.searchContext.on('searchresult:itemselected', proxy(me.itemSelected, me));
        me.searchContext.on('globisearch:resultsetchanged', proxy(me.showResult, me));

        document.addEventListener("click",function(e) {
            if (e.target && e.target.matches(".scientific-name")) {
                var taxonName = e.target.textContent;
                me.sourceSelector.clear();
                me.sourceSelector.add(taxonName);
                me.targetSelector.clear();
                me.searchContext.update({ sourceTaxon: taxonName, targetTaxon: null });

            }
        });
    },

    showResult: function (data) {
        var me = this;
        var searchHash = {
            includeObservations: true,
            field: ['source_taxon_id', 'source_taxon_name', 'source_taxon_path', 'source_taxon_path_ids'
                , 'source_specimen_life_stage_id', 'source_specimen_life_stage'
                , 'source_specimen_physiological_state_id', 'source_specimen_physiological_state'
                , 'source_specimen_body_part_id', 'source_specimen_body_part'
                , 'source_specimen_sex_id', 'source_specimen_sex'
                , 'interaction_type'
                , 'target_taxon_id', 'target_taxon_name', 'target_taxon_path', 'target_taxon_path_ids'
                , 'target_specimen_life_stage_id',  'target_specimen_life_stage'
                , 'target_specimen_physiological_state_id', 'target_specimen_physiological_state'
                , 'target_specimen_body_part_id', 'target_specimen_body_part'
                , 'target_specimen_sex_id', 'target_specimen_sex'
                , 'latitude', 'longitude'
                , 'study_citation', 'study_url', 'study_source_citation']
        };
        var downloadUrls = ['csv'].map(function(resultType) {
            var searchParams = extend({ limit: 4096 }, me.searchContext.searchParameters, searchHash);
            searchParams.resultType = resultType;
            var link = {};
            link.resultType = resultType;
            link.url = globiData.urlForTaxonInteractionQuery(searchParams);
            return link;
        });
        me.searchContext.emit('searchfilter:showresults', processDataForResultList(data), downloadUrls);
    },

    update: function (data) {
        var me = this;
    },

    buildUi: function () {
        var me = this;
        var table = createElement('table', 'search-row'),
            row = createElement('tr'),
            td;

        me.filterElement = createElement('div', 'search-filter');

        td = createElement('td', 'source-taxon-selector-cell');
        td.appendChild(me.createSourceSelector().el);
        row.appendChild(td);

        td = createElement('td', 'type-selector-cell', ['filter-middle-column']);
        td.appendChild(me.createTypeSelector().el);
        row.appendChild(td);

        td = createElement('td', 'target-taxon-selector-cell');
        td.appendChild(me.createTargetSelector().el);
        row.appendChild(td);

        table.appendChild(row);

        me.filterElement.appendChild(table);

        me.populateTypeSelector();
    },

    createTypeSelector: function () {
        var me = this;
        this.typeSelector = new TypeSelector({
            idPrefix: 'source',
            type: 'interactiontype',
            usePlaceholder: false,
            searchContext: me.searchContext,
            startValue: me.searchContext.searchParameters.interactionType
        });

        this.typeSelector.disable();

        return this.typeSelector;
    },

    createSourceSelector: function () {
        var me = this;
        var taxa = me.searchContext.searchParameters.sourceTaxon || [];
        if (!Array.isArray(taxa)) {
            taxa = [taxa];
        }
        this.sourceSelector = new TaxonSelector({
            idPrefix: 'source',
            type: 'source',
            searchContext: me.searchContext,
            preSelectedTaxa: taxa
        });
        return this.sourceSelector;
    },

    createTargetSelector: function () {
        var me = this;
        var taxa = me.searchContext.searchParameters.targetTaxon || [];
        if (!Array.isArray(taxa)) {
            taxa = [taxa];
        }

        this.targetSelector = new TaxonSelector({
            idPrefix: 'target',
            type: 'target',
            searchContext: me.searchContext,
            preSelectedTaxa: taxa
        });
        return this.targetSelector;
    },

    createSearchResult: function () {
        var me = this;
        this.searchResult = new SearchResult({
            searchContext: me.searchContext
        });

        return this.searchResult;
    },

    populateTypeSelector: function () {
        var me = this;

        globiData.findInteractionTypes(
            [],
            {
                callback: function (data) {
                    forEach(data, function (value, key, object) {
                        me.typeSelector.addOption(camelCaseToRealWords(key), key);
                    });
                    me.typeSelector.enable();
                },
                context: me
            }
        );
    },

    itemSelected: function (data) {
        var me = this;
        if (me.searchContext.isAbleToFetch('GlobiSearch::itemselected')) {
            me.searchContext.lockFetching('GlobiSearch::itemselected');
            if (data['source'] && data['source']['name']) {
                globiData.findTaxonInfo(data['source']['name'], function (sourceData) {
                    extend(sourceData, data['source']);
                    me.populateItemData(sourceData, data['source']['id'], 'source');
                    if (data['target'] && data['target']['name']) {
                        globiData.findTaxonInfo(data['target']['name'], function (targetData) {
                            extend(targetData, data['target']);
                            me.populateItemData(targetData, data['target']['id'], 'target');
                            if (data['link'] && data['link']['name']) {
                                globiData.findInteractionTypes(function (linkData) {
                                    me.populateItemData(linkData, data['link']['id'], 'link');
                                });
                            }
                        });
                    }
                });
            }
        }
    },

    populateItemData: function (data, id, type) {
        var me = this;
        switch (type) {
            case 'source':
            case 'target':
                ItemData[type] = {
                    set: true,
                    id: id,
                    label: '',
                    data: fillTemplate(data)
                };
                break;
            case 'link':
                ItemData['link'] = {
                    set: true,
                    id: id,
                    label: '' + camelCaseToRealWords(id) + '',
                    data: ''
                };
                ItemData['source'].label = data[id].source;
                ItemData['target'].label = data[id].target;
                break;
        }
        if (ItemData['source'].set && ItemData['target'].set && ItemData['link'].set) {
            me.searchContext.emit('searchfilter:showitem', ItemData);
            ItemData = { source: {set: false}, target: {set: false}, link: {set: false} };
        }
    },

    /**
     * EVENT HANDLER
     */

    taxonSelected: function (event) {
        this.searchContext.updateSearchParameter(event['emitter'] + 'Taxon', event['data']);
    },

    typeSelected: function (event) {
        this.searchContext.updateSearchParameter('interactionType', event['data']);
    }

});

/**
 * @param elementName
 * @param id
 * @param classes
 * @returns {Element}
 */
function createElement(elementName, id, classes) {
    elementName = elementName || 'div';
    id = id || false;
    classes = classes || [];

    var div = document.createElement(elementName);
    if (id) div.id = id;
    if (classes.length > 0) div.className = classes.join(' ');
    return div;
}

function camelCaseToRealWords(str) {
    return str.replace(/([A-Z])/g, function ($1) {
        return " " + $1.toLowerCase();
    });
}

function proxy(fn, context) {
    return function () {
        return fn.apply(context, arguments);
    };
}

function processDataForResultList(data) {
    var result = [];
    forEach(data, function (item) {
        if ((item['source_taxon_external_id'] !== 'no:match') && (item['target_taxon_external_id'] !== 'no:match')) {
            result.push({
                source: {
                    id: item['source_taxon_external_id'].replace(':', '-@-'),
                    name: item['source_taxon_name'],
                    path: item['source_taxon_path'] ? item['source_taxon_path'] : ''
                },
                target: {
                    id: item['target_taxon_external_id'].replace(':', '-@-'),
                    name: item['target_taxon_name'],
                    path: item['target_taxon_path'] ? item['target_taxon_path'] : ''
                },
                link: {
                    id: item['interaction_type'],
                    name: camelCaseToRealWords(item['interaction_type'])
                }
            })
        }
    });

    return result;
}

function fillTemplate(data) {
    return globi.getTaxonTemplate(data);
}

function getStyleAttribute(path) {
    return 'style="color: ' + taxaprisma.colorFor(path) + ';"'
}
<commit_msg>add basis of records fields for source and target specimen; related to https://github.com/globalbioticinteractions/globalbioticinteractions/issues/602<commit_after>var jQuery = require('jquery');
var inherits = require('util').inherits;
var EventEmitter = require('events').EventEmitter;
var extend = require('extend');
var forEach = require('foreach');
var globi = require('globi');
var globiData = globi.globiData;
var TypeSelector = require('./lib/TypeSelector.js');
var TaxonSelector = require('./lib/TaxonSelector.js');
var SearchResult = require('./lib/SearchResult.js');
var taxaprisma = require('taxaprisma');

module.exports = Plugin;

inherits(Plugin, EventEmitter);

Plugin.Result = SearchResult;
var ItemData = {
    source: {
        set: false
    },
    target: {
        set: false
    },
    link: {
        set: false
    }
};

var FilterElementContainer = null;

function Plugin(settings) {
    if (!(this instanceof Plugin)) {
        return new Plugin(settings);
    }
    this.settings = extend({
        filterContainer: null,
        resultContainer: null
    }, settings);

    this.searchContext = this.settings.searchContext;
    this.init();
}

extend(Plugin.prototype, {
    init: function () {
        var me = this;
        me.el = null;
        me.sourceSelector = null;
        me.targetSelector = null;
        me.typeSelector = null;
        me.searchResult = null;

        me.buildUi();
        me.events();
    },

    appendTo: function (target) {
        var me = this;
        if (typeof target === 'string') target = document.querySelector(target);

        if (FilterElementContainer === null) {
            FilterElementContainer = target.parentNode;
            target.parentNode.insertBefore(me.filterElement, target);
        }
        this.emit('append', target);
    },

    events: function () {
        var me = this;
        me.searchContext.on('taxonselector:selected', proxy(me.taxonSelected, me));
        me.searchContext.on('typeselector:selected', proxy(me.typeSelected, me));
        me.searchContext.on('searchresult:itemselected', proxy(me.itemSelected, me));
        me.searchContext.on('globisearch:resultsetchanged', proxy(me.showResult, me));

        document.addEventListener("click",function(e) {
            if (e.target && e.target.matches(".scientific-name")) {
                var taxonName = e.target.textContent;
                me.sourceSelector.clear();
                me.sourceSelector.add(taxonName);
                me.targetSelector.clear();
                me.searchContext.update({ sourceTaxon: taxonName, targetTaxon: null });

            }
        });
    },

    showResult: function (data) {
        var me = this;
        var searchHash = {
            includeObservations: true,
            field: ['source_taxon_id', 'source_taxon_name', 'source_taxon_path', 'source_taxon_path_ids'
                , 'source_specimen_life_stage_id', 'source_specimen_life_stage'
                , 'source_specimen_physiological_state_id', 'source_specimen_physiological_state'
                , 'source_specimen_body_part_id', 'source_specimen_body_part'
                , 'source_specimen_sex_id', 'source_specimen_sex'
                , 'source_specimen_basis_of_record'
                , 'interaction_type'
                , 'target_taxon_id', 'target_taxon_name', 'target_taxon_path', 'target_taxon_path_ids'
                , 'target_specimen_life_stage_id',  'target_specimen_life_stage'
                , 'target_specimen_physiological_state_id', 'target_specimen_physiological_state'
                , 'target_specimen_body_part_id', 'target_specimen_body_part'
                , 'target_specimen_sex_id', 'target_specimen_sex'
                , 'target_specimen_basis_of_record'
                , 'latitude', 'longitude'
                , 'study_citation', 'study_url', 'study_source_citation']
        };
        var downloadUrls = ['csv'].map(function(resultType) {
            var searchParams = extend({ limit: 4096 }, me.searchContext.searchParameters, searchHash);
            searchParams.resultType = resultType;
            var link = {};
            link.resultType = resultType;
            link.url = globiData.urlForTaxonInteractionQuery(searchParams);
            return link;
        });
        me.searchContext.emit('searchfilter:showresults', processDataForResultList(data), downloadUrls);
    },

    update: function (data) {
        var me = this;
    },

    buildUi: function () {
        var me = this;
        var table = createElement('table', 'search-row'),
            row = createElement('tr'),
            td;

        me.filterElement = createElement('div', 'search-filter');

        td = createElement('td', 'source-taxon-selector-cell');
        td.appendChild(me.createSourceSelector().el);
        row.appendChild(td);

        td = createElement('td', 'type-selector-cell', ['filter-middle-column']);
        td.appendChild(me.createTypeSelector().el);
        row.appendChild(td);

        td = createElement('td', 'target-taxon-selector-cell');
        td.appendChild(me.createTargetSelector().el);
        row.appendChild(td);

        table.appendChild(row);

        me.filterElement.appendChild(table);

        me.populateTypeSelector();
    },

    createTypeSelector: function () {
        var me = this;
        this.typeSelector = new TypeSelector({
            idPrefix: 'source',
            type: 'interactiontype',
            usePlaceholder: false,
            searchContext: me.searchContext,
            startValue: me.searchContext.searchParameters.interactionType
        });

        this.typeSelector.disable();

        return this.typeSelector;
    },

    createSourceSelector: function () {
        var me = this;
        var taxa = me.searchContext.searchParameters.sourceTaxon || [];
        if (!Array.isArray(taxa)) {
            taxa = [taxa];
        }
        this.sourceSelector = new TaxonSelector({
            idPrefix: 'source',
            type: 'source',
            searchContext: me.searchContext,
            preSelectedTaxa: taxa
        });
        return this.sourceSelector;
    },

    createTargetSelector: function () {
        var me = this;
        var taxa = me.searchContext.searchParameters.targetTaxon || [];
        if (!Array.isArray(taxa)) {
            taxa = [taxa];
        }

        this.targetSelector = new TaxonSelector({
            idPrefix: 'target',
            type: 'target',
            searchContext: me.searchContext,
            preSelectedTaxa: taxa
        });
        return this.targetSelector;
    },

    createSearchResult: function () {
        var me = this;
        this.searchResult = new SearchResult({
            searchContext: me.searchContext
        });

        return this.searchResult;
    },

    populateTypeSelector: function () {
        var me = this;

        globiData.findInteractionTypes(
            [],
            {
                callback: function (data) {
                    forEach(data, function (value, key, object) {
                        me.typeSelector.addOption(camelCaseToRealWords(key), key);
                    });
                    me.typeSelector.enable();
                },
                context: me
            }
        );
    },

    itemSelected: function (data) {
        var me = this;
        if (me.searchContext.isAbleToFetch('GlobiSearch::itemselected')) {
            me.searchContext.lockFetching('GlobiSearch::itemselected');
            if (data['source'] && data['source']['name']) {
                globiData.findTaxonInfo(data['source']['name'], function (sourceData) {
                    extend(sourceData, data['source']);
                    me.populateItemData(sourceData, data['source']['id'], 'source');
                    if (data['target'] && data['target']['name']) {
                        globiData.findTaxonInfo(data['target']['name'], function (targetData) {
                            extend(targetData, data['target']);
                            me.populateItemData(targetData, data['target']['id'], 'target');
                            if (data['link'] && data['link']['name']) {
                                globiData.findInteractionTypes(function (linkData) {
                                    me.populateItemData(linkData, data['link']['id'], 'link');
                                });
                            }
                        });
                    }
                });
            }
        }
    },

    populateItemData: function (data, id, type) {
        var me = this;
        switch (type) {
            case 'source':
            case 'target':
                ItemData[type] = {
                    set: true,
                    id: id,
                    label: '',
                    data: fillTemplate(data)
                };
                break;
            case 'link':
                ItemData['link'] = {
                    set: true,
                    id: id,
                    label: '' + camelCaseToRealWords(id) + '',
                    data: ''
                };
                ItemData['source'].label = data[id].source;
                ItemData['target'].label = data[id].target;
                break;
        }
        if (ItemData['source'].set && ItemData['target'].set && ItemData['link'].set) {
            me.searchContext.emit('searchfilter:showitem', ItemData);
            ItemData = { source: {set: false}, target: {set: false}, link: {set: false} };
        }
    },

    /**
     * EVENT HANDLER
     */

    taxonSelected: function (event) {
        this.searchContext.updateSearchParameter(event['emitter'] + 'Taxon', event['data']);
    },

    typeSelected: function (event) {
        this.searchContext.updateSearchParameter('interactionType', event['data']);
    }

});

/**
 * @param elementName
 * @param id
 * @param classes
 * @returns {Element}
 */
function createElement(elementName, id, classes) {
    elementName = elementName || 'div';
    id = id || false;
    classes = classes || [];

    var div = document.createElement(elementName);
    if (id) div.id = id;
    if (classes.length > 0) div.className = classes.join(' ');
    return div;
}

function camelCaseToRealWords(str) {
    return str.replace(/([A-Z])/g, function ($1) {
        return " " + $1.toLowerCase();
    });
}

function proxy(fn, context) {
    return function () {
        return fn.apply(context, arguments);
    };
}

function processDataForResultList(data) {
    var result = [];
    forEach(data, function (item) {
        if ((item['source_taxon_external_id'] !== 'no:match') && (item['target_taxon_external_id'] !== 'no:match')) {
            result.push({
                source: {
                    id: item['source_taxon_external_id'].replace(':', '-@-'),
                    name: item['source_taxon_name'],
                    path: item['source_taxon_path'] ? item['source_taxon_path'] : ''
                },
                target: {
                    id: item['target_taxon_external_id'].replace(':', '-@-'),
                    name: item['target_taxon_name'],
                    path: item['target_taxon_path'] ? item['target_taxon_path'] : ''
                },
                link: {
                    id: item['interaction_type'],
                    name: camelCaseToRealWords(item['interaction_type'])
                }
            })
        }
    });

    return result;
}

function fillTemplate(data) {
    return globi.getTaxonTemplate(data);
}

function getStyleAttribute(path) {
    return 'style="color: ' + taxaprisma.colorFor(path) + ';"'
}
<|endoftext|>


<commit_before>import React from 'react'
import moment from 'moment'
import {markdown} from 'markdown'
import Person from '../../components/person'
import deindent from 'deindent'

export default Episode

function Episode({episodeData}) {
  const {hangoutUrl, title, date, guests, description} = episodeData
  const time = episodeData.time || '12:00 PM (CT)'
  const dateDisplay = moment(date).format('dddd, MMMM Do, YYYY')
  return (

        {getTitle(hangoutUrl, title)}

        {dateDisplay} at {time}

        {guests.map((guest, index) => (
          <Person imgSrc={`episodes/${date}/${guest.twitter}.png`} key={index} {...guest} />
        ))}

  )
}

function getDescriptionHTML(description) {
  return {__html: markdown.toHTML(deindent(description))}
}

function getTitle(hangoutUrl, title) {
  if (hangoutUrl) {
    return {title}
  } else {
    return {title} (hangout url coming soon)
  }
}

<commit_msg>url --> link<commit_after>import React from 'react'
import moment from 'moment'
import {markdown} from 'markdown'
import Person from '../../components/person'
import deindent from 'deindent'

export default Episode

function Episode({episodeData}) {
  const {hangoutUrl, title, date, guests, description} = episodeData
  const time = episodeData.time || '12:00 PM (CT)'
  const dateDisplay = moment(date).format('dddd, MMMM Do, YYYY')
  return (

        {getTitle(hangoutUrl, title)}

        {dateDisplay} at {time}

        {guests.map((guest, index) => (
          <Person imgSrc={`episodes/${date}/${guest.twitter}.png`} key={index} {...guest} />
        ))}

  )
}

function getDescriptionHTML(description) {
  return {__html: markdown.toHTML(deindent(description))}
}

function getTitle(hangoutUrl, title) {
  if (hangoutUrl) {
    return {title}
  } else {
    return {title} (hangout link coming soon)
  }
}

<|endoftext|>


<commit_before>window.multigraph.util.namespace("window.multigraph.parser.jquery", function (ns) {
    "use strict";

    ns.mixin.add(function (ns, parse) {

        var parseLabels = function (xml, axis) {
            var spacingStrings = [],
                spacingString,
                labelsTag = xml.find("labels"),
                labelers  = axis.labelers(),
                Labeler   = ns.core.Labeler,
                $         = ns.jQuery,
                i;
            spacingString = $.trim(labelsTag.attr("spacing"));
            if (spacingString !== "") {
                spacingStrings = spacingString.split(/\s+/);
            }
            if (spacingStrings.length > 0) {
                // If there was a spacing attr on the <labels> tag, create a new labeler for
                // each spacing present in it, using the other values from the <labels> tag
                for (i = 0; i < spacingStrings.length; ++i) {
                    labelers.add(Labeler[parse](labelsTag, axis, undefined, spacingStrings[i]));
                }
            } else {
                // Otherwise, parse the <labels> tag to get default values
                var defaults = Labeler[parse](labelsTag, axis, undefined, null);
                // And loop over each <label> tag, creating labelers for each, splitting multiple
                // spacings on the same <label> tag into multiple labelers:
                $.each(xml.find("label"), function (j, e) {
                    spacingString = $.trim($(e).attr("spacing"));
                    spacingStrings = [];
                    if (spacingString !== "") {
                        spacingStrings = spacingString.split(/\s+/);
                    }
                    for (i = 0; i < spacingStrings.length; ++i) {
                        labelers.add( Labeler[parse]($(e), axis, defaults, spacingStrings[i]) );
                    }
                });
            }
        };

        ns.core.Axis[parse] = function (xml, orientation, messageHandler, multigraph) {

            var core = ns.core,
                axis = new core.Axis(orientation),
                DataValue    = core.DataValue,
                Displacement = ns.math.Displacement,
                Point        = ns.math.Point,
                RGBColor     = ns.math.RGBColor,
                attr, child,
                value;

            if (xml) {

                attr = xml.attr("id");
                if (attr !== undefined) {
                    axis.id(attr);
                }
                attr = xml.attr("type");
                if (attr !== undefined) {
                    axis.type(DataValue.parseType(attr));
                }
                attr = xml.attr("length");
                if (attr !== undefined) {
                    axis.length(Displacement.parse(attr));
                }

                //
                // The following provides support for the deprecated "positionbase" axis attribute;
                // MUGL files should use the "base" attribute instead.  When we're ready to remove
                // support for the deprecated attribute, delete this block of code:
                //
                (function () {
                    var positionbase = xml.attr("positionbase");
                    if (positionbase) {
                        messageHandler.warning('Use of deprecated axis attribute "positionbase"; use "base" attribute instead');
                        if ((positionbase === "left") || (positionbase === "bottom")) {
                            axis.base(Point.parse("-1 -1"));
                        } else if (positionbase === "right") {
                            axis.base(Point.parse("1 -1"));
                        } else if (positionbase === "top") {
                            axis.base(Point.parse("-1 1"));
                        }
                    }
                }());
                //
                // End of code to delete when removing support for deprecated "positionbase"
                // attribute.
                //

                attr = xml.attr("position");
                if (attr !== undefined) {
                    try {
                        axis.position(Point.parse(attr));
                    } catch (e) {
                        // If position did not parse as a Point, and if it can be interpreted
                        // as a number, construct the position point by interpreting that
                        // number as an offset from the 0 location along the perpendicular
                        // direction.
                        value = parseInt(attr, 10);
                        if (value !== value) { // test for isNaN
                            throw e;
                        }
                        if (orientation === core.Axis.HORIZONTAL) {
                            axis.position(new Point(0, value));
                        } else {
                            axis.position(new Point(value, 0));
                        }
                    }
                }
                attr = xml.attr("pregap");
                if (attr !== undefined) {
                    axis.pregap(parseFloat(attr));
                }
                attr = xml.attr("postgap");
                if (attr !== undefined) {
                    axis.postgap(parseFloat(attr));
                }
                attr = xml.attr("anchor");
                if (attr  !== undefined) {
                    axis.anchor(parseFloat(attr));
                }
                attr = xml.attr("base");
                if (attr  !== undefined) {
                    axis.base(Point.parse(attr));
                }
                attr = xml.attr("minposition");
                if (attr !== undefined) {
                    axis.minposition(Displacement.parse(attr));
                }
                attr = xml.attr("maxposition");
                if (attr !== undefined) {
                    axis.maxposition(Displacement.parse(attr));
                }
                axis.min(xml.attr("min"));
                if (axis.min() !== "auto") {
                    axis.dataMin(DataValue.parse(axis.type(), axis.min()));
                }
                attr = xml.attr("minoffset");
                if (attr !== undefined) {
                    axis.minoffset(parseFloat(attr));
                }
                axis.max(xml.attr("max"));
                if (axis.max() !== "auto") {
                    axis.dataMax(DataValue.parse(axis.type(), axis.max()));
                }
                attr = xml.attr("maxoffset");
                if (attr !== undefined) {
                    axis.maxoffset(parseFloat(attr));
                }
                attr = xml.attr("color");
                if (attr !== undefined) {
                    axis.color(RGBColor.parse(attr));
                }
                attr = xml.attr("tickcolor");
                if (attr !== undefined) {
                    axis.tickcolor(RGBColor.parse(attr));
                }
                attr = xml.attr("tickmin");
                if (attr !== undefined) {
                    axis.tickmin(parseInt(attr, 10));
                }
                attr = xml.attr("tickmax");
                if (attr !== undefined) {
                    axis.tickmax(parseInt(attr, 10));
                }
                attr = xml.attr("highlightstyle");
                if (attr !== undefined) {
                    axis.highlightstyle(attr);
                }
                attr = xml.attr("linewidth");
                if (attr !== undefined) {
                    axis.linewidth(parseInt(attr, 10));
                }

                child = xml.find("title");
                if (child.length > 0)                    { axis.title(core.AxisTitle[parse](child, axis));     }
                else                                     { axis.title(new core.AxisTitle(axis));               }

                child = xml.find("grid");
                if (child.length > 0)                    { axis.grid(core.Grid[parse](child));                 }
                child = xml.find("pan");
                if (child.length > 0)                    { axis.pan(core.Pan[parse](child, axis.type()));      }
                child = xml.find("zoom");
                if (child.length > 0)                    { axis.zoom(core.Zoom[parse](child, axis.type()));    }
                if (xml.find("labels").length > 0)       { parseLabels(xml, axis);                             }

                child = xml.find("binding");
                if (child.length > 0) {
                    var bindingIdAttr  = child.attr("id"),
                        bindingMinAttr = child.attr("min"),
                        bindingMaxAttr = child.attr("max"),
                        bindingMinDataValue = DataValue.parse(axis.type(), bindingMinAttr),
                        bindingMaxDataValue = DataValue.parse(axis.type(), bindingMaxAttr);
                    if (typeof(bindingIdAttr) !== "string" || bindingIdAttr.length <= 0) {
                        throw new Error("invalid axis binding id: '" + bindingIdAttr + "'");
                    }
                    if (! DataValue.isInstance(bindingMinDataValue)) {
                        throw new Error("invalid axis binding min: '" + bindingMinAttr + "'");
                    }
                    if (! DataValue.isInstance(bindingMaxDataValue)) {
                        throw new Error("invalid axis binding max: '" + bindingMaxAttr + "'");
                    }
                    core.AxisBinding.findByIdOrCreateNew(bindingIdAttr).addAxis(axis, bindingMinDataValue, bindingMaxDataValue, multigraph);
                }

            }
            return axis;
        };

    });

});
<commit_msg>parser correctly handles labels tags without spacing strings<commit_after>window.multigraph.util.namespace("window.multigraph.parser.jquery", function (ns) {
    "use strict";

    ns.mixin.add(function (ns, parse) {

        var parseLabels = function (xml, axis) {
            var spacingStrings = [],
                spacingString,
                labelsTag = xml.find("labels"),
                labelTags = xml.find("label"),
                labelers  = axis.labelers(),
                Labeler   = ns.core.Labeler,
                $         = ns.jQuery,
                i;
            spacingString = $.trim(labelsTag.attr("spacing"));
            if (spacingString !== "") {
                spacingStrings = spacingString.split(/\s+/);
            }
            if (spacingStrings.length > 0) {
                // If there was a spacing attr on the <labels> tag, create a new labeler for
                // each spacing present in it, using the other values from the <labels> tag
                for (i = 0; i < spacingStrings.length; ++i) {
                    labelers.add(Labeler[parse](labelsTag, axis, undefined, spacingStrings[i]));
                }
            } else if (labelTags.length > 0) {
                // If there are <label> tags, parse the <labels> tag to get default values
                var defaults = Labeler[parse](labelsTag, axis, undefined, null);
                // And loop over each <label> tag, creating labelers for each, splitting multiple
                // spacings on the same <label> tag into multiple labelers:
                $.each(labelTags, function (j, e) {
                    spacingString = $.trim($(e).attr("spacing"));
                    spacingStrings = [];
                    if (spacingString !== "") {
                        spacingStrings = spacingString.split(/\s+/);
                    }
                    for (i = 0; i < spacingStrings.length; ++i) {
                        labelers.add( Labeler[parse]($(e), axis, defaults, spacingStrings[i]) );
                    }
                });
            } else {
                // Otherwise create labelers using the default spacing, with the other values
                // from the <labels> tag
                var defaultValues = (ns.utilityFunctions.getDefaultValuesFromXSD()).horizontalaxis.labels;
                spacingString = axis.type() === ns.core.DataValue.NUMBER ?
                    defaultValues.defaultNumberSpacing :
                    defaultValues.defaultDatetimeSpacing;
                spacingStrings = spacingString.split(/\s+/);
                for (i = 0; i < spacingStrings.length; ++i) {
                    labelers.add(Labeler[parse](labelsTag, axis, undefined, spacingStrings[i]));
                }
            }
        };

        ns.core.Axis[parse] = function (xml, orientation, messageHandler, multigraph) {

            var core = ns.core,
                axis = new core.Axis(orientation),
                DataValue    = core.DataValue,
                Displacement = ns.math.Displacement,
                Point        = ns.math.Point,
                RGBColor     = ns.math.RGBColor,
                attr, child,
                value;

            if (xml) {

                attr = xml.attr("id");
                if (attr !== undefined) {
                    axis.id(attr);
                }
                attr = xml.attr("type");
                if (attr !== undefined) {
                    axis.type(DataValue.parseType(attr));
                }
                attr = xml.attr("length");
                if (attr !== undefined) {
                    axis.length(Displacement.parse(attr));
                }

                //
                // The following provides support for the deprecated "positionbase" axis attribute;
                // MUGL files should use the "base" attribute instead.  When we're ready to remove
                // support for the deprecated attribute, delete this block of code:
                //
                (function () {
                    var positionbase = xml.attr("positionbase");
                    if (positionbase) {
                        messageHandler.warning('Use of deprecated axis attribute "positionbase"; use "base" attribute instead');
                        if ((positionbase === "left") || (positionbase === "bottom")) {
                            axis.base(Point.parse("-1 -1"));
                        } else if (positionbase === "right") {
                            axis.base(Point.parse("1 -1"));
                        } else if (positionbase === "top") {
                            axis.base(Point.parse("-1 1"));
                        }
                    }
                }());
                //
                // End of code to delete when removing support for deprecated "positionbase"
                // attribute.
                //

                attr = xml.attr("position");
                if (attr !== undefined) {
                    try {
                        axis.position(Point.parse(attr));
                    } catch (e) {
                        // If position did not parse as a Point, and if it can be interpreted
                        // as a number, construct the position point by interpreting that
                        // number as an offset from the 0 location along the perpendicular
                        // direction.
                        value = parseInt(attr, 10);
                        if (value !== value) { // test for isNaN
                            throw e;
                        }
                        if (orientation === core.Axis.HORIZONTAL) {
                            axis.position(new Point(0, value));
                        } else {
                            axis.position(new Point(value, 0));
                        }
                    }
                }
                attr = xml.attr("pregap");
                if (attr !== undefined) {
                    axis.pregap(parseFloat(attr));
                }
                attr = xml.attr("postgap");
                if (attr !== undefined) {
                    axis.postgap(parseFloat(attr));
                }
                attr = xml.attr("anchor");
                if (attr  !== undefined) {
                    axis.anchor(parseFloat(attr));
                }
                attr = xml.attr("base");
                if (attr  !== undefined) {
                    axis.base(Point.parse(attr));
                }
                attr = xml.attr("minposition");
                if (attr !== undefined) {
                    axis.minposition(Displacement.parse(attr));
                }
                attr = xml.attr("maxposition");
                if (attr !== undefined) {
                    axis.maxposition(Displacement.parse(attr));
                }
                axis.min(xml.attr("min"));
                if (axis.min() !== "auto") {
                    axis.dataMin(DataValue.parse(axis.type(), axis.min()));
                }
                attr = xml.attr("minoffset");
                if (attr !== undefined) {
                    axis.minoffset(parseFloat(attr));
                }
                axis.max(xml.attr("max"));
                if (axis.max() !== "auto") {
                    axis.dataMax(DataValue.parse(axis.type(), axis.max()));
                }
                attr = xml.attr("maxoffset");
                if (attr !== undefined) {
                    axis.maxoffset(parseFloat(attr));
                }
                attr = xml.attr("color");
                if (attr !== undefined) {
                    axis.color(RGBColor.parse(attr));
                }
                attr = xml.attr("tickcolor");
                if (attr !== undefined) {
                    axis.tickcolor(RGBColor.parse(attr));
                }
                attr = xml.attr("tickmin");
                if (attr !== undefined) {
                    axis.tickmin(parseInt(attr, 10));
                }
                attr = xml.attr("tickmax");
                if (attr !== undefined) {
                    axis.tickmax(parseInt(attr, 10));
                }
                attr = xml.attr("highlightstyle");
                if (attr !== undefined) {
                    axis.highlightstyle(attr);
                }
                attr = xml.attr("linewidth");
                if (attr !== undefined) {
                    axis.linewidth(parseInt(attr, 10));
                }

                child = xml.find("title");
                if (child.length > 0)                    { axis.title(core.AxisTitle[parse](child, axis));     }
                else                                     { axis.title(new core.AxisTitle(axis));               }

                child = xml.find("grid");
                if (child.length > 0)                    { axis.grid(core.Grid[parse](child));                 }
                child = xml.find("pan");
                if (child.length > 0)                    { axis.pan(core.Pan[parse](child, axis.type()));      }
                child = xml.find("zoom");
                if (child.length > 0)                    { axis.zoom(core.Zoom[parse](child, axis.type()));    }
                if (xml.find("labels").length > 0)       { parseLabels(xml, axis);                             }

                child = xml.find("binding");
                if (child.length > 0) {
                    var bindingIdAttr  = child.attr("id"),
                        bindingMinAttr = child.attr("min"),
                        bindingMaxAttr = child.attr("max"),
                        bindingMinDataValue = DataValue.parse(axis.type(), bindingMinAttr),
                        bindingMaxDataValue = DataValue.parse(axis.type(), bindingMaxAttr);
                    if (typeof(bindingIdAttr) !== "string" || bindingIdAttr.length <= 0) {
                        throw new Error("invalid axis binding id: '" + bindingIdAttr + "'");
                    }
                    if (! DataValue.isInstance(bindingMinDataValue)) {
                        throw new Error("invalid axis binding min: '" + bindingMinAttr + "'");
                    }
                    if (! DataValue.isInstance(bindingMaxDataValue)) {
                        throw new Error("invalid axis binding max: '" + bindingMaxAttr + "'");
                    }
                    core.AxisBinding.findByIdOrCreateNew(bindingIdAttr).addAxis(axis, bindingMinDataValue, bindingMaxDataValue, multigraph);
                }

            }
            return axis;
        };

    });

});
<|endoftext|>