<commit_before>/**
 * Convert a CSL date into human-readable format
 *
 * @access protected
 * @memberof Cite.get
 *
 * @param {Object} date - A date in CSL format
 * @param {String} [delimiter='-'] - Date part delimiter
 *
 * @return {String} The string
 */
const getDate = function ({'date-parts': [date]}, delimiter = '-') {
  let strings = date.map(part => part.toString())

  switch (strings.length) {
    // Day
    case 3:
      strings[2] = strings[2].padStart(2, '0')
      // fall through

    // Month
    case 2:
      strings[1] = strings[1].padStart(2, '0')
      // fall through

    // Year
    case 1:
      strings[0] = strings[0].padStart(4, '0')
      break
  }

  return strings.join(delimiter)
}

export default getDate
<commit_msg>[package] Fix code style issues<commit_after>/**
 * Convert a CSL date into human-readable format
 *
 * @access protected
 * @memberof Cite.get
 *
 * @param {Object} date - A date in CSL format
 * @param {String} [delimiter='-'] - Date part delimiter
 *
 * @return {String} The string
 */
const getDate = function ({'date-parts': [date]}, delimiter = '-') {
  let dateParts = date.map(part => part.toString())

  switch (dateParts.length) {
    case 3:
      // Day
      dateParts[2] = dateParts[2].padStart(2, '0')
      // fall through
    case 2:
      // Month
      dateParts[1] = dateParts[1].padStart(2, '0')
      // fall through
    case 1:
      // Year
      dateParts[0] = dateParts[0].padStart(4, '0')
      break
  }

  return dateParts.join(delimiter)
}

export default getDate
<|endoftext|>


<commit_before>var $ = require('jQuery');

function injectAssets(html, re, type) {
    var m;
    while (m = re.exec(html)) {
        var se;
        if (type == 'text/css') {
            var alreadyLoaded = false;
            $.each(document.getElementsByTagName('link'), function(k, i) {
                if (i.rel == 'stylesheet' && i.href == location.protocol+'//'+location.host+m[1]) {
                    alreadyLoaded = true;
                }
            });
            if (alreadyLoaded) {
                continue;
            }
            se = document.createElement('link');
            se.rel = 'stylesheet';
            se.href = m[1];
        } else {
            var alreadyLoaded = false;
            $.each(document.getElementsByTagName('script'), function(k, i) {
                if (i.src == location.protocol+'//'+location.host+m[1]) {
                    alreadyLoaded = true;
                }
            });
            if (alreadyLoaded) {
                continue;
            }
            se = document.createElement('script');
            se.src = m[1];
        }
        se.type = type;
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(se, s);
    }
}

module.exports = function(html) {
    injectAssets(html, /<link rel="stylesheet" type="text\/css" href="([^"]+)" \/>(?!<!\[endif)/g, 'text/css');
    injectAssets(html, /


<commit_before>var dbConfig = require(__base + 'secret/config-db.json');
var MariaSql = require('mariasql');
var bluebird = require('bluebird');

var TagDB = {
	getTags() {
		const connection = bluebird.promisifyAll(new MariaSql(dbConfig));
		const query = (
			'SELECT DISTINCT t.tag_text AS tag FROM TAGS t ' +
			'JOIN USER_TAGS ut ON t.tag_id = ut.tag_id ' +
			'WHERE ut.user_id = :userId'
		)
		return connection.queryAsync(query, {userId: 1}, {useArray: true}).then(rows => {
			connection.end()
			return rows.map(row => row[0])
		})
	},

	getTagsForMessage(messageId) {
		const connection = bluebird.promisifyAll(new MariaSql(dbConfig));
		const query = (
			'SELECT DISTINCT t.tag_text AS tag FROM TAGS t ' +
			'JOIN LINKS_TAGS lt ON t.tag_id = lt.tag_id ' +
			'JOIN LINKS l ON lt.link_id = l.link_id ' +
			'JOIN MESSAGE m ON l.link_id = m.link_id ' +
			'WHERE m.message_id = :messageId'
		)
		return connection.queryAsync(query, {messageId: messageId}, {useArray: true}).then(rows => {
			console.log(rows)
		})
	},

	addTags(messageId, tags) {
		const connection = bluebird.promisifyAll(new MariaSql(dbConfig));
		console.log(tags)

		const promiseTags = tags.map(tag => {
			// insert tag
			// hook tag to message
			// hook tag to user
			const getTag = "SELECT tag_id FROM TAGS WHERE tag_text = :tagText"
			const insertTag = "INSERT INTO TAGS (tag_text) VALUES (:tagText)"
			const getLink = "SELECT link_id FROM MESSAGE WHERE message_id = :messageId"
			const insertTagLink = "INSERT INTO LINKS_TAGS (link_id, tag_id) VALUES (:linkId, :tagId)"
			const insertTagUser = "INSERT INTO USER_TAGS (user_id, tag_id) VALUES (:userId, :tagId)"

			return connection.queryAsync(insertTag, {tagText: tag}, {useArray: true}).then(() => {
				return connection.lastInsertId()
			}).then(tagId => {
				return connection.queryAsync(getLink, {messageId: messageId}, {useArray: true}).then(rows => {
					if (rows && rows.length) {
						const linkId = rows[0]
						console.log("link rows", rows)
						return {
							tagId: tagId,
							linkId: linkId
						}
					}
					return {}
				})
			}).then(linkAndTag => {
				const link = linkAndTag.linkId
				const tag = linkAndTag.tagId

				console.log(linkAndTag)

				if (link && tag) {
					connection.queryAsync(insertTagLink, {linkId: link, tagId: tag})
					connection.queryAsync(insertTagUser, {userId: 1, tagId: tag})
				}
			})
		})

		return Promise.all(promiseTags).then(() => connection.end())
	}
}

module.exports = function (connection) {
	var tagDB = Object.create(TagDB);
	tagDB._connection = connection;
	return tagDB;
}
<commit_msg>adding tagging<commit_after>var dbConfig = require(__base + 'secret/config-db.json');
var MariaSql = require('mariasql');
var bluebird = require('bluebird');

var TagDB = {
	getTags() {
		const connection = bluebird.promisifyAll(new MariaSql(dbConfig));
		const query = (
			'SELECT DISTINCT t.tag_text AS tag FROM TAGS t ' +
			'JOIN USER_TAGS ut ON t.tag_id = ut.tag_id ' +
			'WHERE ut.user_id = :userId'
		)
		return connection.queryAsync(query, {userId: 1}, {useArray: true}).then(rows => {
			connection.end()
			return rows.map(row => row[0])
		})
	},

	getTagsForMessage(messageId) {
		const connection = bluebird.promisifyAll(new MariaSql(dbConfig));
		const query = (
			'SELECT DISTINCT t.tag_text AS tag FROM TAGS t ' +
			'JOIN LINKS_TAGS lt ON t.tag_id = lt.tag_id ' +
			'JOIN LINKS l ON lt.link_id = l.link_id ' +
			'JOIN MESSAGE m ON l.link_id = m.link_id ' +
			'WHERE m.message_id = :messageId'
		)
		return connection.queryAsync(query, {messageId: messageId}, {useArray: true}).then(rows => {
			connection.end()
			return rows.map(row => row[0]);
		})

	},

	addTags(messageId, tags) {
		const connection = bluebird.promisifyAll(new MariaSql(dbConfig));
		console.log(tags)

		const promiseTags = tags.map(tag => {
			// insert tag
			// hook tag to message
			// hook tag to user
			const getTag = "SELECT tag_id FROM TAGS WHERE tag_text = :tagText"
			const insertTag = "INSERT INTO TAGS (tag_text) VALUES (:tagText)"
			const getLink = "SELECT link_id FROM MESSAGE WHERE message_id = :messageId"
			const insertTagLink = "INSERT INTO LINKS_TAGS (link_id, tag_id) VALUES (:linkId, :tagId)"
			const insertTagUser = "INSERT INTO USER_TAGS (user_id, tag_id) VALUES (:userId, :tagId)"

			return connection.queryAsync(insertTag, {tagText: tag}, {useArray: true}).then(() => {
				return connection.lastInsertId()
			}).then(tagId => {
				return connection.queryAsync(getLink, {messageId: messageId}, {useArray: true}).then(rows => {
					if (rows && rows.length) {
						const linkId = rows[0]
						console.log("link rows", rows)
						return {
							tagId: tagId,
							linkId: linkId
						}
					}
					return {}
				})
			}).then(linkAndTag => {
				const link = linkAndTag.linkId
				const tag = linkAndTag.tagId

				console.log(linkAndTag)

				if (link && tag) {
					connection.queryAsync(insertTagLink, {linkId: link, tagId: tag})
					connection.queryAsync(insertTagUser, {userId: 1, tagId: tag})
				}
			})
		})

		return Promise.all(promiseTags).then(() => connection.end())
	}
}

module.exports = function (connection) {
	var tagDB = Object.create(TagDB);
	tagDB._connection = connection;
	return tagDB;
}
<|endoftext|>


<commit_before>const Redis = require('../redis/Redis');
const UserProfile = require('../postgreSQL/models/UserProfile');

const redis = new Redis();

const UPDATE_DURATION = 30 * 60 * 1000;

setInterval(() => Currency.leaderboard(), UPDATE_DURATION);

redis.db.hgetAsync('money', 'bank').then(balance => {
	if (!balance) redis.db.hsetAsync('money', 'bank', 5000);
});

class Currency {
	static _changeBalance(user, amount) {
		redis.db.hgetAsync('money', user).then(balance => {
			balance = parseInt(balance) || 0;
			redis.db.hsetAsync('money', user, amount + parseInt(balance));
		});
	}

	static changeBalance(user, amount) {
		Currency._changeBalance(user, amount);
		Currency._changeBalance('bank', -amount);
	}

	static addBalance(user, amount) {
		Currency.changeBalance(user, amount);
	}

	static removeBalance(user, amount) {
		Currency.changeBalance(user, -amount);
	}

	static async getBalance(user) {
		const money = await redis.db.hgetAsync('money', user) || 0;

		return parseInt(money);
	}

	static async leaderboard() {
		const balances = await redis.db.hgetallAsync('money') || {};
		const bankBalances = await redis.db.hgetallAsync('ledger') || {};

		const ids = Object.keys(balances || {});

		for (const id of ids) {
			const money = parseInt(balances[id] || 0);
			const balance = parseInt(bankBalances[id] || 0);
			const networth = money + balance;

			const user = await UserProfile.findOne({ where: { userID: id } });
			if (!user) {
				UserProfile.create({
					userID: id,
					money,
					balance,
					networth
				});
			} else {
				user.update({
					money,
					balance,
					networth
				});
			}
		}

		redis.db.setAsync('moneyleaderboardreset', Date.now());
		redis.db.expire('moneyleaderboardreset', UPDATE_DURATION);
	}

	static convert(amount, text = false) {
		if (!text) return `${amount} ${Math.abs(amount) === 1 ? Currency.singular : Currency.plural}`;

		return `${amount} ${Math.abs(amount) === 1 ? Currency.textSingular : Currency.textPlural}`;
	}

	static get singular() {
		return '🍩';
	}

	static get plural() {
		return '🍩s';
	}

	static get textSingular() {
		return 'donut';
	}

	static get textPlural() {
		return 'donuts';
	}
}

module.exports = Currency;
<commit_msg>Pretty numeric formatting for money<commit_after>const Redis = require('../redis/Redis');
const UserProfile = require('../postgreSQL/models/UserProfile');

const redis = new Redis();

const UPDATE_DURATION = 30 * 60 * 1000;

setInterval(() => Currency.leaderboard(), UPDATE_DURATION);

redis.db.hgetAsync('money', 'bank').then(balance => {
	if (!balance) redis.db.hsetAsync('money', 'bank', 5000);
});

class Currency {
	static _changeBalance(user, amount) {
		redis.db.hgetAsync('money', user).then(balance => {
			balance = parseInt(balance) || 0;
			redis.db.hsetAsync('money', user, amount + parseInt(balance));
		});
	}

	static changeBalance(user, amount) {
		Currency._changeBalance(user, amount);
		Currency._changeBalance('bank', -amount);
	}

	static addBalance(user, amount) {
		Currency.changeBalance(user, amount);
	}

	static removeBalance(user, amount) {
		Currency.changeBalance(user, -amount);
	}

	static async getBalance(user) {
		const money = await redis.db.hgetAsync('money', user) || 0;

		return parseInt(money);
	}

	static async leaderboard() {
		const balances = await redis.db.hgetallAsync('money') || {};
		const bankBalances = await redis.db.hgetallAsync('ledger') || {};

		const ids = Object.keys(balances || {});

		for (const id of ids) {
			const money = parseInt(balances[id] || 0);
			const balance = parseInt(bankBalances[id] || 0);
			const networth = money + balance;

			const user = await UserProfile.findOne({ where: { userID: id } });
			if (!user) {
				UserProfile.create({
					userID: id,
					money,
					balance,
					networth
				});
			} else {
				user.update({
					money,
					balance,
					networth
				});
			}
		}

		redis.db.setAsync('moneyleaderboardreset', Date.now());
		redis.db.expire('moneyleaderboardreset', UPDATE_DURATION);
	}

	static convert(amount, text = false) {
		if (!text) return `${amount.toLocaleString()} ${Math.abs(amount) === 1 ? Currency.singular : Currency.plural}`;

		return `${amount.toLocaleString()} ${Math.abs(amount) === 1 ? Currency.textSingular : Currency.textPlural}`;
	}

	static get singular() {
		return '🍩';
	}

	static get plural() {
		return '🍩s';
	}

	static get textSingular() {
		return 'donut';
	}

	static get textPlural() {
		return 'donuts';
	}
}

module.exports = Currency;
<|endoftext|>


<commit_before>/*
 * gulp-espower
 * https://github.com/twada/gulp-espower
 *
 * Copyright (c) 2013-2014 Takuto Wada
 * Licensed under the MIT license.
 */
var es = require('event-stream'),
    espower = require('espower'),
    esprima = require('esprima'),
    escodegen = require('escodegen'),
    merge = require('lodash.merge');

module.exports = function (opt) {
    'use strict';

    function instrument(file, cb) {
        var espowerOptions, jsCode, jsAst, modifiedAst;
        if (file.isNull()) {
            cb(null, file); // pass along
        } else if (file.isStream()) {
            cb(new Error('gulp-espower: Streaming not supported'));
        } else {
            jsCode = file.contents.toString('utf8');
            jsAst = esprima.parse(jsCode, {tolerant: true, loc: true, range: true});
            espowerOptions = merge(merge(espower.defaultOptions(), opt), {
                path: file.path,
                source: jsCode
            });
            modifiedAst = espower(jsAst, espowerOptions);
            file.contents = new Buffer(escodegen.generate(modifiedAst));
            cb(null, file);
        }
    }

    return es.map(instrument);
};
<commit_msg>Update license header.<commit_after>/*
 * gulp-espower - A gulp plugin to apply espower to target files.
 *
 * https://github.com/twada/gulp-espower
 *
 * Copyright (c) 2013-2014 Takuto Wada
 * Licensed under the MIT license.
 *   https://raw.github.com/twada/gulp-espower/master/LICENSE-MIT
 */
var es = require('event-stream'),
    espower = require('espower'),
    esprima = require('esprima'),
    escodegen = require('escodegen'),
    merge = require('lodash.merge');

module.exports = function (opt) {
    'use strict';

    function instrument(file, cb) {
        var espowerOptions, jsCode, jsAst, modifiedAst;
        if (file.isNull()) {
            cb(null, file); // pass along
        } else if (file.isStream()) {
            cb(new Error('gulp-espower: Streaming not supported'));
        } else {
            jsCode = file.contents.toString('utf8');
            jsAst = esprima.parse(jsCode, {tolerant: true, loc: true, range: true});
            espowerOptions = merge(merge(espower.defaultOptions(), opt), {
                path: file.path,
                source: jsCode
            });
            modifiedAst = espower(jsAst, espowerOptions);
            file.contents = new Buffer(escodegen.generate(modifiedAst));
            cb(null, file);
        }
    }

    return es.map(instrument);
};
<|endoftext|>


<commit_before>/* istanbul ignore next */

var Tinkerforge = require('tinkerforge');
var names_array = [
  [
    Tinkerforge.BrickDC.DEVICE_IDENTIFIER,
    Tinkerforge.BrickDC.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickIMU.DEVICE_IDENTIFIER,
    Tinkerforge.BrickIMU.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickMaster.DEVICE_IDENTIFIER,
    Tinkerforge.BrickMaster.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickServo.DEVICE_IDENTIFIER,
    Tinkerforge.BrickServo.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickStepper.DEVICE_IDENTIFIER,
    Tinkerforge.BrickStepper.DEVICE_DISPLAY_NAME
  ],
  // BRICKLET'S
  [
    Tinkerforge.BrickletAccelerometer.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletAccelerometer.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletAmbientLight.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletAmbientLight.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletAmbientLightV2.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletAmbientLightV2.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletAnalogIn.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletAnalogIn.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletAnalogInV2.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletAnalogInV2.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletAnalogOut.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletAnalogOut.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletAnalogOutV2.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletAnalogOutV2.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletBarometer.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletBarometer.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletCAN.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletCAN.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletCO2.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletCO2.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletColor.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletColor.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletCurrent12.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletCurrent12.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletCurrent25.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletCurrent25.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletDistanceIR.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletDistanceIR.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletDistanceUS.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletDistanceUS.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletDualButton.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletDualButton.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletDualRelay.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletDualRelay.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletDustDetector.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletDustDetector.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletGPS.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletGPS.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletHallEffect.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletHallEffect.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletHumidity.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletHumidity.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletIndustrialAnalogOut.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletIndustrialAnalogOut.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletIndustrialDigitalIn4.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletIndustrialDigitalIn4.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletIndustrialDigitalOut4.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletIndustrialDigitalOut4.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletIndustrialDual020mA.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletIndustrialDual020mA.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletIndustrialQuadRelay.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletIndustrialQuadRelay.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletIO16.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletIO16.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletIO4.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletIO4.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletJoystick.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletJoystick.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletLaserRangeFinder.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletLaserRangeFinder.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletLCD16x2.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletLCD16x2.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletLCD20x4.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletLCD20x4.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletLEDStrip.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletLEDStrip.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletLine.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletLine.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletLinearPoti.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletLinearPoti.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletLoadCell.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletLoadCell.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletMoisture.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletMoisture.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletMotionDetector.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletMotionDetector.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletMultiTouch.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletMultiTouch.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletNFCRFID.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletNFCRFID.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletOLED128x64.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletOLED128x64.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletOLED64x48.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletOLED64x48.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletPiezoBuzzer.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletPiezoBuzzer.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletPiezoSpeaker.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletPiezoSpeaker.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletPTC.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletPTC.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletRealTimeClock.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletRealTimeClock.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletRemoteSwitch.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletRemoteSwitch.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletRotaryEncoder.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletRotaryEncoder.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletRotaryPoti.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletRotaryPoti.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletRGBLED.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletRGBLED.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletRS232.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletRS232.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletSegmentDisplay4x7.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletSegmentDisplay4x7.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletSolidStateRelay.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletSolidStateRelay.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletSoundIntensity.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletSoundIntensity.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletTemperature.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletTemperature.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletTemperatureIR.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletTemperatureIR.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletThermocouple.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletThermocouple.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletTilt.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletTilt.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletUVLight.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletUVLight.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletVoltage.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletVoltage.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletVoltageCurrent.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletVoltageCurrent.DEVICE_DISPLAY_NAME
  ]
];

exports.get = function get(deviceIdentifier) {
  var name = "undefined";

  names_array.forEach(function (names) {
    if (parseFloat(deviceIdentifier) == parseFloat(names[0])) {
      name = names[1];
    }
  });

  return name;
};
<commit_msg>improvements<commit_after>/* istanbul ignore next */
var Tinkerforge = require('tinkerforge');
var names_array = [
  [
    Tinkerforge.BrickDC.DEVICE_IDENTIFIER,
    Tinkerforge.BrickDC.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickIMU.DEVICE_IDENTIFIER,
    Tinkerforge.BrickIMU.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickMaster.DEVICE_IDENTIFIER,
    Tinkerforge.BrickMaster.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickServo.DEVICE_IDENTIFIER,
    Tinkerforge.BrickServo.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickStepper.DEVICE_IDENTIFIER,
    Tinkerforge.BrickStepper.DEVICE_DISPLAY_NAME
  ],
  // BRICKLET'S
  [
    Tinkerforge.BrickletAccelerometer.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletAccelerometer.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletAmbientLight.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletAmbientLight.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletAmbientLightV2.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletAmbientLightV2.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletAnalogIn.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletAnalogIn.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletAnalogInV2.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletAnalogInV2.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletAnalogOut.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletAnalogOut.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletAnalogOutV2.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletAnalogOutV2.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletBarometer.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletBarometer.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletCAN.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletCAN.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletCO2.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletCO2.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletColor.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletColor.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletCurrent12.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletCurrent12.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletCurrent25.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletCurrent25.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletDistanceIR.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletDistanceIR.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletDistanceUS.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletDistanceUS.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletDualButton.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletDualButton.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletDualRelay.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletDualRelay.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletDustDetector.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletDustDetector.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletGPS.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletGPS.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletHallEffect.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletHallEffect.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletHumidity.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletHumidity.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletIndustrialAnalogOut.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletIndustrialAnalogOut.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletIndustrialDigitalIn4.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletIndustrialDigitalIn4.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletIndustrialDigitalOut4.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletIndustrialDigitalOut4.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletIndustrialDual020mA.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletIndustrialDual020mA.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletIndustrialQuadRelay.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletIndustrialQuadRelay.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletIO16.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletIO16.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletIO4.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletIO4.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletJoystick.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletJoystick.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletLaserRangeFinder.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletLaserRangeFinder.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletLCD16x2.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletLCD16x2.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletLCD20x4.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletLCD20x4.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletLEDStrip.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletLEDStrip.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletLine.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletLine.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletLinearPoti.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletLinearPoti.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletLoadCell.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletLoadCell.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletMoisture.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletMoisture.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletMotionDetector.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletMotionDetector.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletMultiTouch.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletMultiTouch.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletNFCRFID.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletNFCRFID.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletOLED128x64.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletOLED128x64.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletOLED64x48.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletOLED64x48.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletPiezoBuzzer.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletPiezoBuzzer.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletPiezoSpeaker.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletPiezoSpeaker.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletPTC.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletPTC.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletRealTimeClock.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletRealTimeClock.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletRemoteSwitch.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletRemoteSwitch.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletRotaryEncoder.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletRotaryEncoder.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletRotaryPoti.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletRotaryPoti.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletRGBLED.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletRGBLED.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletRS232.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletRS232.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletSegmentDisplay4x7.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletSegmentDisplay4x7.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletSolidStateRelay.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletSolidStateRelay.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletSoundIntensity.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletSoundIntensity.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletTemperature.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletTemperature.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletTemperatureIR.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletTemperatureIR.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletThermocouple.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletThermocouple.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletTilt.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletTilt.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletUVLight.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletUVLight.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletVoltage.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletVoltage.DEVICE_DISPLAY_NAME
  ],
  [
    Tinkerforge.BrickletVoltageCurrent.DEVICE_IDENTIFIER,
    Tinkerforge.BrickletVoltageCurrent.DEVICE_DISPLAY_NAME
  ]
];

exports.get = function get(deviceIdentifier) {
  function checkName(names) {
    return names[0] === deviceIdentifier;
  }
  return names_array.find(checkName)[1];
};
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var StorySchema = new Schema({
  seedID: ObjectId,
  tweetedBy: String,
  title: String,
  link: String,
  img: String,
  description: String,
  date: { type: Date, default: Date.now },
  keywords: [],
  planted: { type: Boolean, default: false }
});

mongoose.model('Story', StorySchema);
<commit_msg>Changed tweet to an object id reference<commit_after>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var StorySchema = new Schema({
  seedID: ObjectId,
  tweetedId: ObjectId,
  title: String,
  link: String,
  img: String,
  description: String,
  date: { type: Date, default: Date.now },
  keywords: [],
  planted: { type: Boolean, default: false }
});

mongoose.model('Story', StorySchema);
<|endoftext|>


<commit_before>"use strict";
var Connection = require("./lib/connection")
global.pd = console.log.bind(console)

module.exports = (function() {
  var connections = {}

  var adapter = {
    syncable: true,

    defaults: {},

    /**
     * Register A Connection
     *
     * Will open up a new connection using the configuration provided and store the DB
     * object to run commands off of. This creates a new pool for each connection config.
     */
    registerConnection(options, tables, cb) {
      if(!options.identity) return cb(new Error('Connection is missing an identity.'))
      if(connections[options.identity]) return cb(new Error('Connection is already registered.'))

      Connection.connect(options, tables, (err, connection) => {
        if (err) return cb(err)
        connections[options.identity] = connection
        cb()
      })
    },

    /**
     * Fired when a model is unregistered, typically when the server
     * is killed. Useful for tearing-down remaining open connections,
     * etc.
     */
    // Teardown a Connection
    teardown(conn, cb) {
      if (typeof conn === 'function') {
        cb = conn
        conn = null
      }
      if (!conn) {
        connections = {}
        return cb()
      }
      if(!connections[conn]) return cb()
      connections[conn].close(() => {
        delete connections[conn]
      })
      cb()
    },

    /**
     * Native
     *
     * Give access to a native mongo table object for running custom
     * queries.
     */
    native(connectionName, tableName, cb) {
      cb(null, connections[connectionName].tables[tableName].table)
    },

    /**
     * Create
     *
     * Insert a single document into a collection.
     */
    create(connectionName, tableName, data, cb) {
      pd("create", data)
      connections[connectionName].tables[tableName].insert(data, cb)
    },

    /**
     * Create Each
     *
     * Insert an array of documents into a collection.
     */
    createEach: function(connectionName, tableName, data, cb) {
      pd("createEach", data)
      connections[connectionName].tables[tableName].insertEach(data, cb)
    },

    /**
     * Find
     *
     * Find all matching documents in a colletion.
     */
    find(connectionName, tableName, query, cb) {
      pd("find", tableName, query)
      connections[connectionName].tables[tableName].find(query, cb)
    },

    /**
     * Update
     *
     * Update all documents matching a criteria object in a collection.
     */
    update(connectionName, tableName, query, data, cb) {
      pd("update", query, data)
      connections[connectionName].tables[tableName].update(query, data, cb)
    },

    /**
     * Destroy
     *
     * Destroy all documents matching a criteria object in a collection.
     */
    destroy(connectionName, tableName, query, cb) {
      pd("destroy", query)
      connections[connectionName].tables[tableName].destroy(query, cb)
    },

    /**
     * Count
     *
     * Return a count of the number of records matching a criteria.
     */
    count(connectionName, tableName, query, cb) {
      pd("count", query)
      connections[connectionName].tables[tableName].count(query, cb)
    }

    /** TODO
     * Join
     *
     * Peforms a join between 2-3 mongo collections when Waterline core
     * needs to satisfy a `.populate()`.
     */
    //join(connectionName, tableName, criteria, cb) {

    /** TODO
     * Stream
     *
     * Stream one or more documents from the collection
     * using where, limit, skip, and order
     * In where: handle `or`, `and`, and `like` queries
     */
    //stream(connectionName, tableName, query, stream) {

  }

  return adapter
})()
<commit_msg>comment out debug print<commit_after>"use strict";
var Connection = require("./lib/connection")
global.pd = console.log.bind(console)

module.exports = (function() {
  var connections = {}

  var adapter = {
    syncable: true,

    defaults: {},

    /**
     * Register A Connection
     *
     * Will open up a new connection using the configuration provided and store the DB
     * object to run commands off of. This creates a new pool for each connection config.
     */
    registerConnection(options, tables, cb) {
      if(!options.identity) return cb(new Error('Connection is missing an identity.'))
      if(connections[options.identity]) return cb(new Error('Connection is already registered.'))

      Connection.connect(options, tables, (err, connection) => {
        if (err) return cb(err)
        connections[options.identity] = connection
        cb()
      })
    },

    /**
     * Fired when a model is unregistered, typically when the server
     * is killed. Useful for tearing-down remaining open connections,
     * etc.
     */
    // Teardown a Connection
    teardown(conn, cb) {
      if (typeof conn === 'function') {
        cb = conn
        conn = null
      }
      if (!conn) {
        connections = {}
        return cb()
      }
      if(!connections[conn]) return cb()
      connections[conn].close(() => {
        delete connections[conn]
      })
      cb()
    },

    /**
     * Native
     *
     * Give access to a native mongo table object for running custom
     * queries.
     */
    native(connectionName, tableName, cb) {
      cb(null, connections[connectionName].tables[tableName].table)
    },

    /**
     * Create
     *
     * Insert a single document into a collection.
     */
    create(connectionName, tableName, data, cb) {
      //pd("create", data)
      connections[connectionName].tables[tableName].insert(data, cb)
    },

    /**
     * Create Each
     *
     * Insert an array of documents into a collection.
     */
    createEach: function(connectionName, tableName, data, cb) {
      //pd("createEach", data)
      connections[connectionName].tables[tableName].insertEach(data, cb)
    },

    /**
     * Find
     *
     * Find all matching documents in a colletion.
     */
    find(connectionName, tableName, query, cb) {
      //pd("find", tableName, query)
      connections[connectionName].tables[tableName].find(query, cb)
    },

    /**
     * Update
     *
     * Update all documents matching a criteria object in a collection.
     */
    update(connectionName, tableName, query, data, cb) {
      //pd("update", query, data)
      connections[connectionName].tables[tableName].update(query, data, cb)
    },

    /**
     * Destroy
     *
     * Destroy all documents matching a criteria object in a collection.
     */
    destroy(connectionName, tableName, query, cb) {
      //pd("destroy", query)
      connections[connectionName].tables[tableName].destroy(query, cb)
    },

    /**
     * Count
     *
     * Return a count of the number of records matching a criteria.
     */
    count(connectionName, tableName, query, cb) {
      //pd("count", query)
      connections[connectionName].tables[tableName].count(query, cb)
    }

    /** TODO
     * Join
     *
     * Peforms a join between 2-3 mongo collections when Waterline core
     * needs to satisfy a `.populate()`.
     */
    //join(connectionName, tableName, criteria, cb) {

    /** TODO
     * Stream
     *
     * Stream one or more documents from the collection
     * using where, limit, skip, and order
     * In where: handle `or`, `and`, and `like` queries
     */
    //stream(connectionName, tableName, query, stream) {

  }

  return adapter
})()
<|endoftext|>


<commit_before>// The "||" notation doesn't work yet
Fixtures = typeof Fixtures !== "undefined" ? Fixtures : {};

Fixtures.quotes = [
  {
    author: 'Peter Drucker',
    quote: 'What gets measured gets managed.'
  },
  {
    author: 'Tim O\'Reilly',
    quote: 'We\'re entering a new world in which data may be more important than software.'
  },
  {
    author: 'Albert Einstein',
    quote: 'Not everything that can be counted counts,  and not everything that counts can be counted.'
  },
  {
    author: 'Albert Einstein',
    quote: 'As far as the laws of mathematics refer to reality, they are not certain; and as far as they are certain, they do not refer to reality.'
  },
  {
    author: 'Greg Egan',
    quote: 'Widespread caffeine use explains a lot about the twentieth century.'
  },
  {
    author: 'Greg Egan',
    quote: 'How does it feel to be seven thousand years old? That depends on how I want to feel.'
  },
  {
    author: 'Alastair Reynolds',
    quote: 'As the old saying went, the Manhattan Project wasn\'t built in a day. Or was that Rome? Something to do with Earth, anyway.'
  },
  {
    author: 'Alastair Reynolds',
    quote: 'Can we drop the "artificial intelligence"? It’s a bit like me calling you a meat-based processing system.'
  },
  {
    author: 'Frank Herbert',
    quote: 'The mystery of life isn\'t a problem to solve, but a reality to experience.'
  },
  {
    author: 'Frank Herbert',
    quote: 'Fear is the mind-killer.'
  },
  {
    author: 'Arthur C. Clarke',
    quote: 'Any sufficiently advanced technology is indistinguishable from magic.'
  },
  {
    author: 'Richard P. Feynman',
    quote: 'It doesn\'t matter how beautiful your theory is, it doesn\'t matter how smart you are. If it doesn\'t agree with experiment, it\'s wrong.'
  },
  {
    author: 'Leonardo da Vinci',
    quote: 'Simplicity is the ultimate sophistication.'
  },
  {
    author: 'Albert Einstein',
    quote: 'Logic will get you from A to B. Imagination will take you everywhere.'
  },
  {
    author: 'Alfred Whitney Griswold',
    quote: 'The only sure weapon against bad ideas is better ideas.'
  },
  {
    author: 'Dr. Seuss',
    quote: 'Think left and think right and think low and think high. Oh, the thinks you can think up if only you try!'
  }
];
<commit_msg>Update quotes.js<commit_after>// The "||" notation doesn't work yet
Fixtures = typeof Fixtures !== "undefined" ? Fixtures : {};

Fixtures.quotes = [
  {
    author: 'Peter Drucker',
    quote: 'What gets measured gets managed.'
  },
  {
    author: 'Tim O\'Reilly',
    quote: 'We\'re entering a new world in which data may be more important than software.'
  },
  {
    author: 'Albert Einstein',
    quote: 'Not everything that can be counted counts,  and not everything that counts can be counted.'
  },
  {
    author: 'Albert Einstein',
    quote: 'As far as the laws of mathematics refer to reality, they are not certain; and as far as they are certain, they do not refer to reality.'
  },
  {
    author: 'Albert Einstein',
    quote: 'Logic will get you from A to B. Imagination will take you everywhere.'
  },
  {
    author: 'Greg Egan',
    quote: 'Widespread caffeine use explains a lot about the twentieth century.'
  },
  {
    author: 'Greg Egan',
    quote: 'How does it feel to be seven thousand years old? That depends on how I want to feel.'
  },
  {
    author: 'Alastair Reynolds',
    quote: 'As the old saying went, the Manhattan Project wasn\'t built in a day. Or was that Rome? Something to do with Earth, anyway.'
  },
  {
    author: 'Alastair Reynolds',
    quote: 'Can we drop the "artificial intelligence"? It’s a bit like me calling you a meat-based processing system.'
  },
  {
    author: 'Frank Herbert',
    quote: 'The mystery of life isn\'t a problem to solve, but a reality to experience.'
  },
  {
    author: 'Frank Herbert',
    quote: 'Fear is the mind-killer.'
  },
  {
    author: 'Arthur C. Clarke',
    quote: 'Any sufficiently advanced technology is indistinguishable from magic.'
  },
  {
    author: 'Isaac Asimov',
    quote: 'I do not fear computers. I fear the lack of them.'
  }
  {
    author: 'Richard P. Feynman',
    quote: 'It doesn\'t matter how beautiful your theory is, it doesn\'t matter how smart you are. If it doesn\'t agree with experiment, it\'s wrong.'
  },
  {
    author: 'Leonardo da Vinci',
    quote: 'Simplicity is the ultimate sophistication.'
  },
  {
    author: 'Alfred Whitney Griswold',
    quote: 'The only sure weapon against bad ideas is better ideas.'
  },
  {
    author: 'Dr. Seuss',
    quote: 'Think left and think right and think low and think high. Oh, the thinks you can think up if only you try!'
  }
];
<|endoftext|>


<commit_before>

var result = $.ajax("https://osiproghackuc2015.osisoft.com/piwebapi/streams/A0EjSJsJ258_0mQZSscfNuctQ7RK9lpfu5BGAywANOjGGlQ5BDuQVJa7VoiDkXYVGKomATUVSQ1VSWTAwMVxEQVRBQkFTRUhBQ0tHUk9VUDExXEFOQUtJTiBTT0xPXFJVTktFRVBFUnxFTEVWQVRJT04/summary",
	{
		type : 'GET',
		headers: { "Authorization" : "basic " + btoa("osiproghack\\hackuser051:bO2rA53P2")
	}});<commit_msg>getting data!<commit_after>
var activeElements = [];
var sleepElements = [];

$.ajax("https://osiproghackuc2015.osisoft.com/piwebapi/assetdatabases/D0EgxEhIf8KUieOFdFcX1IWQZ8qIGYDdE0m5aJCwNb4x_gSlVQSVRFUjAwMVxQSUZJVE5FU1M/elements", {
		type : 'GET',
		headers: { "Authorization" : "Basic " + btoa("osiproghack\\hackuser051:bO2rA53P2")},
		success: function(results){
			for (var i = 0; i < results.Items.length; i++) {

				var item = results.Items[i];

				getSubElements(item);
			}
		}
	});

var getSubElements = function(personElement){

	$.ajax("https://osiproghackuc2015.osisoft.com/piwebapi/elements/" + personElement.WebId + "/elements", {
		type : 'GET',
		headers: { "Authorization" : "Basic " + btoa("osiproghack\\hackuser051:bO2rA53P2")},
		success: function(results){
			for (var i = 0; i < results.Items.length; i++) {

			var innerItem = results.Items[i];

			if (innerItem.TemplateName == "Fitbit Activity Template") {
				getFitbitActivityAttributes({
					Person : personElement.Name,
					Child : "Fitbit Activity",
					ChildWebId : innerItem.WebId
				});
			} else if (innerItem.TemplateName == "Fitbit Sleep Template") {
				getFitbitSleepAttributes({
					Person : personElement.Name,
					Child : "Fitbit Sleep",
					ChildWebId : innerItem.WebId
				});
			}

		}}});
}

var getFitbitActivityAttributes = function(object) {
	$.ajax("https://osiproghackuc2015.osisoft.com/piwebapi/elements/" + object.ChildWebId + "/attributes",{
		type : 'GET',
		headers: { "Authorization" : "Basic " + btoa("osiproghack\\hackuser051:bO2rA53P2")},
		success: function(results){
			object.Attributes = [];
			activeElements.push(object);
			for (var i = 0; i < results.Items.length; i++) {
				var attribute = results.Items[i];
				getAttributeTotal(object,attribute.Name,attribute.WebId);
			};
		}
	});
}

var getFitbitSleepAttributes = function(object) {
	$.ajax("https://osiproghackuc2015.osisoft.com/piwebapi/elements/" + object.ChildWebId + "/attributes",{
		type : 'GET',
		headers: { "Authorization" : "Basic " + btoa("osiproghack\\hackuser051:bO2rA53P2")},
		success: function(results){
			object.Attributes = [];
			sleepElements.push(object);
			for (var i = 0; i < results.Items.length; i++) {
				var attribute = results.Items[i];
				getAttributeTotal(object,attribute.Name,attribute.WebId);
			};
		}
	});
}

var getAttributeTotal = function(object,attributeName, attributeWebId) {
	$.ajax("https://osiproghackuc2015.osisoft.com/piwebapi/streams/" + attributeWebId + "/summary?starttime=\"2015-1-1\"",{
		type : 'GET',
		headers: { "Authorization" : "Basic " + btoa("osiproghack\\hackuser051:bO2rA53P2")},
		success: function(results){

			for (var i = 0; i <results.Items.length; i++){
				var item = results.Items[i];

				if (item.Type == "Total") {
					object.Attributes.push({
					Attribute : attributeName,
					AttributeWebId : attributeWebId,
					AttributeTotal : item.Value.Value
					})
				}
			}
		}
	});
}

<|endoftext|>


<commit_before>'use strict';

var through = require('through2');
var decomment = require('decomment');
var PluginError = require('gulp-util').PluginError;

function main(options, func) {
    return through.obj(function (file, enc, cb) {
        if (file.isNull()) {
            cb(null, file);
            return;
        }
        if (file.isStream()) {
            cb(new PluginError("gulp-strip-comments", "Streaming not supported."));
        }
        file.contents = new Buffer(func(file.contents.toString(), options));
        this.push(file);
        return cb();
    });
}

function gulpDecomment(options) {
    return main(options, decomment);
}

gulpDecomment.text = function (options) {
    return main(options, decomment.text);
};

gulpDecomment.html = function (options) {
    return main(options, decomment.html);
};

gulpDecomment.trim = function (options) {
    return main(options, decomment.html);
};

gulpDecomment.safe = function (options) {
    return main(options, decomment.html);
};

module.exports = gulpDecomment;
<commit_msg>space<commit_after>'use strict';

var through = require('through2');
var decomment = require('decomment');
var PluginError = require('gulp-util').PluginError;

function main(options, func) {
    return through.obj(function (file, enc, cb) {
        if (file.isNull()) {
            cb(null, file);
            return;
        }
        if (file.isStream()) {
            cb(new PluginError("gulp-strip-comments", "Streaming not supported."));
        }
        file.contents = new Buffer(func(file.contents.toString(), options));
        this.push(file);
        return cb();
    });
}

function gulpDecomment(options) {
    return main(options, decomment);
}

gulpDecomment.text = function (options) {
    return main(options, decomment.text);
};

gulpDecomment.html = function (options) {
    return main(options, decomment.html);
};

gulpDecomment.trim = function (options) {
    return main(options, decomment.html);
};

gulpDecomment.space = function (options) {
    return main(options, decomment.html);
};

gulpDecomment.safe = function (options) {
    return main(options, decomment.html);
};

module.exports = gulpDecomment;
<|endoftext|>


<commit_before>'use strict';
require('dotenv').config();
const rp = require("request-promise");

Number.prototype.toRad = function() {
  return this * Math.PI / 180;
}

Number.prototype.toDeg = function() {
  return this * 180 / Math.PI;
}

// Returns a new lat/lng pair at a specific bearing and distance (radius) from a starting point
function createPointOnRadius(startPoint, bearing, dist) {
  if (!startPoint || typeof bearing !== 'number' || typeof dist !== 'number') {
    return 'Invalid Input(s)';
  }

  dist = dist / 6371;
  bearing = bearing.toRad();
  const lat1 = startPoint.lat.toRad();
  const lng1 = startPoint.lng.toRad();
  const lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) + Math.cos(lat1) * Math.sin(dist) * Math.cos(bearing));
  const lng2 = lng1 + Math.atan2(
                      Math.sin(bearing) * Math.sin(dist) * Math.cos(lat1),
                      Math.cos(dist) - Math.sin(lat1) * Math.sin(lat2)
                    );

  if (isNaN(lat2) || isNaN(lng2)) return null;
  const newLat = lat2.toDeg()
  const newLng = lng2.toDeg()
  return {lat: newLat, lng: newLng};
}

// Accepts a lat/lng pair and checks for closest valid point on land
function reverseGeoCode(geoPoint) {
  if (!geoPoint) {
    return 'Undefined or Null input';
  }
  const baseUrl = 'https://maps.googleapis.com/maps/api/geocode/json';
  const googlekey = process.env.GOOGLE_KEY;
  const lat = geoPoint.lat;
  const lng = geoPoint.lng;
  var options = {
    uri: `${baseUrl}?latlng=${lat},${lng}&key=${googlekey}`,
    headers: {
      'User-Agent': 'Request-Promise'
    },
    json: true
  }
  return rp(options)
          .then((resp) => {
            return resp.results[0].geometry.location;
          })
          .catch((err) => {
            return 'Reversing Geocode Failed';
          })
}

// Accepts a starting lat/lng and generates valid lat/lng coordinates at each bearing
function createGeoRadius(coords) {
  const startPoint = coords.start;
  const radius = .5;  // 1km

  // Creates promiseList array and instantiates with the validated start point
  const promiseList = [reverseGeoCode(createPointOnRadius(startPoint, 0, 0))];
  const bearings = [0, 45, 90, 135, 180, 225, 270, 315];
  // const bearings = [0, 90, 180, 270];
  bearings.forEach((bearing) => {
    let newPoint = createPointOnRadius(startPoint, bearing, radius);
    promiseList.push(reverseGeoCode(newPoint));
  });
  return Promise.all(promiseList);

}

module.exports.createGeoRadius = createGeoRadius;
module.exports.createPointOnRadius = createPointOnRadius;
module.exports.reverseGeoCode = reverseGeoCode;
<commit_msg>[fix] add 'use strict' for Heroku compatibility<commit_after>'use strict';

require('dotenv').config();
const rp = require("request-promise");

Number.prototype.toRad = function() {
  return this * Math.PI / 180;
}

Number.prototype.toDeg = function() {
  return this * 180 / Math.PI;
}

// Returns a new lat/lng pair at a specific bearing and distance (radius) from a starting point
function createPointOnRadius(startPoint, bearing, dist) {
  if (!startPoint || typeof bearing !== 'number' || typeof dist !== 'number') {
    return 'Invalid Input(s)';
  }

  dist = dist / 6371;
  bearing = bearing.toRad();
  const lat1 = startPoint.lat.toRad();
  const lng1 = startPoint.lng.toRad();
  const lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) + Math.cos(lat1) * Math.sin(dist) * Math.cos(bearing));
  const lng2 = lng1 + Math.atan2(
                      Math.sin(bearing) * Math.sin(dist) * Math.cos(lat1),
                      Math.cos(dist) - Math.sin(lat1) * Math.sin(lat2)
                    );

  if (isNaN(lat2) || isNaN(lng2)) return null;
  const newLat = lat2.toDeg()
  const newLng = lng2.toDeg()
  return {lat: newLat, lng: newLng};
}

// Accepts a lat/lng pair and checks for closest valid point on land
function reverseGeoCode(geoPoint) {
  if (!geoPoint) {
    return 'Undefined or Null input';
  }
  const baseUrl = 'https://maps.googleapis.com/maps/api/geocode/json';
  const googlekey = process.env.GOOGLE_KEY;
  const lat = geoPoint.lat;
  const lng = geoPoint.lng;
  var options = {
    uri: `${baseUrl}?latlng=${lat},${lng}&key=${googlekey}`,
    headers: {
      'User-Agent': 'Request-Promise'
    },
    json: true
  }
  return rp(options)
          .then((resp) => {
            return resp.results[0].geometry.location;
          })
          .catch((err) => {
            return 'Reversing Geocode Failed';
          })
}

// Accepts a starting lat/lng and generates valid lat/lng coordinates at each bearing
function createGeoRadius(coords) {
  const startPoint = coords.start;
  const radius = .5;  // 1km

  // Creates promiseList array and instantiates with the validated start point
  const promiseList = [reverseGeoCode(createPointOnRadius(startPoint, 0, 0))];
  const bearings = [0, 45, 90, 135, 180, 225, 270, 315];
  // const bearings = [0, 90, 180, 270];
  bearings.forEach((bearing) => {
    let newPoint = createPointOnRadius(startPoint, bearing, radius);
    promiseList.push(reverseGeoCode(newPoint));
  });
  return Promise.all(promiseList);

}

module.exports.createGeoRadius = createGeoRadius;
module.exports.createPointOnRadius = createPointOnRadius;
module.exports.reverseGeoCode = reverseGeoCode;
<|endoftext|>


<commit_before>var http = require('http');
var webhookHandler = require('github-webhook-handler');

module.exports = (function() {
  function chimneypot(opts) {
    if (!opts || !isOptionsValid(opts)) {
      throw new Error("Required options: port, path, secret");
    }

    this.options = {
      port: opts.port,
      path: opts.path,
      secret: opts.secret
    };

    this.routeCount = 0;
    this.routes = {};
  }

  function isOptionsValid(opts) {
    if (opts.port === undefined || opts.path === undefined || opts.secret === undefined) {
      return false;
    }

    // Non numbers and non-integers
    if (Number(opts.port) !== opts.port || opts.port % 1 !== 0) {
      return false;
    }

    return true;
  }

  function route(path, callback) {
    this.routeCount++;

    if (this.routes[path] === undefined) {
      this.routes[path] = [];
    }

    this.routes[path][this.routes[path].length - 1] = callback;
  }

  function listen() {
    if (this.routeCount === 0) {
      throw new Error("Routes must be applied before listening.");
    }

    var handler = webhookHandler({ path: this.options.path, secret: this.options.secret });

    this.server = http.createServer(function (req, res) {
      handler(req, res, function (err) {
        res.statusCode = 404;
        res.end('no such location');
      });
    });

    this.server.listen(this.options.port, function() {
      console.log("listening on *:" + this.options.port);
    }.bind(this));

    for (var path in this.routes) {
      handler.on(path, this.routes[path]);
    }
  }

  function kill() {
    if (this.server !== undefined) {
      this.server.close();
    }

    this.server = undefined;
    console.log("Server killed");
  }

  chimneypot.prototype = {
    constructor: chimneypot,

    route: route,

    listen: listen,

    kill: kill
  };

  return chimneypot;
})();
<commit_msg>Call all callbacks<commit_after>var http = require('http');
var webhookHandler = require('github-webhook-handler');

module.exports = (function() {
  function chimneypot(opts) {
    if (!opts || !isOptionsValid(opts)) {
      throw new Error("Required options: port, path, secret");
    }

    this.options = {
      port: opts.port,
      path: opts.path,
      secret: opts.secret
    };

    this.routeCount = 0;
    this.routes = {};
  }

  function isOptionsValid(opts) {
    if (opts.port === undefined || opts.path === undefined || opts.secret === undefined) {
      return false;
    }

    // Non numbers and non-integers
    if (Number(opts.port) !== opts.port || opts.port % 1 !== 0) {
      return false;
    }

    return true;
  }

  function route(path, callback) {
    this.routeCount++;

    if (this.routes[path] === undefined) {
      this.routes[path] = [];
    }

    this.routes[path][this.routes[path].length - 1] = callback;
  }

  function listen() {
    if (this.routeCount === 0) {
      throw new Error("Routes must be applied before listening.");
    }

    var handler = webhookHandler({ path: this.options.path, secret: this.options.secret });

    this.server = http.createServer(function (req, res) {
      handler(req, res, function (err) {
        res.statusCode = 404;
        res.end('no such location');
      });
    });

    this.server.listen(this.options.port, function() {
      console.log("listening on *:" + this.options.port);
    }.bind(this));

    for (var path in this.routes) {
      handler.on(path, function(data) {
        for (var c in this.routes[path]) {
          this.routes[path][c](data);
        }
      }.bind(this));
    }
  }

  function kill() {
    if (this.server !== undefined) {
      this.server.close();
    }

    this.server = undefined;
    console.log("Server killed");
  }

  chimneypot.prototype = {
    constructor: chimneypot,

    route: route,

    listen: listen,

    kill: kill
  };

  return chimneypot;
})();
<|endoftext|>


<commit_before>

var apiFilmsBaseUrl = "http://www.myapifilms.com/imdb";
var token = process.env.API_FILMS_TOKEN;

var apiFilmsBaseNameSetting = (
        "&format=JSON" +
        "&filmography=1" +
        "&limit=1" +
        "&lang=en-us" +
        "&exactFilter=0" +
        "&bornDied=0" +
        "&starSign=0" +
        "&uniqueName=0" +
        "&actorActress=0" +
        "&actorTrivia=0" +
        "&actorPhotos=N" +
        "&actorVideos=N" +
        "&salary=1" +
        "&spouses=1" +
        "&tradeMark=0" +
        "&personalQuotes=0" +
        "&starMeter=0"
);

getApiFilmsData = function (actor_name, callback) {
    console.log('actor data');
    url =(apiFilmsBaseUrl
        + "?name="
        + actor_name
        + "&token="
        + token
        + apiFilmsBaseNameSetting);
    var actorNameLower = actor_name.split("+").join("").toLowerCase();
    console.log(url);
    // var checkActor = Actors.find({lowerActorName:actorNameLower}).fetch();
    var checkActor = [];
    console.log(checkActor);
    if(checkActor.length === 0) {
        var request = Meteor.http.get(url);
        request.data.lowerActorName = actorNameLower;
        Actors.insert(request.data);

        var actor = request.data;
    } else {
            var actor = checkActor[0];
    }

    //console.log(actor.filmographies);
    var filmog = actor[0].filmographies
    for(var i=0; i<filmog.length; i++) {
        console.log(filmog[i])
        if (filmog[i].section === "Actor" || filmog[i].section === "Actress") {
            var getMovies = filmog[i].filmography;
            break;
        }
    }

    // var getMovies=actor[0].filmographies[0].filmography;
    //console.log(getMovies);
    var movies=[];

    for (var i=0; i<getMovies.length; i++){
        var movie = getOmdbFilmData(getMovies[i].IMDBId)
        movies.push(movie);
    }
    console.log('Done Getting Movies....');

    if (callback) {
        callback([actor,movies])
    } else {
        return [actor,movies];
    }
};

<commit_msg>api call alteration, changed to meet new standards<commit_after>

var apiFilmsBaseUrl = "http://www.myapifilms.com/imdb/idIMDB";
var token = process.env.API_FILMS_TOKEN;

var apiFilmsBaseNameSetting = (
        "&format=json" +
        "&filmography=1"
        // "&limit=1" +
        // "&lang=en-us" +
        // "&exactFilter=0" +
        // "&bornDied=0" +
        // "&starSign=0" +
        // "&uniqueName=0" +
        // "&actorActress=0" +
        // "&actorTrivia=0" +
        // "&actorPhotos=N" +
        // "&actorVideos=N" +
        // "&salary=1" +
        // "&spouses=1" +
        // "&tradeMark=0" +
        // "&personalQuotes=0" +
        // "&starMeter=0"
);

getApiFilmsData = function (actor_name, callback) {
    console.log('actor data');
    url =(apiFilmsBaseUrl
        + "?name="
        + actor_name
        + "&token="
        + token
        + apiFilmsBaseNameSetting);
    var actorNameLower = actor_name.split("+").join("").toLowerCase();
    var checkActor = Actors.find({lowerActorName: actorNameLower}).fetch();
    if(checkActor.length === 0) {
        var request = Meteor.http.get(url);
        var names = request.data.names;
        names[0].lowerActorName = actorNameLower;
        Actors.insert(names);

        var actor = names;
    } else {
            var actor = checkActor[0];
    }

    //console.log(actor.filmographies);
    var filmog = actor[0].filmographies
    for(var i=0; i<filmog.length; i++) {
        console.log(filmog[i])
        if (filmog[i].section === "Actor" || filmog[i].section === "Actress") {
            var getMovies = filmog[i].filmography;
            break;
        }
    }

    // var getMovies=actor[0].filmographies[0].filmography;
    //console.log(getMovies);
    var movies=[];

    for (var i=0; i<getMovies.length; i++){
        var movie = getOmdbFilmData(getMovies[i].IMDBId)
        movies.push(movie);
    }
    console.log('Done Getting Movies....');

    if (callback) {
        callback([actor,movies])
    } else {
        return [actor,movies];
    }
};

<|endoftext|>


<commit_before>var app = require("application");

exports.actionSnackbar = function(page, snackText, hideDelay, actionText, actionClickFunction) {
    // Just making sure we are on Android for the native approach
    // Will see about finding someone to help with iOS side
    if (app.android) {

        // Make sure user sent actionText and actionClickFunction
        // if undefined then we will pass the page, snackText arguments to the simpleSnackbar() method.
        if (!actionText && !actionClickFunction) {
          exports.simpleSnackbar(page, snackText);
        } else {
              var listener;

             // First, lets create the OnClickListener callback for the Action of the Snackbar
            if (actionClickFunction) {
                listener = new android.view.View.OnClickListener({
                  onClick: actionClickFunction
                });
            }

            // Check for hideDelay, actionText
            if (!hideDelay) {
                hideDelay = 3000;
            };

            if (!actionText) {
                actionText = "";
            };

            // Create the native snackbar
             var snackbar = android.support.design.widget.Snackbar;

            // Last, use the .make(), .setAction() methods to add text and functionality to the snackbar.
            snackbar.make(page.android, text, delay)
                .setAction(actionText, listener)
                .show();

        };

    }
};

// .simpleSnackbar(View page, string snackText) is the simplest method available to construct a native snackbar
exports.simpleSnackbar = function(page, snackText) {

    if (page.android && snackText) {

        // Create the native snackbar
        var snackbar = android.support.design.widget.Snackbar;

        // Now call the snackbar .make() and .show() methods
        snackbar.make(page.android, snackText, 3000)
                .show();

    };
};
<commit_msg>Change comment text<commit_after>var app = require("application");

exports.actionSnackbar = function(page, snackText, hideDelay, actionText, actionClickFunction) {
    // Just making sure we are on Android for the native approach
    // Will see about finding someone to help with iOS side
    if (app.android) {

        // Make sure user sent actionText and actionClickFunction
        // if undefined then we will pass the page, snackText arguments to the simpleSnackbar() method.
        if (!actionText && !actionClickFunction) {
          exports.simpleSnackbar(page, snackText);
        } else {
              var listener;

             // First, lets create the OnClickListener callback for the Action of the Snackbar
            if (actionClickFunction) {
                listener = new android.view.View.OnClickListener({
                  onClick: actionClickFunction
                });
            }

            // Check for hideDelay, actionText
            if (!hideDelay) {
                hideDelay = 3000;
            };

            if (!actionText) {
                actionText = "";
            };

            // Create the native snackbar
             var snackbar = android.support.design.widget.Snackbar;

            // Use the .make(), .setAction() methods to add text and functionality to the snackbar.
            snackbar.make(page.android, text, delay)
                .setAction(actionText, listener)
                .show();

        };

    }
};

// .simpleSnackbar(View page, string snackText) is the simplest method available to construct a native snackbar
exports.simpleSnackbar = function(page, snackText) {

    if (page.android && snackText) {

        // Create the native snackbar
        var snackbar = android.support.design.widget.Snackbar;

        // Now call the snackbar .make() and .show() methods
        snackbar.make(page.android, snackText, 3000)
                .show();

    };
};
<|endoftext|>


<commit_before>;(function (root) {
    var main = function () {
            var gl,
                temp = 0,
                buffer,
                program,
                modelMatrix,
                c = document.getElementById("c"),
                normals = function (v) {
                    var normalize = function (a) {
                            var d = Math.sqrt((a[0]*a[0])+(a[1]*a[1])+(a[2]*a[2]));
                            return [a[0]/d, a[1]/d, a[2]/d];
                        },
                        minus = function (a, b) {
                            return [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
                        },
                        cross = function (a, b) {
                            return [(a[1] * b[2]) - (a[2] * b[1]), -((a[0] * b[2]) - (a[2] * b[0])), (a[0] * b[1]) - (a[1] * b[0])];
                        },
                        b,
                        i,
                        temp,
                        ret = [];
                    for (i = 0; i < 18 * sides; i+=18) {
                        // ret = ret.concat(0,0,1, 0,0,1, 0,0,1);
                        b = v.slice(i+3, i+6);
                        temp = normalize(cross(minus(b, v.slice(i,i+3)), minus(b, v.slice(i+6, i+9))));
                        ret = ret.concat(
                            temp, temp.slice(), temp.slice(),
                            temp.slice(), temp.slice(), temp.slice()
                        );
                    }
                    for (; i < v.length; i+=9) {
                        // ret = ret.concat(0,0,1, 0,0,1, 0,0,1);
                        b = v.slice(i+3, i+6);
                        temp = normalize(cross(minus(b, v.slice(i,i+3)), minus(b, v.slice(i+6, i+9))));
                        ret = ret.concat(temp, temp.slice(), temp.slice());
                    }
                    return ret;
                },
                sides = 200,
                vertices = [];

            for (temp = 0; temp < sides;  temp += 1) {
                vertices.push( Math.cos(temp * 2 * Math.PI / sides), Math.sin(temp * 2 * Math.PI / sides), 0,
                               Math.cos(temp * 2 * Math.PI / sides), Math.sin(temp * 2 * Math.PI / sides), 2,
                               Math.cos((temp + 1) * 2 * Math.PI / sides), Math.sin((temp + 1) * 2 * Math.PI / sides), 2,

                               Math.cos((temp + 1) * 2 * Math.PI / sides), Math.sin((temp + 1) * 2 * Math.PI / sides), 2,
                               Math.cos(temp * 2 * Math.PI / sides), Math.sin(temp * 2 * Math.PI / sides), 0,
                               Math.cos((temp + 1) * 2 * Math.PI / sides), Math.sin((temp + 1) * 2 * Math.PI / sides), 0);
            }
            for (temp = 0; temp < sides;  temp += 1) {
                vertices.push( Math.cos(temp * 2 * Math.PI / sides), Math.sin(temp * 2 * Math.PI / sides), 0,
                               0, 0, 0,
                               Math.cos((temp + 1) * 2 * Math.PI / sides), Math.sin((temp + 1) * 2 * Math.PI / sides), 0);
            }
            for (temp = 0; temp < sides;  temp += 1) {
                vertices.push( Math.cos(temp * 2 * Math.PI / sides), Math.sin(temp * 2 * Math.PI / sides), 2,
                               0, 0, 2,
                               Math.cos((temp + 1) * 2 * Math.PI / sides), Math.sin((temp + 1) * 2 * Math.PI / sides), 2);
            }

            c.width = root.innerWidth;
            c.height = root.innerHeight;
            program = initializeProgram(gl = initializeWebGL(c), initializeShader(gl, "vshader"), initializeShader(gl, "fshader"));
            gl.useProgram(program);
            gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

            gl.vertexAttribPointer(temp = gl.getAttribLocation(program, "aPosition"), 3, gl.FLOAT, !1, 0, 0);
            gl.enableVertexAttribArray(temp);
            gl.bindBuffer(gl.ARRAY_BUFFER, null);
            gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(normals(vertices)), gl.STATIC_DRAW);

            gl.vertexAttribPointer(temp = gl.getAttribLocation(program, "aNormal"), 3, gl.FLOAT, !1, 0, 0);
            gl.enableVertexAttribArray(temp);
            gl.bindBuffer(gl.ARRAY_BUFFER, null);

            temp = -1;
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer = gl.createBuffer());
            gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(Array.apply(0, Array(vertices.length / 3)).map(function () {return temp+=1;})), gl.STATIC_DRAW);
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);

            mat4.rotateY(modelMatrix = mat4.create(), modelMatrix, glMatrix.toRadian(angle));
            mat4.rotateX(modelMatrix, modelMatrix, glMatrix.toRadian(90));
            gl.uniformMatrix4fv(gl.getUniformLocation(program, "uModel"), !1, modelMatrix);

            mat4.invert(temp = mat4.create(), modelMatrix);
            mat4.transpose(temp, temp);
            gl.uniformMatrix4fv(gl.getUniformLocation(program, "uNormal"), !1, temp);

            mat4.lookAt(temp = mat4.create(), [3, 2, 8], [0, -1, 0], [0, 1, 0]);
            gl.uniformMatrix4fv(gl.getUniformLocation(program, "uView"), !1, temp);

            mat4.perspective(temp = mat4.create(), glMatrix.toRadian(zoom == 30 ? zoom : zoom--), c.width / c.height, 1, 100);
            gl.uniformMatrix4fv(gl.getUniformLocation(program, "uProjection"), !1, temp);

			gl.uniform3f(gl.getUniformLocation(program,"uLightDirection"), -1, -2.5, -5);
			gl.uniform3f(gl.getUniformLocation(program,"uEyePosition"), 3 ,3 ,7);
            gl.uniform3f(gl.getUniformLocation(program, "uMaterialDiffuse"), (Math.sin(2 * Math.PI / 2550 * counter) * 127 + 128) / 255, (Math.sin(2 * Math.PI / 2550 * counter + 2) * 127 + 128) / 255, (Math.sin(2 * Math.PI / 2550 * counter + 4) * 127 + 128) / 255);
		  	// gl.uniform3f(gl.getUniformLocation(program,"uMaterialDiffuse"), 0.2, 0.7, 0.2);
			gl.uniform3f(gl.getUniformLocation(program,"uLightDiffuse"), 1, 1, 1);
		  	gl.uniform3f(gl.getUniformLocation(program,"uMaterialAmbient"), 0.2, 0.2, 0.2);
			gl.uniform3f(gl.getUniformLocation(program,"uLightAmbient"), 0.3, 0.3, 0.3);
		  	gl.uniform3f(gl.getUniformLocation(program,"uMaterialSpecular"), 0.9, 1, 0.9);
			gl.uniform3f(gl.getUniformLocation(program,"uLightSpecular"), 1, 1, 1);
			gl.uniform1f(gl.getUniformLocation(program,"uShininess"), 1);
			gl.uniform1i(gl.getUniformLocation(program,"uEnableAmbient"), !0);
			gl.uniform1i(gl.getUniformLocation(program,"uEnableDiffuse"), !0);
			gl.uniform1i(gl.getUniformLocation(program,"uEnableSpecular"), !0);

		  	//draw scene
			gl.clearColor(0, 0, 0, 1);
			gl.enable(gl.DEPTH_TEST);
			gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
			gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer);
			gl.drawElements(gl.TRIANGLES, vertices.length / 3, gl.UNSIGNED_SHORT, 0);
        },
        easing = function (t, b, c, d) {
            t /= d/2;
            if (t < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
            t -= 2;
            return c/2 * (Math.sqrt(1 - t*t) + 1) + b;
        },
        zoom = 30,
        angle = 0,
        counter = 0,
        interval = setInterval(function () {
            angle = easing((counter++%200), angle % 360, 360, 3000);
            main();
        }, 10);

    jarvis.learn([
        ["rotate", function () {
            interval = setInterval(function () {
                angle = easing((counter%200), angle % 360, 360, 3000);
                main();
            }, 10);
        }],
        ["stop", function () {
            clearInterval(interval);
        }]
    ]);
    jarvis.debug = true;
    jarvis.start();

} (this) );
<commit_msg>cylinder: fixed normals<commit_after>;(function (root) {
    var main = function () {
            var gl,
                temp = 0,
                buffer,
                program,
                modelMatrix,
                c = document.getElementById("c"),
                sides = 200,
                vertices = [];

            for (; temp < sides;  temp += 1) {
                vertices.push( Math.cos(temp * 2 * Math.PI / sides), Math.sin(temp * 2 * Math.PI / sides), 0,
                               Math.cos(temp * 2 * Math.PI / sides), Math.sin(temp * 2 * Math.PI / sides), 2,
                               Math.cos((temp + 1) * 2 * Math.PI / sides), Math.sin((temp + 1) * 2 * Math.PI / sides), 2,

                               Math.cos((temp + 1) * 2 * Math.PI / sides), Math.sin((temp + 1) * 2 * Math.PI / sides), 2,
                               Math.cos(temp * 2 * Math.PI / sides), Math.sin(temp * 2 * Math.PI / sides), 0,
                               Math.cos((temp + 1) * 2 * Math.PI / sides), Math.sin((temp + 1) * 2 * Math.PI / sides), 0);
            }

            for (temp = 0; temp < sides;  temp += 1) {
                vertices.push( Math.cos((temp + 1) * 2 * Math.PI / sides), Math.sin((temp + 1) * 2 * Math.PI / sides), 0,
                               0, 0, 0,
                               Math.cos(temp * 2 * Math.PI / sides), Math.sin(temp * 2 * Math.PI / sides), 0
                               );
            }

            for (temp = 0; temp < sides;  temp += 1) {
                vertices.push( Math.cos(temp * 2 * Math.PI / sides), Math.sin(temp * 2 * Math.PI / sides), 2,
                               0, 0, 2,
                               Math.cos((temp + 1) * 2 * Math.PI / sides), Math.sin((temp + 1) * 2 * Math.PI / sides), 2);
            }

            c.width = root.innerWidth;
            c.height = root.innerHeight;
            program = initializeProgram(gl = initializeWebGL(c), initializeShader(gl, "vshader"), initializeShader(gl, "fshader"));
            gl.useProgram(program);
            gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

            gl.vertexAttribPointer(temp = gl.getAttribLocation(program, "aPosition"), 3, gl.FLOAT, !1, 0, 0);
            gl.enableVertexAttribArray(temp);
            gl.bindBuffer(gl.ARRAY_BUFFER, null);
            gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

            gl.vertexAttribPointer(temp = gl.getAttribLocation(program, "aNormal"), 3, gl.FLOAT, !1, 0, 0);
            gl.enableVertexAttribArray(temp);
            gl.bindBuffer(gl.ARRAY_BUFFER, null);

            temp = -1;
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer = gl.createBuffer());
            gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(Array.apply(0, Array(vertices.length / 3)).map(function () {return temp+=1;})), gl.STATIC_DRAW);
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);

            mat4.rotateY(modelMatrix = mat4.create(), modelMatrix, glMatrix.toRadian(angle));
            mat4.rotateX(modelMatrix, modelMatrix, glMatrix.toRadian(-90));
            // mat4.rotateZ(modelMatrix, modelMatrix, glMatrix.toRadian(angle));
            gl.uniformMatrix4fv(gl.getUniformLocation(program, "uModel"), !1, modelMatrix);

            mat4.invert(temp = mat4.create(), modelMatrix);
            mat4.transpose(temp, temp);
            gl.uniformMatrix4fv(gl.getUniformLocation(program, "uNormal"), !1, temp);

            mat4.lookAt(temp = mat4.create(), [3, 5, 8], [0, 1, 0], [0, 1, 0]);
            gl.uniformMatrix4fv(gl.getUniformLocation(program, "uView"), !1, temp);

            mat4.perspective(temp = mat4.create(), glMatrix.toRadian(zoom == 30 ? zoom : zoom--), c.width / c.height, 1, 100);
            gl.uniformMatrix4fv(gl.getUniformLocation(program, "uProjection"), !1, temp);

			gl.uniform3f(gl.getUniformLocation(program,"uLightDirection"), -1, -2.5, -5);
			gl.uniform3f(gl.getUniformLocation(program,"uEyePosition"), 0, 10, 0);
            gl.uniform3f(gl.getUniformLocation(program, "uMaterialDiffuse"), (Math.sin(2 * Math.PI / 2550 * counter) * 127 + 128) / 255, (Math.sin(2 * Math.PI / 2550 * counter + 2) * 127 + 128) / 255, (Math.sin(2 * Math.PI / 2550 * counter + 4) * 127 + 128) / 255);
			gl.uniform3f(gl.getUniformLocation(program,"uLightDiffuse"), 1, 1, 1);
		  	gl.uniform3f(gl.getUniformLocation(program,"uMaterialAmbient"), 0.2, 0.2, 0.2);
			gl.uniform3f(gl.getUniformLocation(program,"uLightAmbient"), 0.3, 0.3, 0.3);
		  	gl.uniform3f(gl.getUniformLocation(program,"uMaterialSpecular"), 0.9, 1, 0.9);
			gl.uniform3f(gl.getUniformLocation(program,"uLightSpecular"), 1, 1, 1);
			gl.uniform1f(gl.getUniformLocation(program,"uShininess"), 10);
			gl.uniform1i(gl.getUniformLocation(program,"uEnableAmbient"), !0);
			gl.uniform1i(gl.getUniformLocation(program,"uEnableDiffuse"), !0);
			gl.uniform1i(gl.getUniformLocation(program,"uEnableSpecular"), !0);

		  	//draw scene
			gl.clearColor(0, 0, 0, 1);
			gl.enable(gl.DEPTH_TEST);
			gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
			gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer);
			gl.drawElements(gl.TRIANGLES, vertices.length / 3, gl.UNSIGNED_SHORT, 0);
        },
        easing = function (t, b, c, d) {
            t /= d/2;
            if (t < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
            t -= 2;
            return c/2 * (Math.sqrt(1 - t*t) + 1) + b;
        },
        zoom = 30,
        angle = 0,
        counter = 0,
        interval = setInterval(function () {
            angle = easing((counter++%200), angle % 360, 360, 3000);
            main();
        }, 10);

    jarvis.learn([
        ["rotate", function () {
            interval = setInterval(function () {
                angle = easing((counter%200), angle % 360, 360, 3000);
                main();
            }, 10);
        }],
        ["stop", function () {
            clearInterval(interval);
        }]
    ]);
    jarvis.debug = true;
    jarvis.start();

} (this) );
<|endoftext|>


<commit_before>var fs = require('fs')
var path = require('path')
var crypto = require('crypto')
var stream = require('readable-stream')
var util = require('util')
var eos = require('end-of-stream')
var os = require('os')
var mkdirp = require('mkdirp')
var thunky = require('thunky')

var noop = function() {}

var SIGNAL_FLUSH = new Buffer([0])

var toPath = function(base, hash) {
  return hash ? path.join(base, hash.slice(0, 2), hash.slice(2)) : base
}

var Writer = function(dir, algo, init) {
  this.key = null
  this.size = 0
  this.destroyed = false

  this._tmp = null
  this._ws = null
  this._directory = dir
  this._digest = crypto.createHash(algo)
  this._init = init

  stream.Writable.call(this)
}

util.inherits(Writer, stream.Writable)

Writer.prototype._flush = function(cb) {
  var self = this
  var hash = this.key = this._digest.digest('hex')
  var dir = path.join(this._directory, hash.slice(0, 2))

  self._ws.end(function() {
    fs.mkdir(dir, function() {
      fs.rename(self._tmp, toPath(self._directory, hash), cb)
    })
  })
}

Writer.prototype._setup = function(data, enc, cb) {
  var self = this
  var destroy = function(err) {
    self.destroy(err)
  }

  this._init(function(dir) {
    if (self.destroyed) return cb(new Error('stream destroyed'))
    self._tmp = path.join(dir, Date.now()+'-'+Math.random().toString().slice(2))
    self._ws = fs.createWriteStream(self._tmp)
    self._ws.on('error', destroy)
    self._ws.on('close', destroy)
    self._write(data, enc, cb)
  })
}

Writer.prototype.destroy = function(err) {
  if (this.destroyed) return
  this.destroyed = true
  if (this._ws) this._ws.destroy()
  if (err) this.emit('error', err)
  this.emit('close')
}

Writer.prototype._write = function(data, enc, cb) {
  if (!this._tmp) return this._setup(data, enc, cb)
  if (data === SIGNAL_FLUSH) return this._flush(cb)
  this.size += data.length
  this._digest.update(data)
  this._ws.write(data, enc, cb)
}

Writer.prototype.end = function(data, enc, cb) {
  if (typeof data === 'function') return this.end(null, null, data)
  if (typeof enc === 'function') return this.end(data, null, enc)
  if (data) this.write(data)
  this.write(SIGNAL_FLUSH)
  stream.Writable.prototype.end.call(this, cb)
}

module.exports = function(opts) {
  if (typeof opts === 'string') opts = {path: opts}
  if (!opts) opts = {}

  var algo = opts.algo
  if (!algo) algo = 'sha256'

  var dir = opts.dir || opts.path
  if (!dir) dir = path.join(process.cwd(), 'blobs')

  var that = {}

  var init = thunky(function(cb) {
    var tmp = path.join(os.tmpDir(), 'cabs')
    mkdirp(tmp, function() {
      mkdirp(dir, function() {
        cb(dir)
      })
    })
  })

  that.createWriteStream = function(opts, cb) {
    if (typeof opts === 'string') opts = {key:opts}
    if (typeof opts === 'function') return that.createWriteStream(null, opts)

    var ws = new Writer(dir, algo, init)
    if (!cb) return ws

    eos(ws, function(err) {
      if (err) return cb(err)
      cb(null, {
        key: ws.key,
        size: ws.size
      })
    })

    return ws
  }

  that.createReadStream = function(opts) {
    if (typeof opts === 'string') opts = {key:opts}
    return fs.createReadStream(toPath(dir, opts.key || opts.hash), opts)
  }

  that.exists = function(opts, cb) {
    if (typeof opts === 'string') opts = {key:opts}
    fs.stat(toPath(dir, opts.key), function(err, stat) {
      if (err && err.code === 'ENOENT') return cb(null, false)
      if (err) return cb(err)
      cb(null, true)
    })
  }

  that.remove = function(opts, cb) {
    if (!cb) cb = noop
    if (typeof opts === 'string') opts = {key:opts}
    fs.unlink(toPath(dir, opts.key), function(err) {
      if (err && err.code === 'ENOENT') return cb(null, false)
      if (err) return cb(err)
      cb(null, true)
    })
  }

  return that
}
<commit_msg>Actually use tmp folder (#11)<commit_after>var fs = require('fs')
var path = require('path')
var crypto = require('crypto')
var stream = require('readable-stream')
var util = require('util')
var eos = require('end-of-stream')
var os = require('os')
var mkdirp = require('mkdirp')
var thunky = require('thunky')

var noop = function() {}

var SIGNAL_FLUSH = new Buffer([0])

var toPath = function(base, hash) {
  return hash ? path.join(base, hash.slice(0, 2), hash.slice(2)) : base
}

var Writer = function(dir, algo, init) {
  this.key = null
  this.size = 0
  this.destroyed = false

  this._tmp = null
  this._ws = null
  this._directory = dir
  this._digest = crypto.createHash(algo)
  this._init = init

  stream.Writable.call(this)
}

util.inherits(Writer, stream.Writable)

Writer.prototype._flush = function(cb) {
  var self = this
  var hash = this.key = this._digest.digest('hex')
  var dir = path.join(this._directory, hash.slice(0, 2))

  self._ws.end(function() {
    fs.mkdir(dir, function() {
      fs.rename(self._tmp, toPath(self._directory, hash), cb)
    })
  })
}

Writer.prototype._setup = function(data, enc, cb) {
  var self = this
  var destroy = function(err) {
    self.destroy(err)
  }

  this._init(function(dir) {
    if (self.destroyed) return cb(new Error('stream destroyed'))
    self._tmp = path.join(dir, Date.now()+'-'+Math.random().toString().slice(2))
    self._ws = fs.createWriteStream(self._tmp)
    self._ws.on('error', destroy)
    self._ws.on('close', destroy)
    self._write(data, enc, cb)
  })
}

Writer.prototype.destroy = function(err) {
  if (this.destroyed) return
  this.destroyed = true
  if (this._ws) this._ws.destroy()
  if (err) this.emit('error', err)
  this.emit('close')
}

Writer.prototype._write = function(data, enc, cb) {
  if (!this._tmp) return this._setup(data, enc, cb)
  if (data === SIGNAL_FLUSH) return this._flush(cb)
  this.size += data.length
  this._digest.update(data)
  this._ws.write(data, enc, cb)
}

Writer.prototype.end = function(data, enc, cb) {
  if (typeof data === 'function') return this.end(null, null, data)
  if (typeof enc === 'function') return this.end(data, null, enc)
  if (data) this.write(data)
  this.write(SIGNAL_FLUSH)
  stream.Writable.prototype.end.call(this, cb)
}

module.exports = function(opts) {
  if (typeof opts === 'string') opts = {path: opts}
  if (!opts) opts = {}

  var algo = opts.algo
  if (!algo) algo = 'sha256'

  var dir = opts.dir || opts.path
  if (!dir) dir = path.join(process.cwd(), 'blobs')

  var that = {}

  var init = thunky(function(cb) {
    var tmp = path.join(os.tmpDir(), 'cabs')
    mkdirp(tmp, function() {
      mkdirp(dir, function() {
        cb(tmp)
      })
    })
  })

  that.createWriteStream = function(opts, cb) {
    if (typeof opts === 'string') opts = {key:opts}
    if (typeof opts === 'function') return that.createWriteStream(null, opts)

    var ws = new Writer(dir, algo, init)
    if (!cb) return ws

    eos(ws, function(err) {
      if (err) return cb(err)
      cb(null, {
        key: ws.key,
        size: ws.size
      })
    })

    return ws
  }

  that.createReadStream = function(opts) {
    if (typeof opts === 'string') opts = {key:opts}
    return fs.createReadStream(toPath(dir, opts.key || opts.hash), opts)
  }

  that.exists = function(opts, cb) {
    if (typeof opts === 'string') opts = {key:opts}
    fs.stat(toPath(dir, opts.key), function(err, stat) {
      if (err && err.code === 'ENOENT') return cb(null, false)
      if (err) return cb(err)
      cb(null, true)
    })
  }

  that.remove = function(opts, cb) {
    if (!cb) cb = noop
    if (typeof opts === 'string') opts = {key:opts}
    fs.unlink(toPath(dir, opts.key), function(err) {
      if (err && err.code === 'ENOENT') return cb(null, false)
      if (err) return cb(err)
      cb(null, true)
    })
  }

  return that
}
<|endoftext|>


<commit_before>module.exports = require('./rowcol.js');<commit_msg>Add missing line break<commit_after>module.exports = require('./rowcol.js');
<|endoftext|>