<commit_before>'use strict';

/**
 * Returns `Set` class with custom equality comparisons.
 *
 * @param {function} hashFn — the function to determine the unique of value.
 * @returns {HashSet}
 */
module.exports = function hashSet(hashFn) {
    if (!hashFn) {
        throw new Error('You should specify hash function to create HashSet.');
    }

    /**
     * Set objects are collections of values, you can iterate its elements in insertion order.
     *
     * A value in the Set may only occur once; it is unique in the Set's collection.
     */
    return class HashSet {
        /**
         * The value of the length property is 0.
         */
        static get length() {
            return 0;
        }
        /**
         * Returns the function that created an instance's prototype.
         *
         * @param iterable If an iterable object is passed, all of its elements will be added to the new Set.
         *                 null is treated as undefined.
         * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of}
         */
        constructor(iterable) {
            this._map = new Map();

            if (iterable) {
                for (let item of iterable) {
                    this.add(item);
                }
            }
        }
        /**
         * The value of size is an integer representing how many entries the Set object has.
         * A set accessor function for size is undefined; you can not change this property.
         *
         * @returns the number of elements in a Set object.
         */
        get size() {
            return this._map.size;
        }
        /**
         * Appends a new element with the given value to the Set object.
         *
         * @param {*} value — the value of the element to add to the Set object.
         * @returns {HashSet}.
         */
        add(value) {
            const id = hashFn(value);

            if (!this._map.has(id)) {
                this._map.set(id, value);
            }

            return this;
        }
        /**
         * Returns a boolean asserting whether an element is present with the given value in the Set object or not.
         *
         * @param {*} value — the value to test for presence in the Set object.
         * @returns {boolean} Returns true if an element with the specified value exists in the Set object;
         *                    otherwise false.
         */
        has(value) {
            const id = hashFn(value);

            return this._map.has(id);
        }
        /**
         * Removes the element associated to the value and returns the value that.
         *
         * `Set.prototype.has(value)` would have previously returned.
         * `Set.prototype.has(value)` will return false afterwards.
         *
         * @param {*} value — the value of the element to remove from the Set object.
         * @returns {boolean} Returns true if an element in the Set object has been removed successfully;
         *                    otherwise false.
         */
        delete(obj) {
            const id = hashFn(obj);

            return this._map.delete(id);
        }
        /**
         * Removes all elements from the Set object.
         */
        clear() {
            this._map.clear();
        }
        /**
         * Returns a new Iterator object that contains an array of [value, value] for each element in the Set object,
         * in insertion order.
         *
         * This is kept similar to the Map object, so that each entry has the same value for its key and value here.
         *
         * @returns {Iterator}
         */
        entries() {
            return this._map.values();
        }
        /**
         * Executes a provided function once per each value in the Set object, in insertion order.
         *
         * It is not invoked for values which have been deleted. However, it is executed for values which are present
         * but have the value undefined.
         *
         * Callback is invoked with three arguments:
         *   * the element value
         *   * the element value
         *   * the Set object being traversed
         *
         * @param {function} callbackFn — function to execute for each element.
         * @param {object} thisArg — value to use as this when executing callback. If a thisArg parameter is provided
         *                           to forEach, it will be used as the this value for each callback.
         */
        forEach(callbackFn, thisArg) {
            this._map.forEach(function(value) {
                callbackFn(value, value, this);
            }, thisArg);
        }
        /**
         * Returns a new Iterator object that contains the values for each element in the Set object in insertion order.
         *
         * Is the same function as the values() function.
         *
         * @returns {Iterator}
         */
        values() {
            return this._map.values();
        }
        /**
         * Returns a new Iterator object that contains the values for each element in the Set object in insertion order.
         *
         * Is the same function as the values() function.
         *
         * @returns {Iterator}
         */
        keys() {
            return this._map.values();
        }
        /**
         * The initial value of the @@iterator property is the same function object as the initial
         * value of the values property.
         *
         * Is the same function as the values() function.
         *
         * @returns {Iterator}
         */
        [Symbol.iterator]() {
            return this._map.values();
        }
        /**
         * Returns Set object is equivalent to this HashSet object.
         *
         * @returns {Set}
         */
        valueOf() {
            return new Set(this._map.values());
        }
        /**
         * Returns a string representing object.
         *
         * @returns {string}
         */
        toString() {
            return '[object Set]';
        }
    };
}
<commit_msg>docs(jsdoc): fix jsdoc<commit_after>'use strict';

/**
 * Returns `Set` class with custom equality comparisons.
 *
 * @param {function} hashFn — the function to determine the unique of value.
 * @returns {HashSet}
 */
module.exports = function hashSet(hashFn) {
    if (!hashFn) {
        throw new Error('You should specify hash function to create HashSet.');
    }

    /**
     * Set objects are collections of values, you can iterate its elements in insertion order.
     *
     * A value in the Set may only occur once; it is unique in the Set's collection.
     */
    return class HashSet {
        /**
         * The value of the length property is 0.
         */
        static get length() {
            return 0;
        }
        /**
         * Returns the function that created an instance's prototype.
         *
         * @param {Iterable} iterable — if an iterable object is passed, then all of its elements
         *                              will be added to the new Set. `null` is treated as undefined.
         * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of}
         */
        constructor(iterable) {
            this._map = new Map();

            if (iterable) {
                for (let item of iterable) {
                    this.add(item);
                }
            }
        }
        /**
         * The value of size is an integer representing how many entries the Set object has.
         * A set accessor function for size is undefined; you can not change this property.
         *
         * @returns {number} the number of elements in a Set object.
         */
        get size() {
            return this._map.size;
        }
        /**
         * Appends a new element with the given value to the Set object.
         *
         * @param {*} value — the value of the element to add to the Set object.
         * @returns {HashSet}.
         */
        add(value) {
            const id = hashFn(value);

            if (!this._map.has(id)) {
                this._map.set(id, value);
            }

            return this;
        }
        /**
         * Returns a boolean asserting whether an element is present with the given value in the Set object or not.
         *
         * @param {*} value — the value to test for presence in the Set object.
         * @returns {boolean} Returns true if an element with the specified value exists in the Set object;
         *                    otherwise false.
         */
        has(value) {
            const id = hashFn(value);

            return this._map.has(id);
        }
        /**
         * Removes the element associated to the value and returns the value that.
         *
         * `Set.prototype.has(value)` would have previously returned.
         * `Set.prototype.has(value)` will return false afterwards.
         *
         * @param {*} value — the value of the element to remove from the Set object.
         * @returns {boolean} Returns true if an element in the Set object has been removed successfully;
         *                    otherwise false.
         */
        delete(value) {
            const id = hashFn(value);

            return this._map.delete(id);
        }
        /**
         * Removes all elements from the Set object.
         */
        clear() {
            this._map.clear();
        }
        /**
         * Returns a new Iterator object that contains an array of [value, value] for each element in the Set object,
         * in insertion order.
         *
         * This is kept similar to the Map object, so that each entry has the same value for its key and value here.
         *
         * @returns {Iterator}
         */
        entries() {
            return this._map.values();
        }
        /**
         * Executes a provided function once per each value in the Set object, in insertion order.
         *
         * It is not invoked for values which have been deleted. However, it is executed for values which are present
         * but have the value undefined.
         *
         * Callback is invoked with three arguments:
         *   * the element value
         *   * the element value
         *   * the Set object being traversed
         *
         * @param {function} callbackFn — function to execute for each element.
         * @param {object} thisArg — value to use as this when executing callback. If a thisArg parameter is provided
         *                           to forEach, it will be used as the this value for each callback.
         */
        forEach(callbackFn, thisArg) {
            this._map.forEach(function(value) {
                callbackFn(value, value, this);
            }, thisArg);
        }
        /**
         * Returns a new Iterator object that contains the values for each element in the Set object in insertion order.
         *
         * Is the same function as the values() function.
         *
         * @returns {Iterator}
         */
        values() {
            return this._map.values();
        }
        /**
         * Returns a new Iterator object that contains the values for each element in the Set object in insertion order.
         *
         * Is the same function as the values() function.
         *
         * @returns {Iterator}
         */
        keys() {
            return this._map.values();
        }
        /**
         * The initial value of the @@iterator property is the same function object as the initial
         * value of the values property.
         *
         * Is the same function as the values() function.
         *
         * @returns {Iterator}
         */
        [Symbol.iterator]() {
            return this._map.values();
        }
        /**
         * Returns Set object is equivalent to this HashSet object.
         *
         * @returns {Set}
         */
        valueOf() {
            return new Set(this._map.values());
        }
        /**
         * Returns a string representing object.
         *
         * @returns {string}
         */
        toString() {
            return '[object Set]';
        }
    };
}
<|endoftext|>


<commit_before>var λ = {};

/**
	λx.x
*/
λ.id = function id(x){
	return x;
};

/**
	λs.(s s)
*/
λ.applySelf = function applySelf(fn){
	return fn(fn);
};

/**
	λfn.λarg.(fn arg)
*/
λ.apply = function apply(fn){
	return function __apply__(arg){
		return fn.call(null, arg);
	};
};

/**
	λx.λy.x
*/
λ.first = function first(optA){
	return function __first__(optB){
		return optA
	}
}

/**
	λx.λy.y
*/
λ.second = function second(optA){
	return λ.id;
}

module.exports = λ;<commit_msg>damn tabs<commit_after>var λ = {};

/**
    λx.x
*/
λ.id = function id(x){
    return x;
};

/**
    λs.(s s)
*/
λ.applySelf = function applySelf(fn){
    return fn(fn);
};

/**
    λfn.λarg.(fn arg)
*/
λ.apply = function apply(fn){
    return function __apply__(arg){
        return fn.call(null, arg);
    };
};

/**
    λx.λy.x
*/
λ.first = function first(optA){
    return function __first__(optB){
        return optA
    }
}

/**
    λx.λy.y
*/
λ.second = function second(optA){
    return λ.id;
}

module.exports = λ;<|endoftext|>


<commit_before>// var Repo = require('git-tools');
// var repo = new Repo('./');

var repo = require('simple-git')('./');
var JsDiff = require('diff');
// var fs = require('fs');

module.exports = function () {

  // repo.authors(function (error, authors) {
  //   console.log(authors);
  // });
  var options = { file: 'index.js' };
  repo.log(options, (err, log) => {
    if (err) {
      throw new Error(err);
    }

    var allLogs = log.all.reverse();
    // var revisions = log.all.length;
    repo.show(`${allLogs[0].hash} ${options.file}`, function (err, show1) {
      if (err) {
        throw new Error(err);
      }
      // console.log('!!!!');
      // console.log('show1', show1);

      repo.show(`${allLogs[1].hash} ${options.file}`, function (err, show2) {
        if (err) {
          throw new Error(err);
        }

        console.log('creating patch');
        var patch = JsDiff.createPatch('index.js', show1, show2);
        console.log(patch);
      });
    });

    // repo.diff(`${allLogs[0].hash} ${allLogs[1].hash} -- ${options.file}`, (err, diff) => {
    //   if (err) {
    //     throw new Error(err);
    //   }
    //   console.log(diff);
    // });

    // allLogs.reverse().map( (log, i) => {
    //   if (i < allLogs.length - 1 ) {
    //     repo.diff(`${log.hash} ${allLogs[i + 1].hash} -- ${options.file}`, (err, diff) => {
    //       if (err) {
    //         throw new Error(err);
    //       }
    //       console.log(diff);
    //     });
    //   }
    // });

  });
};
<commit_msg>Removed old index.js.<commit_after><|endoftext|>


<commit_before>/*!
 * helper-link-to <https://github.com/helpers/helper-link-to>
 *
 * Copyright (c) 2016, Brian Woodward.
 * Licensed under the MIT License.
 */

'use strict';

module.exports = function () {
  // do stuff
};
<commit_msg>implementation<commit_after>/*!
 * helper-link-to <https://github.com/helpers/helper-link-to>
 *
 * Copyright (c) 2016, Brian Woodward.
 * Licensed under the MIT License.
 */

'use strict';

var relativePath = require('relative-dest');

module.exports = function linkTo(key, collectionName) {
  var name = collectionName;
  if (typeof name === 'object') {
    name = null;
  }

  name = name || 'pages';

  if (!this || typeof this.app === 'undefined') {
    var msg = 'helper-link-to requires that it is used in an `app` created with `templates`.';
    console.error(msg);
    return '';
  }

  var collection = this.app[name];
  if (typeof collection === 'undefined') {
    var msg = 'Invalid collection `' + name + '`.';
    console.error(msg);
    return '';
  }

  var current = this.context.view;
  var target = collection.getView(key);

  if (!target || !Object.keys(target).length) {
    var msg = 'Unable target find `' + key + '` in `' + name + '`.';
    console.error(msg);
    return '';
  }

  var fromDest = current.dest || current.path;
  var targetDest = target.dest || target.path;
  return relativePath(fromDest, targetDest);
};
<|endoftext|>


<commit_before>import React from 'react-native';
const {
  PixelRatio,
  StatusBar,
  Component,
  Text,
  View,
  PropTypes,
  Platform
} = React;
import NavbarButton from './NavbarButton';
import styles from './styles';

const ButtonShape = {
  title: PropTypes.string.isRequired,
  style: PropTypes.any,
  handler: PropTypes.func,
};

const TitleShape = {
  title: PropTypes.string.isRequired,
  tintColor: PropTypes.string,
};

const StatusBarShape = {
  style: PropTypes.oneOf(['light-content', 'default', ]),
  hidden: PropTypes.bool,
  tintColor: PropTypes.string,
  hideAnimation: PropTypes.oneOf(['fade', 'slide', 'none', ]),
  showAnimation: PropTypes.oneOf(['fade', 'slide', 'none', ])
};

function customizeStatusBar(data) {
  if (Platform.OS === 'ios') {
    if (data.style) {
      StatusBar.setBarStyle(data.style, true);
    }
    const animation = data.hidden ?
    (data.hideAnimation || NavigationBar.defaultProps.statusBar.hideAnimation) :
    (data.showAnimation || NavigationBar.defaultProps.statusBar.showAnimation);

    StatusBar.setHidden(data.hidden, animation);
  }
}

class NavigationBar extends Component {
  componentDidMount() {
    customizeStatusBar(this.props.statusBar);
  }

  componentWillReceiveProps(props) {
    customizeStatusBar(this.props.statusBar);
  }

  getButtonElement(data = {}, style) {
    if (!!data.props) {
      return <View style={styles.navBarButton}>{data}</View>;
    }

    return <NavbarButton
      title={data.title}
      style={[data.style, style, ]}
      tintColor={data.tintColor}
      handler={data.handler} />;
  }

  getTitleElement(data) {
    if (!!data.props) {
      return <View style={styles.customTitle}>{data}</View>;
    }

    const colorStyle = data.tintColor ? { color: data.tintColor, } : null;

    return (
      <Text
        style={[styles.navBarTitleText, colorStyle, ]}>
        {data.title}
      </Text>
    );
  }

  render() {
    const customTintColor = this.props.tintColor ?
      { backgroundColor: this.props.tintColor } : null;

    const customStatusBarTintColor = this.props.statusBar.tintColor ?
      { backgroundColor: this.props.statusBar.tintColor } : null;

    const statusBar = !this.props.statusBar.hidden ?
      <View style={[styles.statusBar, customStatusBarTintColor ]} /> : null;

    return (
      <View style={[styles.navBarContainer, customTintColor, ]}>
        {statusBar}
        <View style={[styles.navBar, this.props.style, ]}>
          {this.getTitleElement(this.props.title)}
          {this.getButtonElement(this.props.leftButton, { marginLeft: 8, })}
          {this.getButtonElement(this.props.rightButton, { marginRight: 8, })}
        </View>
      </View>
    );
  }

  static propTypes = {
    tintColor: PropTypes.string,
    statusBar: PropTypes.shape(StatusBarShape),
    leftButton: PropTypes.oneOfType([
      PropTypes.shape(ButtonShape),
      PropTypes.element,
    ]),
    rightButton: PropTypes.oneOfType([
      PropTypes.shape(ButtonShape),
      PropTypes.element,
    ]),
    title: PropTypes.oneOfType([
      PropTypes.shape(TitleShape),
      PropTypes.element,
    ]),
  };

  static defaultProps = {
    statusBar: {
      style: 'default',
      hidden: false,
      hideAnimation: 'slide',
      showAnimation: 'slide',
    },
    title: {
      title: '',
    },
  };
}
module.exports = NavigationBar;
<commit_msg>Adjust rest props to new StatusBar signature<commit_after>import React from 'react-native';
const {
  PixelRatio,
  StatusBar,
  Component,
  Text,
  View,
  PropTypes,
  Platform
} = React;
import NavbarButton from './NavbarButton';
import styles from './styles';

const ButtonShape = {
  title: PropTypes.string.isRequired,
  style: PropTypes.any,
  handler: PropTypes.func,
};

const TitleShape = {
  title: PropTypes.string.isRequired,
  tintColor: PropTypes.string,
};

const StatusBarShape = {
  style: PropTypes.oneOf(['light-content', 'default', ]),
  hidden: PropTypes.bool,
  tintColor: PropTypes.string,
  hideAnimation: PropTypes.oneOf(['fade', 'slide', 'none', ]),
  showAnimation: PropTypes.oneOf(['fade', 'slide', 'none', ])
};

function customizeStatusBar(data) {
  if (Platform.OS === 'ios') {
    if (data.style) {
      StatusBar.barStyle(data.style, true);
    }
    const animation = data.hidden ?
    (data.hideAnimation || NavigationBar.defaultProps.statusBar.hideAnimation) :
    (data.showAnimation || NavigationBar.defaultProps.statusBar.showAnimation);

    StatusBar.showHideTransition(animation);
    StatusBar.hidden = data.hidden;
  }
}

class NavigationBar extends Component {
  componentDidMount() {
    customizeStatusBar(this.props.statusBar);
  }

  componentWillReceiveProps(props) {
    customizeStatusBar(this.props.statusBar);
  }

  getButtonElement(data = {}, style) {
    if (!!data.props) {
      return <View style={styles.navBarButton}>{data}</View>;
    }

    return <NavbarButton
      title={data.title}
      style={[data.style, style, ]}
      tintColor={data.tintColor}
      handler={data.handler} />;
  }

  getTitleElement(data) {
    if (!!data.props) {
      return <View style={styles.customTitle}>{data}</View>;
    }

    const colorStyle = data.tintColor ? { color: data.tintColor, } : null;

    return (
      <Text
        style={[styles.navBarTitleText, colorStyle, ]}>
        {data.title}
      </Text>
    );
  }

  render() {
    const customTintColor = this.props.tintColor ?
      { backgroundColor: this.props.tintColor } : null;

    const customStatusBarTintColor = this.props.statusBar.tintColor ?
      { backgroundColor: this.props.statusBar.tintColor } : null;

    const statusBar = !this.props.statusBar.hidden ?
      <View style={[styles.statusBar, customStatusBarTintColor ]} /> : null;

    return (
      <View style={[styles.navBarContainer, customTintColor, ]}>
        {statusBar}
        <View style={[styles.navBar, this.props.style, ]}>
          {this.getTitleElement(this.props.title)}
          {this.getButtonElement(this.props.leftButton, { marginLeft: 8, })}
          {this.getButtonElement(this.props.rightButton, { marginRight: 8, })}
        </View>
      </View>
    );
  }

  static propTypes = {
    tintColor: PropTypes.string,
    statusBar: PropTypes.shape(StatusBarShape),
    leftButton: PropTypes.oneOfType([
      PropTypes.shape(ButtonShape),
      PropTypes.element,
    ]),
    rightButton: PropTypes.oneOfType([
      PropTypes.shape(ButtonShape),
      PropTypes.element,
    ]),
    title: PropTypes.oneOfType([
      PropTypes.shape(TitleShape),
      PropTypes.element,
    ]),
  };

  static defaultProps = {
    statusBar: {
      style: 'default',
      hidden: false,
      hideAnimation: 'slide',
      showAnimation: 'slide',
    },
    title: {
      title: '',
    },
  };
}
module.exports = NavigationBar;
<|endoftext|>


<commit_before>#!/usr/bin/env node

global.Snakeskin = require('./snakeskin');

var program = require('commander');
var beautify = require('js-beautify');

var path = require('path');
var fs = require('fs'),
	exists = fs.existsSync || path.existsSync;

program
	.version(Snakeskin.VERSION.join('.'))

	.usage('[options] [dir|file ...]')
	.option('-p, --params[options]', 'javascript options object')

	.option('-s, --source [src]', 'path to the template file')
	.option('-o, --output [src]', 'path to the file to save')
	.option('-n, --common-js', 'common.js export (for node.js)')

	.option('-e, --exec', 'execute compiled template')
	.option('-d, --data [src]', 'path to the data file (JSON) or data JSON')
	.option('-t, --tpl [name]', 'name of the main template')

	.option('--disable-localization', 'disable support for localization')
	.option('--i18n-fn', 'i18n function name')
	.option('--language [src]', 'path to the localization file (JSON) or localization JSON')
	.option('--words [src]', 'path to the localization file to save')

	.option('--disable-xml', 'disable default xml validation')
	.option('--interface', 'render all templates as interface')
	.option('--string-buffer', 'use StringBuffer for concatenate strings')
	.option('--inline-iterators', 'inline forEach and forIn')
	.option('--disable-escape-output', 'disable default "html" filter')
	.option('--pretty-print', 'formatting output')

	.parse(process.argv);

var params = program['params'] ?
	parse(params) : {};

params.xml = 'disableXml' in program ?
	!program['disableXml'] : params.xml;

params.commonJS = 'commonJs' in program ?
	program['commonJs'] : params.commonJS;

params.localization = 'disableLocalization' in program ?
	!program['disableLocalization'] : params.localization;

params.i18nFn = 'i18nFn' in program ?
	program['i18nFn'] : params.i18nFn;

params.language = 'language' in program ?
	program['language'] : params.language;

params.words = 'words' in program ?
	program['words'] : params.words;

params.interface = 'interface' in program ?
	program['interface'] : params.interface;

params.stringBuffer = 'stringBuffer' in program ?
	program['stringBuffer'] : params.stringBuffer;

params.inlineIterators = 'inlineIterators' in program ?
	program['inlineIterators'] : params.inlineIterators;

params.escapeOutput = 'disableEscapeOutput' in program ?
	!program['disableEscapeOutput'] : params.escapeOutput;

params.prettyPrint = 'prettyPrint' in program ?
	program['prettyPrint'] : params.prettyPrint;

var prettyPrint = params.prettyPrint;

if (params.language) {
	params.language = parse(params.language);
}

var exec = program['exec'];
var tplData = program['data'],
	mainTpl = program['tpl'];

var words = params.words;

if (words) {
	params.words = {};
}

var args = program['args'],
	input;

var file = program['source'],
	newFile = program['output'];

if (!file && args.length) {
	input = args.join(' ');

	if (exists(input)) {
		file = input;
		input = false;
	}
}

function parse(val) {
	if (exists(val)) {
		return JSON.parse(fs.readFileSync(val));
	}

	var res;

	try {
		res =  eval((("(" + val) + ")"));

	} catch (ignore) {
		res = {};
	}

	return res || {};
}

function action(data) {
	if (!data && !file) {
		program['help']();
	}

	var tpls = {};

	if (tplData || mainTpl || exec) {
		params.commonJS = true;
		params.context = tpls;
		params.prettyPrint = false;
	}

	var str = String(data),
		res = Snakeskin.compile(str, params, {file: file});

	var toConsole = input && !program['output'] ||
		!newFile;

	if (res !== false) {
		if (tplData || mainTpl || exec) {
			var tpl;

			if (mainTpl && mainTpl !== true) {
				tpl = tpls[mainTpl];

			} else {
				if (file) {
					tpl = tpls[file.split('.').slice(0, -1).join('.')] || tpls.main || tpls[Object.keys(tpls)[0]];

				} else {
					tpl = tpls.main || tpls[Object.keys(tpls)[0]];
				}
			}

			if (!tpl) {
				console.error('Template is not defined');
				process.exit(1);
			}

			if (tplData && tplData !== true) {
				tplData = parse(tplData);

			} else {
				tplData = void 0;
			}

			res = tpl(tplData);

			if (prettyPrint) {
				if (toConsole) {
					res = beautify['html'](res);

				} else {
					res = beautify[newFile.split('.').slice(-1)](res);
				}
			}
		}

		if (toConsole) {
			console.log(res);

		} else {
			fs.writeFileSync(newFile, res);
			console.log((("File \"" + file) + ("\" has been successfully compiled \"" + newFile) + "\"."));
		}

	} else {
		process.exit(1);
	}

	if (words) {
		fs.writeFileSync(words, JSON.stringify(params.words, null, '\t'));
	}

	process.exit(0);
}

if (input == null) {
	var buf = '';
	var stdin = process.stdin,
		stdout = process.stdout;

	stdin.setEncoding('utf8');
	stdin.on('data', function(chunk)  {
		buf += chunk;
	});

	stdin.on('end', function()  {
		action(buf);
	}).resume();

	process.on('SIGINT', function()  {
		stdout.write('\n');
		stdin.emit('end');
		stdout.write('\n');
		process.exit();
	});

} else {
	action(file ? fs.readFileSync(file).toString() : input);
}

<commit_msg>Удалён лишний пробел<commit_after>#!/usr/bin/env node

global.Snakeskin = require('./snakeskin');

var program = require('commander');
var beautify = require('js-beautify');

var path = require('path');
var fs = require('fs'),
	exists = fs.existsSync || path.existsSync;

program
	.version(Snakeskin.VERSION.join('.'))

	.usage('[options] [dir|file ...]')
	.option('-p, --params[options]', 'javascript options object')

	.option('-s, --source [src]', 'path to the template file')
	.option('-o, --output [src]', 'path to the file to save')
	.option('-n, --common-js', 'common.js export (for node.js)')

	.option('-e, --exec', 'execute compiled template')
	.option('-d, --data [src]', 'path to the data file (JSON) or data JSON')
	.option('-t, --tpl [name]', 'name of the main template')

	.option('--disable-localization', 'disable support for localization')
	.option('--i18n-fn', 'i18n function name')
	.option('--language [src]', 'path to the localization file (JSON) or localization JSON')
	.option('--words [src]', 'path to the localization file to save')

	.option('--disable-xml', 'disable default xml validation')
	.option('--interface', 'render all templates as interface')
	.option('--string-buffer', 'use StringBuffer for concatenate strings')
	.option('--inline-iterators', 'inline forEach and forIn')
	.option('--disable-escape-output', 'disable default "html" filter')
	.option('--pretty-print', 'formatting output')

	.parse(process.argv);

var params = program['params'] ?
	parse(params) : {};

params.xml = 'disableXml' in program ?
	!program['disableXml'] : params.xml;

params.commonJS = 'commonJs' in program ?
	program['commonJs'] : params.commonJS;

params.localization = 'disableLocalization' in program ?
	!program['disableLocalization'] : params.localization;

params.i18nFn = 'i18nFn' in program ?
	program['i18nFn'] : params.i18nFn;

params.language = 'language' in program ?
	program['language'] : params.language;

params.words = 'words' in program ?
	program['words'] : params.words;

params.interface = 'interface' in program ?
	program['interface'] : params.interface;

params.stringBuffer = 'stringBuffer' in program ?
	program['stringBuffer'] : params.stringBuffer;

params.inlineIterators = 'inlineIterators' in program ?
	program['inlineIterators'] : params.inlineIterators;

params.escapeOutput = 'disableEscapeOutput' in program ?
	!program['disableEscapeOutput'] : params.escapeOutput;

params.prettyPrint = 'prettyPrint' in program ?
	program['prettyPrint'] : params.prettyPrint;

var prettyPrint = params.prettyPrint;

if (params.language) {
	params.language = parse(params.language);
}

var exec = program['exec'];
var tplData = program['data'],
	mainTpl = program['tpl'];

var words = params.words;

if (words) {
	params.words = {};
}

var args = program['args'],
	input;

var file = program['source'],
	newFile = program['output'];

if (!file && args.length) {
	input = args.join(' ');

	if (exists(input)) {
		file = input;
		input = false;
	}
}

function parse(val) {
	if (exists(val)) {
		return JSON.parse(fs.readFileSync(val));
	}

	var res;

	try {
		res = eval((("(" + val) + ")"));

	} catch (ignore) {
		res = {};
	}

	return res || {};
}

function action(data) {
	if (!data && !file) {
		program['help']();
	}

	var tpls = {};

	if (tplData || mainTpl || exec) {
		params.commonJS = true;
		params.context = tpls;
		params.prettyPrint = false;
	}

	var str = String(data),
		res = Snakeskin.compile(str, params, {file: file});

	var toConsole = input && !program['output'] ||
		!newFile;

	if (res !== false) {
		if (tplData || mainTpl || exec) {
			var tpl;

			if (mainTpl && mainTpl !== true) {
				tpl = tpls[mainTpl];

			} else {
				if (file) {
					tpl = tpls[file.split('.').slice(0, -1).join('.')] || tpls.main || tpls[Object.keys(tpls)[0]];

				} else {
					tpl = tpls.main || tpls[Object.keys(tpls)[0]];
				}
			}

			if (!tpl) {
				console.error('Template is not defined');
				process.exit(1);
			}

			if (tplData && tplData !== true) {
				tplData = parse(tplData);

			} else {
				tplData = void 0;
			}

			res = tpl(tplData);

			if (prettyPrint) {
				if (toConsole) {
					res = beautify['html'](res);

				} else {
					res = beautify[newFile.split('.').slice(-1)](res);
				}
			}
		}

		if (toConsole) {
			console.log(res);

		} else {
			fs.writeFileSync(newFile, res);
			console.log((("File \"" + file) + ("\" has been successfully compiled \"" + newFile) + "\"."));
		}

	} else {
		process.exit(1);
	}

	if (words) {
		fs.writeFileSync(words, JSON.stringify(params.words, null, '\t'));
	}

	process.exit(0);
}

if (input == null) {
	var buf = '';
	var stdin = process.stdin,
		stdout = process.stdout;

	stdin.setEncoding('utf8');
	stdin.on('data', function(chunk)  {
		buf += chunk;
	});

	stdin.on('end', function()  {
		action(buf);
	}).resume();

	process.on('SIGINT', function()  {
		stdout.write('\n');
		stdin.emit('end');
		stdout.write('\n');
		process.exit();
	});

} else {
	action(file ? fs.readFileSync(file).toString() : input);
}

<|endoftext|>


<commit_before>export {
    SuperMap,
    DataFormat,
    ServerType,
    GeometryType,
    QueryOption,
    JoinType,
    EngineType,
    MeasureMode,
    SpatialRelationType,
    DataReturnMode,
    Unit,
    BufferRadiusUnit,
    SpatialQueryMode,
    ThemeGraphTextFormat,
    ThemeGraphType,
    GraphAxesTextDisplayMode,
    GraduatedMode,
    RangeMode,
    ThemeType,
    ColorGradientType,
    TextAlignment,
    FillGradientMode,
    SideType,
    AlongLineDirection,
    LabelBackShape,
    LabelOverLengthMode,
    DirectionType,
    OverlayOperationType,
    SupplyCenterType,
    TurnType,
    BufferEndType,
    SmoothMethod,
    SurfaceAnalystMethod,
    ColorSpaceType,
    ChartType,
    EditType,
    TransferTactic,
    TransferPreference,
    GridType,
    ClientType,
    LayerType,
    UGCLayerType,
    StatisticMode,
    PixelFormat,
    SearchMode,
    SummaryType,
    InterpolationAlgorithmType,
    VariogramMode,
    Exponent,
    ClipAnalystMode,
    AnalystAreaUnit,
    AnalystSizeUnit,
    StatisticAnalystMode,
    TopologyValidatorRule,
    OutputType,
    //control
    TimeFlowControl,
    //iManager
    IManager,
    IManagerServiceBase,
    IManagerCreateNodeParam,
    //iPortal
    IPortal,
    IPortalMap,
    IPortalMapsQueryParam,
    IPortalService,
    IPortalServiceBase,
    IPortalServicesQueryParam,
    //Online
    Online,
    OnlineData,
    OnlineQueryDatasParameter,
    ServiceStatus,
    DataItemType,
    DataItemOrderBy,
    FilterField,
    OnlineServiceBase,
    //security
    KeyServiceParameter,
    SecurityManager,
    ServerInfo,
    TokenServiceParameter,
    //thirdparty
    ElasticSearch,
    //util
    FetchRequest,
    //iServer
    AreaSolarRadiationParameters,
    BufferAnalystParameters,
    BufferDistance,
    BuffersAnalystJobsParameter,
    BufferSetting,
    BurstPipelineAnalystParameters,
    ChartQueryFilterParameter,
    ChartQueryParameters,
    ClipParameter,
    ColorDictionary,
    ComputeWeightMatrixParameters,
    DataReturnOption,
    DatasetBufferAnalystParameters,
    DatasetInfo,
    DatasetOverlayAnalystParameters,
    DatasetSurfaceAnalystParameters,
    DatasetThiessenAnalystParameters,
    DatasourceConnectionInfo,
    DensityKernelAnalystParameters,
    EditFeaturesParameters,
    FacilityAnalyst3DParameters,
    FacilityAnalystSinks3DParameters,
    FacilityAnalystSources3DParameters,
    FacilityAnalystStreamParameters,
    FacilityAnalystTracedown3DParameters,
    FacilityAnalystTraceup3DParameters,
    FacilityAnalystUpstream3DParameters,
    FieldParameters,
    FieldStatisticsParameters,
    FilterParameter,
    FindClosestFacilitiesParameters,
    FindLocationParameters,
    FindMTSPPathsParameters,
    FindPathParameters,
    FindServiceAreasParameters,
    FindTSPPathsParameters,
    GenerateSpatialDataParameters,
    GeoCodingParameter,
    GeoDecodingParameter,
    GeometryBufferAnalystParameters,
    GeometryOverlayAnalystParameters,
    GeometrySurfaceAnalystParameters,
    GeometryThiessenAnalystParameters,
    GeoRelationAnalystParameters,
    GetFeaturesByBoundsParameters,
    GetFeaturesByBufferParameters,
    GetFeaturesByGeometryParameters,
    GetFeaturesByIDsParameters,
    GetFeaturesBySQLParameters,
    GetGridCellInfosParameters,
    Grid,
    Image,
    InterpolationAnalystParameters,
    InterpolationIDWAnalystParameters,
    InterpolationKrigingAnalystParameters,
    InterpolationRBFAnalystParameters,
    JoinItem,
    KernelDensityJobParameter,
    LabelImageCell,
    LabelMatrixCell,
    LabelMixedTextStyle,
    LabelSymbolCell,
    LabelThemeCell,
    LayerStatus,
    LinkItem,
    MathExpressionAnalysisParameters,
    MeasureParameters,
    OutputSetting,
    OverlapDisplayedOptions,
    OverlayAnalystParameters,
    OverlayGeoJobParameter,
    PointWithMeasure,
    QueryByBoundsParameters,
    QueryByDistanceParameters,
    QueryByGeometryParameters,
    QueryBySQLParameters,
    QueryParameters,
    Route,
    RouteCalculateMeasureParameters,
    RouteLocatorParameters,
    ServerColor,
    ServerFeature,
    ServerGeometry,
    ServerStyle,
    ServerTextStyle,
    ServerTheme,
    SetLayerInfoParameters,
    SetLayersInfoParameters,
    SetLayerStatusParameters,
    SingleObjectQueryJobsParameter,
    StopQueryParameters,
    SummaryAttributesJobsParameter,
    SummaryMeshJobParameter,
    SummaryRegionJobParameter,
    SupplyCenter,
    SurfaceAnalystParameters,
    SurfaceAnalystParametersSetting,
    TerrainCurvatureCalculationParameters,
    Theme,
    ThemeDotDensity,
    ThemeFlow,
    ThemeGraduatedSymbol,
    ThemeGraduatedSymbolStyle,
    ThemeGraph,
    ThemeGraphAxes,
    ThemeGraphItem,
    ThemeGraphSize,
    ThemeGraphText,
    ThemeGridRange,
    ThemeGridRangeItem,
    ThemeGridUnique,
    ThemeGridUniqueItem,
    ThemeLabel,
    ThemeLabelAlongLine,
    ThemeLabelBackground,
    ThemeLabelItem,
    ThemeLabelText,
    ThemeLabelUniqueItem,
    ThemeMemoryData,
    ThemeOffset,
    ThemeParameters,
    ThemeRange,
    ThemeRangeItem,
    ThemeUnique,
    ThemeUniqueItem,
    ThiessenAnalystParameters,
    TopologyValidatorJobsParameter,
    TransferLine,
    TransferPathParameters,
    TransferSolutionParameters,
    TransportationAnalystParameter,
    TransportationAnalystResultSetting,
    UGCLayer,
    UGCMapLayer,
    UGCSubLayer,
    UpdateEdgeWeightParameters,
    UpdateTurnNodeWeightParameters,
    Vector,
    VectorClipJobsParameter
} from '@supermap/iclient-common';

export * from './control';
export * from './core';
export * from './mapping';
export * from './overlay';
export * from './services';<commit_msg>fix OpenLayers模块名和Common模块重名的问题。<commit_after>export {
    SuperMap,
    DataFormat,
    ServerType,
    GeometryType,
    QueryOption,
    JoinType,
    EngineType,
    MeasureMode,
    SpatialRelationType,
    DataReturnMode,
    Unit,
    BufferRadiusUnit,
    SpatialQueryMode,
    ThemeGraphTextFormat,
    ThemeGraphType,
    GraphAxesTextDisplayMode,
    GraduatedMode,
    RangeMode,
    ThemeType,
    ColorGradientType,
    TextAlignment,
    FillGradientMode,
    SideType,
    AlongLineDirection,
    LabelBackShape,
    LabelOverLengthMode,
    DirectionType,
    OverlayOperationType,
    SupplyCenterType,
    TurnType,
    BufferEndType,
    SmoothMethod,
    SurfaceAnalystMethod,
    ColorSpaceType,
    ChartType,
    EditType,
    TransferTactic,
    TransferPreference,
    GridType,
    ClientType,
    LayerType,
    UGCLayerType,
    StatisticMode,
    PixelFormat,
    SearchMode,
    SummaryType,
    InterpolationAlgorithmType,
    VariogramMode,
    Exponent,
    ClipAnalystMode,
    AnalystAreaUnit,
    AnalystSizeUnit,
    StatisticAnalystMode,
    TopologyValidatorRule,
    OutputType,
    //control
    TimeFlowControl,
    //iManager
    IManager,
    IManagerServiceBase,
    IManagerCreateNodeParam,
    //iPortal
    IPortal,
    IPortalMap,
    IPortalMapsQueryParam,
    IPortalService,
    IPortalServiceBase,
    IPortalServicesQueryParam,
    //Online
    Online,
    OnlineData,
    OnlineQueryDatasParameter,
    ServiceStatus,
    DataItemType,
    DataItemOrderBy,
    FilterField,
    OnlineServiceBase,
    //security
    KeyServiceParameter,
    SecurityManager,
    ServerInfo,
    TokenServiceParameter,
    //thirdparty
    ElasticSearch,
    //util
    FetchRequest,
    //iServer
    AreaSolarRadiationParameters,
    BufferAnalystParameters,
    BufferDistance,
    BuffersAnalystJobsParameter,
    BufferSetting,
    BurstPipelineAnalystParameters,
    ChartQueryFilterParameter,
    ChartQueryParameters,
    ClipParameter,
    ColorDictionary,
    ComputeWeightMatrixParameters,
    DataReturnOption,
    DatasetBufferAnalystParameters,
    DatasetInfo,
    DatasetOverlayAnalystParameters,
    DatasetSurfaceAnalystParameters,
    DatasetThiessenAnalystParameters,
    DatasourceConnectionInfo,
    DensityKernelAnalystParameters,
    EditFeaturesParameters,
    FacilityAnalyst3DParameters,
    FacilityAnalystSinks3DParameters,
    FacilityAnalystSources3DParameters,
    FacilityAnalystStreamParameters,
    FacilityAnalystTracedown3DParameters,
    FacilityAnalystTraceup3DParameters,
    FacilityAnalystUpstream3DParameters,
    FieldParameters,
    FieldStatisticsParameters,
    FilterParameter,
    FindClosestFacilitiesParameters,
    FindLocationParameters,
    FindMTSPPathsParameters,
    FindPathParameters,
    FindServiceAreasParameters,
    FindTSPPathsParameters,
    GenerateSpatialDataParameters,
    GeoCodingParameter,
    GeoDecodingParameter,
    GeometryBufferAnalystParameters,
    GeometryOverlayAnalystParameters,
    GeometrySurfaceAnalystParameters,
    GeometryThiessenAnalystParameters,
    GeoRelationAnalystParameters,
    GetFeaturesByBoundsParameters,
    GetFeaturesByBufferParameters,
    GetFeaturesByGeometryParameters,
    GetFeaturesByIDsParameters,
    GetFeaturesBySQLParameters,
    GetGridCellInfosParameters,
    Grid,
    Image,
    InterpolationAnalystParameters,
    InterpolationIDWAnalystParameters,
    InterpolationKrigingAnalystParameters,
    InterpolationRBFAnalystParameters,
    JoinItem,
    KernelDensityJobParameter,
    LabelImageCell,
    LabelMatrixCell,
    LabelMixedTextStyle,
    LabelSymbolCell,
    LabelThemeCell,
    LayerStatus,
    LinkItem,
    MathExpressionAnalysisParameters,
    MeasureParameters,
    OutputSetting,
    OverlapDisplayedOptions,
    OverlayAnalystParameters,
    OverlayGeoJobParameter,
    PointWithMeasure,
    QueryByBoundsParameters,
    QueryByDistanceParameters,
    QueryByGeometryParameters,
    QueryBySQLParameters,
    QueryParameters,
    Route,
    RouteCalculateMeasureParameters,
    RouteLocatorParameters,
    ServerColor,
    ServerFeature,
    ServerGeometry,
    ServerStyle,
    ServerTextStyle,
    ServerTheme,
    SetLayerInfoParameters,
    SetLayersInfoParameters,
    SetLayerStatusParameters,
    SingleObjectQueryJobsParameter,
    StopQueryParameters,
    SummaryAttributesJobsParameter,
    SummaryMeshJobParameter,
    SummaryRegionJobParameter,
    SupplyCenter,
    SurfaceAnalystParameters,
    SurfaceAnalystParametersSetting,
    TerrainCurvatureCalculationParameters,
    Theme as CommonTheme,
    ThemeDotDensity,
    ThemeFlow,
    ThemeGraduatedSymbol,
    ThemeGraduatedSymbolStyle,
    ThemeGraph,
    ThemeGraphAxes,
    ThemeGraphItem,
    ThemeGraphSize,
    ThemeGraphText,
    ThemeGridRange,
    ThemeGridRangeItem,
    ThemeGridUnique,
    ThemeGridUniqueItem,
    ThemeLabel,
    ThemeLabelAlongLine,
    ThemeLabelBackground,
    ThemeLabelItem,
    ThemeLabelText,
    ThemeLabelUniqueItem,
    ThemeMemoryData,
    ThemeOffset,
    ThemeParameters,
    ThemeRange,
    ThemeRangeItem,
    ThemeUnique,
    ThemeUniqueItem,
    ThiessenAnalystParameters,
    TopologyValidatorJobsParameter,
    TransferLine,
    TransferPathParameters,
    TransferSolutionParameters,
    TransportationAnalystParameter,
    TransportationAnalystResultSetting,
    UGCLayer,
    UGCMapLayer,
    UGCSubLayer,
    UpdateEdgeWeightParameters,
    UpdateTurnNodeWeightParameters,
    Vector,
    VectorClipJobsParameter
} from '@supermap/iclient-common';

export * from './control';
export * from './core';
export * from './mapping';
export * from './overlay';
export * from './services';<|endoftext|>


<commit_before>var express = require('express');
var fs = require('fs');
var url = require('url');
var https = require('https');
var bodyParser = require('body-parser');
var tmp = require('tmp');
var mpd = require('mpd');
var PlayMusic = require('playmusic');
var id3 = require('node-id3');

// Config setup

var config = require('./config.json');
var max_results = config.max_results || 25;
var listen_port = config.listen_port || 3000;
var server_timeout = config.server_timeout || 600000;

// PlayMusic setup

var pm = new PlayMusic();

pm.init(config.gmp, function(err) {
    if (err) throw err;
});

// MPD setup

var mpc = mpd.connect(config.mpd);

function mpc_clear_cmd() { return mpd.cmd('clear', []) };
function mpc_play_cmd() { return mpd.cmd('play', []) };
function mpc_load_cmd(url) { return mpd.cmd('add', [url]) };

function mpc_callback(err, msg) {
    if (err) throw err;
    if (msg) console.log(msg);
}

function mpc_add_track(urls, play) {
    if (play) mpc.sendCommand(mpc_clear_cmd(), mpc_callback);
    urls.map(function(url) { mpc.sendCommand(mpc_load_cmd(url), mpc_callback) });
    if (play) mpc.sendCommand(mpc_play_cmd(), mpc_callback);
}

// Express setup

var app = express();

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());

function pass_through(res) {
    return function(err, data) { res.status(200).send(data); }
}

app.get('/search', function(_req, _res) {
    if (_req.query.q) pm.search(_req.query.q, max_results, pass_through(_res));
});

app.get('/artist', function(_req, _res) {
    if (_req.query.id) pm.getArtist(_req.query.id, false, max_results, 0, pass_through(_res));
});

app.get('/album', function(_req, _res) {
    if (_req.query.id) pm.getAlbum(_req.query.id, true, pass_through(_res));
});

function id3_wrapper(id, callback) {
    pm.getAllAccessTrack(id, function(err, track) {
        var tags = {
            'artist' : track.artist,
            'album' : track.album,
            'title' : track.title,
            //'year' : track.year
        };
        tmp.file(function(err, path, fd) {
            if (err) throw err;
            var sts = id3.write(tags, path);
            callback(sts, fs.readFileSync(path));
        });
    });
}

app.get('/play.mp3', function(_req, _res) {
    if (_req.query.id) {
        pm.getStreamUrl(_req.query.id, function(err, url) {
            https.get(url, function(res) {
                _res.status(res.statusCode);
                if (res.statusCode === 200) {
                    id3_wrapper(_req.query.id, function(sts, data) {
                        if (sts) _res.write(data);
                        res.on('data', function(chunk) { _res.write(chunk) });
                        res.on('end', function() { _res.send(); });
                    });
                }
                else _res.end();
            });
        });
    }
    else _res.status(400).end();
});

function url_ids(req, ids) {
    return ids.map(function(id) {
        return url.format({
            'protocol': req.protocol,
            'hostname': req.hostname,
            'port': listen_port,
            'pathname': 'play.mp3',
            'query': {id: id}
        });
    });
}

function load_track(_req) {
    mpc_add_track(url_ids(_req, [_req.body.id]), _req.body.mode==='play');
}

function load_radio(_req) {
    pm.createStation('radio:' + _req.body.id, _req.body.id, "track", function(err, body) {
        pm.getStationTracks(body.mutate_response[0].id, max_results, function(err, data) {
            var ids = data.data.stations[0].tracks.map(function(track) { return track.nid; });
            mpc_add_track(url_ids(_req, ids), true)
        });
    });
}

function load_album(_req) {
    pm.getAlbum(_req.body.id, true, function(err, data) {
        var ids = data.tracks.map(function(track) { return track.nid; });
        mpc_add_track(url_ids(_req, ids), _req.body.mode==='play')
    });
}

app.post('/load', function(_req, _res) {
    switch (_req.body.type) {
        case "track": load_track(_req); break;
        case "radio": load_radio(_req); break;
        case "album": load_album(_req); break;
        default: _res.status(400).end(); return;
    }
    _res.status(202).end();
});

var server = app.listen(listen_port, function() {
    var host = server.address().address
    var port = server.address().port
    console.log('gmpd listening at http://%s:%s', host, port)
});
server.setTimeout(server_timeout, console.log);
<commit_msg>Better timeout logging<commit_after>var express = require('express');
var fs = require('fs');
var url = require('url');
var https = require('https');
var bodyParser = require('body-parser');
var tmp = require('tmp');
var mpd = require('mpd');
var PlayMusic = require('playmusic');
var id3 = require('node-id3');

// Config setup

var config = require('./config.json');
var max_results = config.max_results || 25;
var listen_port = config.listen_port || 3000;
var server_timeout = config.server_timeout || 600000;

// PlayMusic setup

var pm = new PlayMusic();

pm.init(config.gmp, function(err) {
    if (err) throw err;
});

// MPD setup

var mpc = mpd.connect(config.mpd);

function mpc_clear_cmd() { return mpd.cmd('clear', []) };
function mpc_play_cmd() { return mpd.cmd('play', []) };
function mpc_load_cmd(url) { return mpd.cmd('add', [url]) };

function mpc_callback(err, msg) {
    if (err) throw err;
    if (msg) console.log(msg);
}

function mpc_add_track(urls, play) {
    if (play) mpc.sendCommand(mpc_clear_cmd(), mpc_callback);
    urls.map(function(url) { mpc.sendCommand(mpc_load_cmd(url), mpc_callback) });
    if (play) mpc.sendCommand(mpc_play_cmd(), mpc_callback);
}

// Express setup

var app = express();

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());

function pass_through(res) {
    return function(err, data) { res.status(200).send(data); }
}

app.get('/search', function(_req, _res) {
    if (_req.query.q) pm.search(_req.query.q, max_results, pass_through(_res));
});

app.get('/artist', function(_req, _res) {
    if (_req.query.id) pm.getArtist(_req.query.id, false, max_results, 0, pass_through(_res));
});

app.get('/album', function(_req, _res) {
    if (_req.query.id) pm.getAlbum(_req.query.id, true, pass_through(_res));
});

function id3_wrapper(id, callback) {
    pm.getAllAccessTrack(id, function(err, track) {
        var tags = {
            'artist' : track.artist,
            'album' : track.album,
            'title' : track.title,
            //'year' : track.year
        };
        tmp.file(function(err, path, fd) {
            if (err) throw err;
            var sts = id3.write(tags, path);
            callback(sts, fs.readFileSync(path));
        });
    });
}

app.get('/play.mp3', function(_req, _res) {
    if (_req.query.id) {
        pm.getStreamUrl(_req.query.id, function(err, url) {
            https.get(url, function(res) {
                _res.status(res.statusCode);
                if (res.statusCode === 200) {
                    id3_wrapper(_req.query.id, function(sts, data) {
                        if (sts) _res.write(data);
                        res.on('data', function(chunk) { _res.write(chunk) });
                        res.on('end', function() { _res.send(); });
                    });
                }
                else _res.end();
            });
        });
    }
    else _res.status(400).end();
});

function url_ids(req, ids) {
    return ids.map(function(id) {
        return url.format({
            'protocol': req.protocol,
            'hostname': req.hostname,
            'port': listen_port,
            'pathname': 'play.mp3',
            'query': {id: id}
        });
    });
}

function load_track(_req) {
    mpc_add_track(url_ids(_req, [_req.body.id]), _req.body.mode==='play');
}

function load_radio(_req) {
    pm.createStation('radio:' + _req.body.id, _req.body.id, "track", function(err, body) {
        pm.getStationTracks(body.mutate_response[0].id, max_results, function(err, data) {
            var ids = data.data.stations[0].tracks.map(function(track) { return track.nid; });
            mpc_add_track(url_ids(_req, ids), true)
        });
    });
}

function load_album(_req) {
    pm.getAlbum(_req.body.id, true, function(err, data) {
        var ids = data.tracks.map(function(track) { return track.nid; });
        mpc_add_track(url_ids(_req, ids), _req.body.mode==='play')
    });
}

app.post('/load', function(_req, _res) {
    switch (_req.body.type) {
        case "track": load_track(_req); break;
        case "radio": load_radio(_req); break;
        case "album": load_album(_req); break;
        default: _res.status(400).end(); return;
    }
    _res.status(202).end();
});

var server = app.listen(listen_port, function() {
    var host = server.address().address
    var port = server.address().port
    console.log('gmpd listening at http://%s:%s', host, port)
});
server.setTimeout(server_timeout, function(msg) { console.log("timeout:", msg) } );
<|endoftext|>


<commit_before>/*
 * gulp-bootlint
 * https://github.com/tschortsch/gulp-bootlint
 *
 * Copyright (c) 2014 Juerg Hunziker
 * Licensed under the MIT license.
 */

'use strict';
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var through = require('through2');
var chalk = require('chalk');
var bootlint = require('bootlint');

// consts
var PLUGIN_NAME = 'gulp-bootlint';

function gulpBootlint(options) {
  options = options || {
    disabledIds: []
  };

  // creating a stream through which each file will pass
  var stream = through.obj(function (file, enc, cb) {
    var errorCount = 0;

    if (file.isNull()) {
      return cb(null, file);
    }

    if (file.isStream()) {
      this.emit('error', new PluginError(PLUGIN_NAME, 'Streams are not supported!'));
      return cb();
    }

    var reporter = function (lint) {
      var lintId = (lint.id[0] === 'E') ? chalk.bgRed.white(lint.id) : chalk.bgYellow.white(lint.id),
          errorElementsAvailable = false;

      if (lint.elements) {
        lint.elements.each(function (_, element) {
          var errorLocation = element.startLocation;
          gutil.log(file.path + ":" + (errorLocation.line + 1) + ":" + (errorLocation.column + 1), lintId, lint.message);
          errorElementsAvailable = true;
        });
      }
      if (!errorElementsAvailable) {
        gutil.log(file.path + ":", lintId, lint.message);
      }

      ++errorCount;
      file.bootlint.success = false;
      file.bootlint.issues.push(lint);
    };

    gutil.log(chalk.gray('Linting file ' + file.path));
    file.bootlint = { success: true, issues: [] };
    bootlint.lintHtml(file.contents.toString(), reporter, options.disabledIds);

    if(errorCount > 0) {
      gutil.log(chalk.red(errorCount + ' lint error(s) found in file ' + file.path));
    } else {
      gutil.log(chalk.green(file.path + ' is lint free!'));
    }

    return cb(null, file);
  });

  return stream;
};

// exporting the plugin
module.exports = gulpBootlint;<commit_msg>introduced global error if linting fails<commit_after>/*
 * gulp-bootlint
 * https://github.com/tschortsch/gulp-bootlint
 *
 * Copyright (c) 2014 Juerg Hunziker
 * Licensed under the MIT license.
 */

'use strict';
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var through = require('through2');
var chalk = require('chalk');
var bootlint = require('bootlint');

// consts
var PLUGIN_NAME = 'gulp-bootlint';

function gulpBootlint(options) {
  options = options || {
    disabledIds: []
  };
  var hasError = false;

  // creating a stream through which each file will pass
  var stream = through.obj(function (file, enc, cb) {
    var errorCount = 0;

    if (file.isNull()) {
      return cb(null, file);
    }

    if (file.isStream()) {
      this.emit('error', new PluginError(PLUGIN_NAME, 'Streams are not supported!'));
      return cb();
    }

    var reporter = function (lint) {
      console.log("reporter says something");
      var lintId = (lint.id[0] === 'E') ? chalk.bgRed.white(lint.id) : chalk.bgYellow.white(lint.id),
        errorElementsAvailable = false;

      if (lint.elements) {
        lint.elements.each(function (_, element) {
          var errorLocation = element.startLocation;
          gutil.log(file.path + ":" + (errorLocation.line + 1) + ":" + (errorLocation.column + 1), lintId, lint.message);
          errorElementsAvailable = true;
        });
      }
      if (!errorElementsAvailable) {
        gutil.log(file.path + ":", lintId, lint.message);
      }

      ++errorCount;
      hasError = true;
      file.bootlint.success = false;
      file.bootlint.issues.push(lint);
    };

    gutil.log(chalk.gray('Linting file ' + file.path));
    file.bootlint = { success: true, issues: [] };
    bootlint.lintHtml(file.contents.toString(), reporter, options.disabledIds);

    if(errorCount > 0) {
      gutil.log(chalk.red(errorCount + ' lint error(s) found in file ' + file.path));
    } else {
      gutil.log(chalk.green(file.path + ' is lint free!'));
    }

    return cb(null, file);
  }, function(cb) {
    if(hasError) {
      this.emit('error', new PluginError(PLUGIN_NAME, 'Lint errors found!'));
      return cb();
    }
  });

  return stream;
};

// exporting the plugin
module.exports = gulpBootlint;<|endoftext|>


<commit_before>/**
 * Defines a model that loosely resembles the structure of a mongoose document property.
 * @mongoose-option - Denotes that the given value will be used to defined the mongoose SchemaType option of the same name.
 */

import mongoose from 'mongoose';
import ChimeraSchema from '../schema';

const { Mixed } = mongoose.Schema.Types;
const schema = new ChimeraSchema('ChimeraField', {
	/**
	 * The name that will be used to uniquely identify the property on the model.
	 * This will be set as the key value in the generated mongoose schema.
	 */
	name: {
		type: String,
		required: true
	},

	/**
	 * @mongoose-option
	 * A secondary name to use to reference the field.
	 */
	alias: {
		type: String,
		default: ''
	},

	/**
	 * @mongoose-option
	 * The primitive data-type for the contents of the field.
	 */
	type: {
		type: String,
		required: true,
		enum: Object.keys(mongoose.SchemaTypes)
	},

	/**
	 * @mongoose-option
	 * Used to enforce if this field should require a value (neither null nor undefined)
	*/
	required: {
		type: Mixed,
		default: false
	},

	/**
	 * @mongoose-option
	 * Used to specify a default value that should be set when this field is left blank.
	 */
	default: {
		type: Mixed,
		default: undefined
	},

	/**
	 * Used to specify a validation pattern that should be performed for this field
	 */
	validators: {
		type: Object,
		default: undefined
	},

	/**
	 * @mongoose-option
	 * Used to enforce unique values in the field by enabling unique indexing in the ODM
	 */
	unique: {
		type: Boolean,
		default: false
	},

	/**
	 * @mongoose-option
	 * Used to determine if this field should be indexed for quicker filtering.
	 */
	index: {
		type: Boolean,
		default: false
	}
})
	/** Associations */
	.belongsTo('ChimeraModel', {
		localField: 'chimeraModelId',
		as: 'chimeraModel'
	}, {
		required: true
	})

	/** Indexing */
	.index({ name: 1, chimeraModelId: 1 }, { unique: true })

	/** Middleware */
	.post('save', function (field, next) {
		mongoose.model('ChimeraModel').emit('compile', field.chimeraModelId);
		next();
	});

export default schema;
<commit_msg>Add enum option to ChimeraField.<commit_after>/**
 * Defines a model that loosely resembles the structure of a mongoose document property.
 * @mongoose-option - Denotes that the given value will be used to defined the mongoose SchemaType option of the same name.
 */

import mongoose from 'mongoose';
import ChimeraSchema from '../schema';

const { Mixed, Array } = mongoose.Schema.Types;
const schema = new ChimeraSchema('ChimeraField', {
	/**
	 * The name that will be used to uniquely identify the property on the model.
	 * This will be set as the key value in the generated mongoose schema.
	 */
	name: {
		type: String,
		required: true
	},

	/**
	 * @mongoose-option
	 * A secondary name to use to reference the field.
	 */
	alias: {
		type: String,
		default: ''
	},

	/**
	 * @mongoose-option
	 * The primitive data-type for the contents of the field.
	 */
	type: {
		type: String,
		required: true,
		enum: Object.keys(mongoose.SchemaTypes)
	},

	/**
	 * @mongoose-option
	 * Used to enforce if this field should require a value (neither null nor undefined)
	*/
	required: {
		type: Mixed,
		default: false
	},

	/**
	 * @mongoose-option
	 * Used to specify a default value that should be set when this field is left blank.
	 */
	default: {
		type: Mixed,
		default: undefined
	},

	/**
	 * @mongoose-option
	 * Used to specify a discrete set of values that can be set in this field.
	 */
	enum: {
		type: Array
	},

	/**
	 * Used to specify a validation pattern that should be performed for this field
	 */
	validators: {
		type: Object,
		default: undefined
	},

	/**
	 * @mongoose-option
	 * Used to enforce unique values in the field by enabling unique indexing in the ODM
	 */
	unique: {
		type: Boolean,
		default: false
	},

	/**
	 * @mongoose-option
	 * Used to determine if this field should be indexed for quicker filtering.
	 */
	index: {
		type: Boolean,
		default: false
	}
})
	/** Associations */
	.belongsTo('ChimeraModel', {
		localField: 'chimeraModelId',
		as: 'chimeraModel'
	}, {
		required: true
	})

	/** Indexing */
	.index({ name: 1, chimeraModelId: 1 }, { unique: true })

	/** Middleware */
	.post('save', function (field, next) {
		mongoose.model('ChimeraModel').emit('compile', field.chimeraModelId);
		next();
	});

export default schema;
<|endoftext|>


<commit_before>/* eslint-disable strict */
// UMD template: https://github.com/ForbesLindesay/umd/blob/master/template.js
;(function(factory) { // eslint-disable-line no-extra-semi

    // CommonJS
    if (typeof exports === 'object' && typeof module !== 'undefined') {
        module.exports = factory();

    // RequireJS (AMD)
    } else if (typeof define === 'function' && define.amd) { // eslint-disable-line no-undef
        define([], factory()); // eslint-disable-line no-undef

    // Browser (script tag)
    } else {
        var root;
        if (typeof window !== 'undefined') {
            root = window;
        } else if (typeof global !== 'undefined') {
            root = global;
        } else if (typeof self !== 'undefined') {
            root = self;
        } else {
            // works provided we're not in strict mode
            root = this;
        }

        // define namespace
        root.HTMLReactParser = factory();
    }

})(function() {

    var domToReact = require('./lib/dom-to-react');
    var htmlToDOM;

    // client (browser)
    if (typeof window !== 'undefined' && this === window) {
        htmlToDOM = require('./lib/html-to-dom-client');

    // server (node)
    } else {
        htmlToDOM = require('./lib/html-to-dom-server');
    }

    /**
     * Convert HTML string to React elements.
     *
     * @param  {String}   html              - The HTML.
     * @param  {Object}   [options]         - The additional options.
     * @param  {Function} [options.replace] - The replace method.
     * @return {ReactElement|Array}
     */
    function HTMLReactParser(html, options) {
        if (typeof html !== 'string') {
            throw new Error('`HTMLReactParser`: The first argument must be a string.');
        }
        return domToReact(htmlToDOM(html), options);
    }

    // source
    return HTMLReactParser;

});
<commit_msg>Refactor `index.js` to let webpack handle UMD build<commit_after>'use strict';

/**
 * Module dependencies.
 */
var domToReact = require('./lib/dom-to-react');
var htmlToDOM = (
    process.browser && process.title === 'browser' ?
    require('./lib/html-to-dom-client') :
    require('./lib/html-to-dom-server')
);

/**
 * Convert HTML string to React elements.
 *
 * @param  {String}   html              - The HTML.
 * @param  {Object}   [options]         - The additional options.
 * @param  {Function} [options.replace] - The replace method.
 * @return {ReactElement|Array}
 */
function HTMLReactParser(html, options) {
    if (typeof html !== 'string') {
        throw new Error('`HTMLReactParser`: The first argument must be a string.');
    }
    return domToReact(htmlToDOM(html), options);
}

/**
 * Export HTML to React parser.
 */
module.exports = HTMLReactParser;
<|endoftext|>


<commit_before>//https://github.com/jasondavies/conrec.js
//http://stackoverflow.com/questions/263305/drawing-a-topographical-map
var tin = require('turf-tin');
var inside = require('turf-inside');
var grid = require('turf-grid');
var extent = require('turf-extent');
var planepoint = require('turf-planepoint');
var featurecollection = require('turf-featurecollection');
var linestring = require('turf-linestring');
var polygon = require('turf-polygon');
var point = require('turf-point');
var square = require('turf-square');
var size = require('turf-size');
var Conrec = require('./conrec.js');

/**
 * Takes a {@link FeatureCollection} of {@link Point} features with z-values and an array of
 * value breaks and generates filled contour isobands.
 *
 * @module turf/isobands
 * @param {FeatureCollection} points a FeeatureCollection of {@link Point} features
 * @param {string} z the property name in `points` from which z-values will be pulled
 * @param {number} resolution resolution of the underlying grid
 * @param {Array<number>} breaks where to draw contours
 * @returns {FeatureCollection} a FeatureCollection of {@link Polygon} features representing isobands
 * @example
 * // create random points with random
 * // z-values in their properties
 * var points = turf.random('point', 100, {
 *   bbox: [0, 30, 20, 50]
 * });
 * for (var i = 0; i < points.features.length; i++) {
 *   points.features[i].properties.z = Math.random() * 10;
 * }
 * var breaks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 * var isolined = turf.isobands(points, 'z', 15, breaks);
 * //=isolined
 */
module.exports = function(points, z, resolution, breaks){
  var addEdgesResult = addEdges(points, z, resolution);

  var tinResult = tin(points, z);
  var extentBBox = extent(points);
  var squareBBox = square(extentBBox);
  var gridResult = grid(squareBBox, resolution);
  var data = [];

  gridResult.features.forEach(function(pt){
    tinResult.features.forEach(function(triangle){
      if (inside(pt, triangle)) {
        pt.properties = {};
        pt.properties[z] = planepoint(pt, triangle);
      }
    });
    if(!pt.properties){
      pt.properties = {};
      pt.properties[z] = -100;
    }
  });

  var depth = Math.sqrt(gridResult.features.length);
  for (var x=0; x<depth; x++){
    var xGroup = gridResult.features.slice(x * depth, (x + 1) * depth);
    var xFlat = [];
    xGroup.forEach(function(verticalPoint){
      if(verticalPoint.properties){
        xFlat.push(verticalPoint.properties[z]);
      } else{
        xFlat.push(0);
      }
    });
    data.push(xFlat);
  }
  var interval = (squareBBox[2] - squareBBox[0]) / depth;
  var xCoordinates = [];
  var yCoordinates = [];
  for (var x=0; x<depth; x++){
    xCoordinates.push(x * interval + squareBBox[0]);
    yCoordinates.push(x * interval + squareBBox[1]);
  }

  //change zero breaks to .01 to deal with bug in conrec algorithm
  breaks = breaks.map(function(num) {
    if(num === 0){
      return 0.01;
    }
    else{
      return num;
    }
  });
  //deduplicate breaks
  breaks = unique(breaks);

  var c = new Conrec();
  c.contour(data, 0, resolution, 0, resolution, xCoordinates, yCoordinates, breaks.length, breaks);
  var contourList = c.contourList();

  var fc = featurecollection([]);
  contourList.forEach(function(c){
    if(c.length > 2){
      var polyCoordinates = [];
      c.forEach(function(coord){
        polyCoordinates.push([coord.x, coord.y]);
      });
      polyCoordinates.push([c[0].x, c[0].y]);
      var poly = polygon([polyCoordinates]);
      poly.properties = {};
      poly.properties[z] = c.level;
      fc.features.push(poly);
    }
  });

  return fc;
};

function addEdges(points, z, resolution){
  var extentBBox = extent(points),
    sizeResult;

  var squareBBox = square(extentBBox);
  var sizeBBox = size(squareBBox, 0.35);

  var edgeDistance = sizeBBox[2] - sizeBBox[0];
  var extendDistance = edgeDistance / resolution;

  var xmin = sizeBBox[0];
  var ymin = sizeBBox[1];
  var xmax = sizeBBox[2];
  var ymax = sizeBBox[3];

  //left
  var left = [[xmin, ymin],[xmin, ymax]];
  for(var i = 0; i<=resolution; i++){
    var pt = point([xmin, ymin + (extendDistance * i)]);
    pt.properties = {};
    pt.properties[z] = -100;
    points.features.push(pt);
  }

  var i, pt;

  //bottom
  var bottom = [[xmin, ymin],[xmax, ymin]];
  for(i = 0; i<=resolution; i++){
    pt = point([xmin + (extendDistance * i), ymin]);
    pt.properties = {};
    pt.properties[z] = -100;
    points.features.push(pt);
  }

  //right
  var right = [[xmax, ymin],[xmax, ymax]];
  for(i = 0; i<=resolution; i++){
    pt = point([xmax, ymin + (extendDistance * i)]);
    pt.properties = {};
    pt.properties[z] = -100;
    points.features.push(pt);
  }

  //top
  var top = [[xmin, ymax],[xmax, ymax]];
  for(i = 0; i<=resolution; i++){
    pt = point([xmin + (extendDistance * i), ymax]);
    pt.properties = {};
    pt.properties[z] = -100;
    points.features.push(pt);
  }

  return points;
}

function unique(a) {
  return a.reduce(function(p, c) {
      if (p.indexOf(c) < 0) p.push(c);
      return p;
  }, []);
}
<commit_msg>Add category<commit_after>//https://github.com/jasondavies/conrec.js
//http://stackoverflow.com/questions/263305/drawing-a-topographical-map
var tin = require('turf-tin');
var inside = require('turf-inside');
var grid = require('turf-grid');
var extent = require('turf-extent');
var planepoint = require('turf-planepoint');
var featurecollection = require('turf-featurecollection');
var linestring = require('turf-linestring');
var polygon = require('turf-polygon');
var point = require('turf-point');
var square = require('turf-square');
var size = require('turf-size');
var Conrec = require('./conrec.js');

/**
 * Takes a {@link FeatureCollection} of {@link Point} features with z-values and an array of
 * value breaks and generates filled contour isobands.
 *
 * @module turf/isobands
 * @category interpolation
 * @param {FeatureCollection} points a FeeatureCollection of {@link Point} features
 * @param {string} z the property name in `points` from which z-values will be pulled
 * @param {number} resolution resolution of the underlying grid
 * @param {Array<number>} breaks where to draw contours
 * @returns {FeatureCollection} a FeatureCollection of {@link Polygon} features representing isobands
 * @example
 * // create random points with random
 * // z-values in their properties
 * var points = turf.random('point', 100, {
 *   bbox: [0, 30, 20, 50]
 * });
 * for (var i = 0; i < points.features.length; i++) {
 *   points.features[i].properties.z = Math.random() * 10;
 * }
 * var breaks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 * var isolined = turf.isobands(points, 'z', 15, breaks);
 * //=isolined
 */
module.exports = function(points, z, resolution, breaks){
  var addEdgesResult = addEdges(points, z, resolution);

  var tinResult = tin(points, z);
  var extentBBox = extent(points);
  var squareBBox = square(extentBBox);
  var gridResult = grid(squareBBox, resolution);
  var data = [];

  gridResult.features.forEach(function(pt){
    tinResult.features.forEach(function(triangle){
      if (inside(pt, triangle)) {
        pt.properties = {};
        pt.properties[z] = planepoint(pt, triangle);
      }
    });
    if(!pt.properties){
      pt.properties = {};
      pt.properties[z] = -100;
    }
  });

  var depth = Math.sqrt(gridResult.features.length);
  for (var x=0; x<depth; x++){
    var xGroup = gridResult.features.slice(x * depth, (x + 1) * depth);
    var xFlat = [];
    xGroup.forEach(function(verticalPoint){
      if(verticalPoint.properties){
        xFlat.push(verticalPoint.properties[z]);
      } else{
        xFlat.push(0);
      }
    });
    data.push(xFlat);
  }
  var interval = (squareBBox[2] - squareBBox[0]) / depth;
  var xCoordinates = [];
  var yCoordinates = [];
  for (var x=0; x<depth; x++){
    xCoordinates.push(x * interval + squareBBox[0]);
    yCoordinates.push(x * interval + squareBBox[1]);
  }

  //change zero breaks to .01 to deal with bug in conrec algorithm
  breaks = breaks.map(function(num) {
    if(num === 0){
      return 0.01;
    }
    else{
      return num;
    }
  });
  //deduplicate breaks
  breaks = unique(breaks);

  var c = new Conrec();
  c.contour(data, 0, resolution, 0, resolution, xCoordinates, yCoordinates, breaks.length, breaks);
  var contourList = c.contourList();

  var fc = featurecollection([]);
  contourList.forEach(function(c){
    if(c.length > 2){
      var polyCoordinates = [];
      c.forEach(function(coord){
        polyCoordinates.push([coord.x, coord.y]);
      });
      polyCoordinates.push([c[0].x, c[0].y]);
      var poly = polygon([polyCoordinates]);
      poly.properties = {};
      poly.properties[z] = c.level;
      fc.features.push(poly);
    }
  });

  return fc;
};

function addEdges(points, z, resolution){
  var extentBBox = extent(points),
    sizeResult;

  var squareBBox = square(extentBBox);
  var sizeBBox = size(squareBBox, 0.35);

  var edgeDistance = sizeBBox[2] - sizeBBox[0];
  var extendDistance = edgeDistance / resolution;

  var xmin = sizeBBox[0];
  var ymin = sizeBBox[1];
  var xmax = sizeBBox[2];
  var ymax = sizeBBox[3];

  //left
  var left = [[xmin, ymin],[xmin, ymax]];
  for(var i = 0; i<=resolution; i++){
    var pt = point([xmin, ymin + (extendDistance * i)]);
    pt.properties = {};
    pt.properties[z] = -100;
    points.features.push(pt);
  }

  var i, pt;

  //bottom
  var bottom = [[xmin, ymin],[xmax, ymin]];
  for(i = 0; i<=resolution; i++){
    pt = point([xmin + (extendDistance * i), ymin]);
    pt.properties = {};
    pt.properties[z] = -100;
    points.features.push(pt);
  }

  //right
  var right = [[xmax, ymin],[xmax, ymax]];
  for(i = 0; i<=resolution; i++){
    pt = point([xmax, ymin + (extendDistance * i)]);
    pt.properties = {};
    pt.properties[z] = -100;
    points.features.push(pt);
  }

  //top
  var top = [[xmin, ymax],[xmax, ymax]];
  for(i = 0; i<=resolution; i++){
    pt = point([xmin + (extendDistance * i), ymax]);
    pt.properties = {};
    pt.properties[z] = -100;
    points.features.push(pt);
  }

  return points;
}

function unique(a) {
  return a.reduce(function(p, c) {
      if (p.indexOf(c) < 0) p.push(c);
      return p;
  }, []);
}
<|endoftext|>


<commit_before>var crypto = require('crypto');

module.exports = function (config) {
  if (!config.github) {
    throw new Error('No configuration found');
  }

  // extract 'github' config section
  config = config.github;

  /**
   * Validate incoming HTTP headers
   *
   * Check if all required HTTP headers exist and
   * throw an exception otherwise.
   */
  var validateHeaders = function(req) {
    var validHeaders = [
      'x-hub-signature',
      'x-github-event',
      'x-github-delivery'
    ];
    for (var i in validHeaders) {
      if (!req.headers[validHeaders[i]]) {
        throw new Error('No ' + validHeaders[i] + ' found on request');
      }
    }
  }

  return {
    process: function(req, callback) {
      validateHeaders(req);

      // obtain the signature from the x-hub-signature header
      var signature = req.headers['x-hub-signature'];

      // start a hasher
      req.hasher = crypto.createHmac('sha1', config.key);
      req.setEncoding('utf8');
      var data = '';

      // whenever there's new incoming data update the hasher
      req.on('data', function (chunk) {
        data += chunk;
        req.hasher.update(chunk);
      });

      // when the request ends, compare signature and hash
      req.on('end', function() {
        var hash = 'sha1=' + req.hasher.digest('hex');
        if (hash != received_sig) {
          callback(null, 403);
        } else {
          // this is a valid webhook from GitHub

          // convert body to JSON
          req.body = JSON.parse(data);

          // TODO: contact GitHub
          // TODO
          // Get all issues with the same label as the one
          // from the webhook and return the whole object
          //
          // Also get associated milestones and parse them

          // callback the caller passing the JSON body
          callback(req.body, null);
        }
      });
    }
  };
};<commit_msg>:wrench: Typo.<commit_after>var crypto = require('crypto');

module.exports = function (config) {
  if (!config.github) {
    throw new Error('No configuration found');
  }

  // extract 'github' config section
  config = config.github;

  /**
   * Validate incoming HTTP headers
   *
   * Check if all required HTTP headers exist and
   * throw an exception otherwise.
   */
  var validateHeaders = function(req) {
    var validHeaders = [
      'x-hub-signature',
      'x-github-event',
      'x-github-delivery'
    ];
    for (var i in validHeaders) {
      if (!req.headers[validHeaders[i]]) {
        throw new Error('No ' + validHeaders[i] + ' found on request');
      }
    }
  }

  return {
    process: function(req, callback) {
      validateHeaders(req);

      // obtain the signature from the x-hub-signature header
      var signature = req.headers['x-hub-signature'];

      // start a hasher
      req.hasher = crypto.createHmac('sha1', config.key);
      req.setEncoding('utf8');
      var data = '';

      // whenever there's new incoming data update the hasher
      req.on('data', function (chunk) {
        data += chunk;
        req.hasher.update(chunk);
      });

      // when the request ends, compare signature and hash
      req.on('end', function() {
        var hash = 'sha1=' + req.hasher.digest('hex');
        if (hash != signature) {
          callback(null, 403);
        } else {
          // this is a valid webhook from GitHub

          // convert body to JSON
          req.body = JSON.parse(data);

          // callback the caller passing the JSON body
          callback(req.body, null);
        }
      });
    }
  };
};<|endoftext|>


<commit_before>var starwars = require('starwars');
var fs = require('fs');
var talk = '\n Now is ' + (new Date()).toString() + '.\n ' + starwars() + '\n';
var path = require('path');
var myPath = path.normalize(__dirname);
var exec = require('child_process').exec;

function gitExecute(args, callback) {
  var cmd = 'git --git-dir='+path.join(myPath,'.git')+' --work-tree='+myPath+' ';

  args.forEach(function(item) {
    cmd += item + ' ';
  });
  exec(cmd, callback);
}
gitExecute(['pull', '--rebase'], function(err, stdout, stderr) {
  if (err) {
    throw err;
  }
  fs.open('./README.md', 'a', 0644, function(e, fd) {
    if (e) throw e;
    console.log(talk);
    fs.write(fd, talk, function(e) {
      if (e) throw e;
      fs.closeSync(fd);
      gitExecute(['add', '-A'], function(err, stdout, stderr) {
        if (err) {
          throw err;
        }

        gitExecute(['commit', '-m', '"' + starwars() + '"'], function(err, stdout, stderr) {
          if (err) {
            throw err;
          }

        gitExecute(['push'], function(err, stdout, stderr) {
          if (err) {
            throw err;
          }

        });
        });
      });
    });
  });
});
<commit_msg>update path<commit_after>var starwars = require('starwars');
var fs = require('fs');
var talk = '\n Now is ' + (new Date()).toString() + '.\n ' + starwars() + '\n';
var path = require('path');
var myPath = path.normalize(__dirname);
var exec = require('child_process').exec;

function gitExecute(args, callback) {
  var cmd = 'git --git-dir='+path.join(myPath,'.git')+' --work-tree='+myPath+' ';

  args.forEach(function(item) {
    cmd += item + ' ';
  });
  exec(cmd, callback);
}
gitExecute(['pull', '--rebase'], function(err, stdout, stderr) {
  if (err) {
    throw err;
  }
  fs.open(path.join(__dirname,'README.md'), 'a', 0644, function(e, fd) {
    if (e) throw e;
    console.log(talk);
    fs.write(fd, talk, function(e) {
      if (e) throw e;
      fs.closeSync(fd);
      gitExecute(['add', '-A'], function(err, stdout, stderr) {
        if (err) {
          throw err;
        }

        gitExecute(['commit', '-m', '"' + starwars() + '"'], function(err, stdout, stderr) {
          if (err) {
            throw err;
          }

        gitExecute(['push'], function(err, stdout, stderr) {
          if (err) {
            throw err;
          }

        });
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-cli-segment',

  contentFor: function (type, config) {
    if (type === 'head') {

      if (!config.segment || !config.segment.WRITE_KEY) {
        return '';
      }

      return `<script type="text/javascript">
                !function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","group","track","ready","alias","page","once","off","on"];analytics.factory=function(t){return function(){var e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(var t=0;t<analytics.methods.length;t++){var e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t){var e=document.createElement("script");e.type="text/javascript";e.async=!0;e.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(e,n)};analytics.SNIPPET_VERSION="3.0.1";
                  analytics.load("${config.segment.WRITE_KEY}");
                }}();
             </script>`;
    }
  },
};
<commit_msg>Don't use ES6 string interpolation<commit_after>/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-cli-segment',

  contentFor: function (type, config) {
    if (type === 'head') {

      if (!config.segment || !config.segment.WRITE_KEY) {
        return '';
      }

      return '<script type="text/javascript">' +
                '!function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","group","track","ready","alias","page","once","off","on"];analytics.factory=function(t){return function(){var e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(var t=0;t<analytics.methods.length;t++){var e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t){var e=document.createElement("script");e.type="text/javascript";e.async=!0;e.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(e,n)};analytics.SNIPPET_VERSION="3.0.1";' +
                  'analytics.load("' + config.segment.WRITE_KEY + '");' +
                '}}();' +
             '</script>';
    }
  },
};
<|endoftext|>


<commit_before>/**
 * TafgeetJS module.
 * @module TafgeetJS
 * @description Converts currency digits into written Arabic words
 * @author Mohammed Mahgoub <mmahgoub@gmail.com>
 */

function Tafgeet(digit, currency = "SDG") {
  //Split fractions
  var splitted = digit.toString().split(".");
  this.fraction = 0;
  if (splitted.length > 1) {
    var fraction = parseInt(splitted[1]);
    if (fraction >= 1 && fraction <= 99) {
      this.fraction = fraction;
    } else {
      //trim it
      var trimmed = Array.from(splitted[1]);
      this.fraction = "" + trimmed[0] + trimmed[1];
    }
  }
  this.digit = splitted[0];
  this.currency = currency;
}

Tafgeet.prototype.parse = function() {
  var serialized = [];
  var tmp = [];
  var inc = 1;
  var count = this.length();
  if (count >= 16) {
    console.error("Number out of range!");
    return;
  }
  //Sperate the number into columns
  Array.from(this.digit.toString()).reverse().forEach(function(d, i) {
    tmp.push(d);
    if (inc == 3) {
      serialized.unshift(tmp);
      tmp = [];
      inc = 0;
    }
    if (inc == 0 && count - (i + 1) < 3 && count - (i + 1) != 0) {
      serialized.unshift(tmp);
    }
    inc++;
  });

  var str = "";
  str += "فقط ";

  if (this.length() >= 1 && this.length() <= 3) {
    str += this.read(this.digit);
  } else {
    var column = this.getColumnIndex();
    for (i = 0; i < serialized.length; i++) {
      var joinedNumber = parseInt(serialized[i].reverse().join(""));
      if (joinedNumber == 0) {
        column++;
        continue;
      }
      if (column == null || column + 1 > this.columns.length) {
        str += this.read(joinedNumber);
      } else {
        str += this.addSuffixPrefix(serialized[i], column) + " و";
      }
      column++;
    }
  }

  if (this.currency != "") {
    if (this.digit >= 3 && this.digit <= 10) {
      str += " " + this.currencies[this.currency].plural;
    } else {
      str += " " + this.currencies[this.currency].singular;
    }

    if (this.fraction != 0) {
      if (this.digit >= 3 && this.digit <= 10) {
        str +=
          " و" +
          this.read(this.fraction) +
          " " +
          this.currencies[this.currency].fractions;
      } else {
        str +=
          " و" +
          this.read(this.fraction) +
          " " +
          this.currencies[this.currency].fraction;
      }
    }
  }

  str += " لا غير";
  return str;
};

Tafgeet.prototype.addSuffixPrefix = function(arr, column) {
  if (arr.length == 1) {
    if (parseInt(arr[0]) == 1) {
      return this[this.columns[column]].singular;
    }
    if (parseInt(arr[0]) == 2) {
      return this[this.columns[column]].binary;
    }
    if (parseInt(arr[0]) > 2 && parseInt(arr[0]) <= 9) {
      return (
        this.readOnes(parseInt(arr[0])) +
        " " +
        this[this.columns[column]].plural
      );
    }
  } else {
    var joinedNumber = parseInt(arr.join(""));
    return this.read(joinedNumber) + " " + this[this.columns[column]].singular;
  }
};

Tafgeet.prototype.read = function(d) {
  var str = "";
  var len = Array.from(d.toString()).length;
  if (len == 1) {
    str += this.readOnes(d);
  } else if (len == 2) {
    str += this.readTens(d);
  } else if (len == 3) {
    str += this.readHundreds(d);
  }
  return str;
};

Tafgeet.prototype.readOnes = function(d) {
  if (d == 0) return;
  return this.ones["_" + d.toString()];
};
Tafgeet.prototype.readTens = function(d) {
  if (Array.from(d.toString())[1] === "0") {
    return this.tens["_" + d.toString()];
  }
  if (d > 10 && d < 20) {
    return this.teens["_" + d.toString()];
  }
  if (d > 19 && d < 100 && Array.from(d.toString())[1] !== "0") {
    return (
      this.readOnes(Array.from(d.toString())[1]) +
      " و" +
      this.tens["_" + Array.from(d.toString())[0] + "0"]
    );
  }
};
Tafgeet.prototype.readHundreds = function(d) {
  var str = "";
  str += this.hundreds["_" + Array.from(d.toString())[0] + "00"];

  if (
    Array.from(d.toString())[1] === "0" &&
    Array.from(d.toString())[2] !== "0"
  ) {
    str += " و" + this.readOnes(Array.from(d.toString())[2]);
  }

  if (Array.from(d.toString())[1] !== "0") {
    str +=
      " و" +
      this.readTens(
        (Array.from(d.toString())[1] + Array.from(d.toString())[2]).toString()
      );
  }
  return str;
};

Tafgeet.prototype.length = function() {
  return Array.from(this.digit.toString()).length;
};

Tafgeet.prototype.getColumnIndex = function() {
  var column = null;
  if (this.length() > 12) {
    column = 0;
  } else if (this.length() <= 12 && this.length() > 9) {
    column = 1;
  } else if (this.length() <= 9 && this.length() > 6) {
    column = 2;
  } else if (this.length() <= 6 && this.length() >= 4) {
    column = 3;
  }
  return column;
};

Tafgeet.prototype.ones = {
  _1: "واحد",
  _2: "إثنين",
  _3: "ثلاثة",
  _4: "أربعة",
  _5: "خمسة",
  _6: "ستة",
  _7: "سبعة",
  _8: "ثمانية",
  _9: "تسعة"
};

Tafgeet.prototype.teens = {
  _11: "أحد عشر",
  _12: "أثني عشر",
  _13: "ثلاثة عشر",
  _14: "أربعة عشر",
  _15: "خمسة عشر",
  _16: "ستة عشر",
  _17: "سبعة عشر",
  _18: "ثمانية عشر",
  _19: "تسعة عشر"
};

Tafgeet.prototype.tens = {
  _10: "عشرة",
  _20: "عشرين",
  _30: "ثلاثين",
  _40: "أربعين",
  _50: "خمسين",
  _60: "ستين",
  _70: "سبعين",
  _80: "ثمانين",
  _90: "تسعين"
};
Tafgeet.prototype.hundreds = {
  _100: "مائة",
  _200: "مائتين",
  _300: "ثلاثمائة",
  _400: "أربعمائة",
  _500: "خمسمائة",
  _600: "ستمائة",
  _700: "سبعمائة",
  _800: "ثمانمائة",
  _900: "تسعمائة"
};
Tafgeet.prototype.thousands = {
  singular: "ألف",
  binary: "ألفين",
  plural: "ألآف"
};
Tafgeet.prototype.milions = {
  singular: "مليون",
  binary: "مليونين",
  plural: "ملايين"
};
Tafgeet.prototype.bilions = {
  singular: "مليار",
  binary: "مليارين",
  plural: "مليارات"
};
Tafgeet.prototype.trilions = {
  singular: "ترليون",
  binary: "ترليونين",
  plural: "ترليونات"
};
Tafgeet.prototype.columns = ["trilions", "bilions", "milions", "thousands"];

Tafgeet.prototype.currencies = {
  SDG: {
    singular: "جنيه سوداني",
    plural: "جنيهات سودانية",
    fraction: "قرش",
    fractions: "قروش"
  },
  SAR: {
    singular: "ريال سعودي",
    plural: "ريالات سعودية",
    fraction: "هللة",
    fractions: "هللات"
  },
  QR: {
    singular: "ريال قطري",
    plural: "ريالات قطرية",
    fraction: "درهم",
    fractions: "دراهم"
  },
  AED: {
    singular: "درهم أماراتي",
    plural: "دراهم أماراتية",
    fraction: "فلس",
    fractions: "فلوس"
  },
  EGP: {
    singular: "جنيه مصري",
    plural: "جنيهات مصرية",
    fraction: "قرش",
    fractions: "قروش"
  },
  USD: {
    singular: "دولار أمريكي",
    plural: "دولارات أمريكية",
    fraction: "سنت",
    fractions: "سنتات"
  }
};

module.exports = Tafgeet;
<commit_msg>fix 'ٱثنين' word & add TND (Tunisian Dinar) currency<commit_after>/**
 * TafgeetJS module.
 * @module TafgeetJS
 * @description Converts currency digits into written Arabic words
 * @author Mohammed Mahgoub <mmahgoub@gmail.com>
 */

function Tafgeet(digit, currency = "SDG") {
  //Split fractions
  var splitted = digit.toString().split(".");
  this.fraction = 0;
  if (splitted.length > 1) {
    var fraction = parseInt(splitted[1]);
    if (fraction >= 1 && fraction <= 99) {
      this.fraction = fraction;
    } else {
      //trim it
      var trimmed = Array.from(splitted[1]);
      this.fraction = "" + trimmed[0] + trimmed[1];
    }
  }
  this.digit = splitted[0];
  this.currency = currency;
}

Tafgeet.prototype.parse = function() {
  var serialized = [];
  var tmp = [];
  var inc = 1;
  var count = this.length();
  if (count >= 16) {
    console.error("Number out of range!");
    return;
  }
  //Sperate the number into columns
  Array.from(this.digit.toString()).reverse().forEach(function(d, i) {
    tmp.push(d);
    if (inc == 3) {
      serialized.unshift(tmp);
      tmp = [];
      inc = 0;
    }
    if (inc == 0 && count - (i + 1) < 3 && count - (i + 1) != 0) {
      serialized.unshift(tmp);
    }
    inc++;
  });

  var str = "";
  str += "فقط ";

  if (this.length() >= 1 && this.length() <= 3) {
    str += this.read(this.digit);
  } else {
    var column = this.getColumnIndex();
    for (i = 0; i < serialized.length; i++) {
      var joinedNumber = parseInt(serialized[i].reverse().join(""));
      if (joinedNumber == 0) {
        column++;
        continue;
      }
      if (column == null || column + 1 > this.columns.length) {
        str += this.read(joinedNumber);
      } else {
        str += this.addSuffixPrefix(serialized[i], column) + " و";
      }
      column++;
    }
  }

  if (this.currency != "") {
    if (this.digit >= 3 && this.digit <= 10) {
      str += " " + this.currencies[this.currency].plural;
    } else {
      str += " " + this.currencies[this.currency].singular;
    }

    if (this.fraction != 0) {
      if (this.digit >= 3 && this.digit <= 10) {
        str +=
          " و" +
          this.read(this.fraction) +
          " " +
          this.currencies[this.currency].fractions;
      } else {
        str +=
          " و" +
          this.read(this.fraction) +
          " " +
          this.currencies[this.currency].fraction;
      }
    }
  }

  str += " لا غير";
  return str;
};

Tafgeet.prototype.addSuffixPrefix = function(arr, column) {
  if (arr.length == 1) {
    if (parseInt(arr[0]) == 1) {
      return this[this.columns[column]].singular;
    }
    if (parseInt(arr[0]) == 2) {
      return this[this.columns[column]].binary;
    }
    if (parseInt(arr[0]) > 2 && parseInt(arr[0]) <= 9) {
      return (
        this.readOnes(parseInt(arr[0])) +
        " " +
        this[this.columns[column]].plural
      );
    }
  } else {
    var joinedNumber = parseInt(arr.join(""));
    return this.read(joinedNumber) + " " + this[this.columns[column]].singular;
  }
};

Tafgeet.prototype.read = function(d) {
  var str = "";
  var len = Array.from(d.toString()).length;
  if (len == 1) {
    str += this.readOnes(d);
  } else if (len == 2) {
    str += this.readTens(d);
  } else if (len == 3) {
    str += this.readHundreds(d);
  }
  return str;
};

Tafgeet.prototype.readOnes = function(d) {
  if (d == 0) return;
  return this.ones["_" + d.toString()];
};
Tafgeet.prototype.readTens = function(d) {
  if (Array.from(d.toString())[1] === "0") {
    return this.tens["_" + d.toString()];
  }
  if (d > 10 && d < 20) {
    return this.teens["_" + d.toString()];
  }
  if (d > 19 && d < 100 && Array.from(d.toString())[1] !== "0") {
    return (
      this.readOnes(Array.from(d.toString())[1]) +
      " و" +
      this.tens["_" + Array.from(d.toString())[0] + "0"]
    );
  }
};
Tafgeet.prototype.readHundreds = function(d) {
  var str = "";
  str += this.hundreds["_" + Array.from(d.toString())[0] + "00"];

  if (
    Array.from(d.toString())[1] === "0" &&
    Array.from(d.toString())[2] !== "0"
  ) {
    str += " و" + this.readOnes(Array.from(d.toString())[2]);
  }

  if (Array.from(d.toString())[1] !== "0") {
    str +=
      " و" +
      this.readTens(
        (Array.from(d.toString())[1] + Array.from(d.toString())[2]).toString()
      );
  }
  return str;
};

Tafgeet.prototype.length = function() {
  return Array.from(this.digit.toString()).length;
};

Tafgeet.prototype.getColumnIndex = function() {
  var column = null;
  if (this.length() > 12) {
    column = 0;
  } else if (this.length() <= 12 && this.length() > 9) {
    column = 1;
  } else if (this.length() <= 9 && this.length() > 6) {
    column = 2;
  } else if (this.length() <= 6 && this.length() >= 4) {
    column = 3;
  }
  return column;
};

Tafgeet.prototype.ones = {
  _1: "واحد",
  _2: "ٱثنين",
  _3: "ثلاثة",
  _4: "أربعة",
  _5: "خمسة",
  _6: "ستة",
  _7: "سبعة",
  _8: "ثمانية",
  _9: "تسعة"
};

Tafgeet.prototype.teens = {
  _11: "أحد عشر",
  _12: "أثني عشر",
  _13: "ثلاثة عشر",
  _14: "أربعة عشر",
  _15: "خمسة عشر",
  _16: "ستة عشر",
  _17: "سبعة عشر",
  _18: "ثمانية عشر",
  _19: "تسعة عشر"
};

Tafgeet.prototype.tens = {
  _10: "عشرة",
  _20: "عشرين",
  _30: "ثلاثين",
  _40: "أربعين",
  _50: "خمسين",
  _60: "ستين",
  _70: "سبعين",
  _80: "ثمانين",
  _90: "تسعين"
};
Tafgeet.prototype.hundreds = {
  _100: "مائة",
  _200: "مائتين",
  _300: "ثلاثمائة",
  _400: "أربعمائة",
  _500: "خمسمائة",
  _600: "ستمائة",
  _700: "سبعمائة",
  _800: "ثمانمائة",
  _900: "تسعمائة"
};
Tafgeet.prototype.thousands = {
  singular: "ألف",
  binary: "ألفين",
  plural: "ألآف"
};
Tafgeet.prototype.milions = {
  singular: "مليون",
  binary: "مليونين",
  plural: "ملايين"
};
Tafgeet.prototype.bilions = {
  singular: "مليار",
  binary: "مليارين",
  plural: "مليارات"
};
Tafgeet.prototype.trilions = {
  singular: "ترليون",
  binary: "ترليونين",
  plural: "ترليونات"
};
Tafgeet.prototype.columns = ["trilions", "bilions", "milions", "thousands"];

Tafgeet.prototype.currencies = {
  SDG: {
    singular: "جنيه سوداني",
    plural: "جنيهات سودانية",
    fraction: "قرش",
    fractions: "قروش"
  },
  SAR: {
    singular: "ريال سعودي",
    plural: "ريالات سعودية",
    fraction: "هللة",
    fractions: "هللات"
  },
  QR: {
    singular: "ريال قطري",
    plural: "ريالات قطرية",
    fraction: "درهم",
    fractions: "دراهم"
  },
  AED: {
    singular: "درهم أماراتي",
    plural: "دراهم أماراتية",
    fraction: "فلس",
    fractions: "فلوس"
  },
  EGP: {
    singular: "جنيه مصري",
    plural: "جنيهات مصرية",
    fraction: "قرش",
    fractions: "قروش"
  },
  USD: {
    singular: "دولار أمريكي",
    plural: "دولارات أمريكية",
    fraction: "سنت",
    fractions: "سنتات"
  },
  TND: {
    singular: "دينار تونسي",
    plural: "دنانير تونسية",
    fraction: "مليم",
    fractions: "مليمات"
  }
};

module.exports = Tafgeet;
<|endoftext|>


<commit_before>var express = require('express'),
    app = express(),
    coffeeBear = require('coffee-bear');

// configuration
app.set('port', process.env.PORT || 5000);
app.use(express.logger());

app.get('/api/v1/measurements/:cups?', function (req, res) {
  coffeeBear(function (err, data) {
    var cups = req.params.cups;

    if (err) { res.json(500, {error: err}); }

    if (cups === undefined) {
      res.json(data);
      return;
    }

    if (data[cups] !== undefined) {
      res.json(data[cups]);
      return;
    }

    res.json(404, {error: 'Measurement not found' });
  });
});

app.listen(app.get('port'), function () {
  console.log('listening on port ' + app.get('port'));
});
<commit_msg>add slack webhook<commit_after>var express = require('express'),
    app = express(),
    coffeeBear = require('coffee-bear');

// configuration
app.set('port', process.env.PORT || 5000);
app.use(express.logger());

app.get('/api/v1/measurements/:cups?', function (req, res) {
  coffeeBear(function (err, data) {
    var cups = req.params.cups;

    if (err) { res.json(500, {error: err}); }

    if (cups === undefined) {
      res.json(data);
      return;
    }

    if (data[cups] !== undefined) {
      res.json(data[cups]);
      return;
    }

    res.json(404, {error: 'Measurement not found' });
  });
});

// support slack requests
app.get('/webhooks/slack', function (req, res) {
  coffeeBear(function (err, data) {
    var cups = req.query.text;

    if (err) {
      res.send('Sorry, something went wrong processing your request');
    }

    if (cups === undefined) {
      res.send('How many cups did you want to make? eg: /coffee 5');
      return;
    }

    if (data[cups] !== undefined) {
      res.send(JSON.stringify(data[cups]));
      return;
    }

    res.send("Sorry, I don't know how to make that much coffee.");
  });
});

app.listen(app.get('port'), function () {
  console.log('listening on port ' + app.get('port'));
});
<|endoftext|>