<commit_before>#! /usr/bin/env node
'use strict';

const program = require('commander');
const spotify = require('spotify-web-api-node');
const prompt = require('prompt');
const parseSearchResults = require('./parsers/');
const printer = require('./printers/');
const spotifyClient = require('./osascripts/');
const nconf = require('nconf');
const path = require('path');
const readlineSync = require('readline-sync');
const fetchLyrics = require('./fetch_lyrics').fetchLyrics;
const version = require('./package.json').version;
const semver = require('semver');
nconf.file(path.join(__dirname, '/config.json'));

// need client access token for genius
let lyricist = require('lyricist/node6');

let GENIUS_API_KEY = nconf.get('GeniusAPIClientKey');
let GENIUS_API_KEY_SET = GENIUS_API_KEY !== 'YOUR_CLIENT_ACCESS_TOKEN_HERE';
if(GENIUS_API_KEY_SET){
	lyricist = new lyricist(GENIUS_API_KEY);
}

let SPOTIFY_CLIENT_ID = nconf.get('spotifyClientID');
let SPOTIFY_CLIENT_ID_SET = SPOTIFY_CLIENT_ID !== 'YOUR_SPOTIFY_CLIENT_ID_HERE';
let SPOTIFY_CLIENT_SECRET = nconf.get('spotifyClientSecret');
let SPOTIFY_CLIENT_SECRET_SET = SPOTIFY_CLIENT_SECRET !== 'YOUR_SPOTIFY_CLIENT_SECRET_HERE';
let spotifyApi = null;

const initSpotifyApi = (client_id, client_secret) => {
	return new spotify({
		clientId : client_id,
		clientSecret : client_secret
	});
};

const setTokens = () => {
	let clientId = readlineSync.question('What is your Spotify Client ID? \n', { hideEchoBack: true });
	let clientSecret = readlineSync.question('What is your Spotify Client Secret? \n', { hideEchoBack: true });
	nconf.set('spotifyClientID', clientId);
	nconf.set('spotifyClientSecret', clientSecret);
	nconf.save();
	printer.printConfig();
};

if(SPOTIFY_CLIENT_ID_SET && SPOTIFY_CLIENT_SECRET_SET) {
	spotifyApi = initSpotifyApi(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET);
}
else {
	setTokens();
	let SPOTIFY_CLIENT_ID = nconf.get('spotifyClientID');
	let SPOTIFY_CLIENT_SECRET = nconf.get('spotifyClientSecret');
	spotifyApi = initSpotifyApi(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET);
}

const SearchOptions = {
	'track': {
		'fn': spotifyApi.searchTracks.bind(spotifyApi),
		'type': 'tracks'
	},
	't': {
		'fn': spotifyApi.searchTracks.bind(spotifyApi),
		'type': 'tracks'
	},
	'artist': {
		'fn': spotifyApi.searchArtists.bind(spotifyApi),
		'type': 'artists'
	},
	'ar': {
		'fn': spotifyApi.searchArtists.bind(spotifyApi),
		'type': 'artists'
	},
	'album': {
		'fn': spotifyApi.searchAlbums.bind(spotifyApi),
		'type': 'albums'
	},
	'al': {
		'fn': spotifyApi.searchAlbums.bind(spotifyApi),
		'type': 'albums'
	},
	'playlist': {
		'fn': spotifyApi.searchPlaylists.bind(spotifyApi),
		'type': 'playlists'
	},
	'p': {
		'fn': spotifyApi.searchPlaylists.bind(spotifyApi),
		'type': 'playlists'
	}
};

program
	.version(version)
	.command('search <type> [query...]')
	.description('Search for a <track (t) | artist (ar) | album (al) | playlist (p) > (searches tracks by default)')
	.alias('s')
	.action((type, query) => {
		// search for tracks by default
		var searchFn = SearchOptions['track'].fn;
		var searchQry = `${type} ${query.join(' ')}`;
		var resultType = SearchOptions['track'].type;

		if (SearchOptions[type]){
			searchFn = SearchOptions[type].fn;
			searchQry = query.join(' ');
			resultType = SearchOptions[type].type;
		}

		// Retrieve an access token.
		spotifyApi.clientCredentialsGrant()
			.then(function(data) {
				spotifyApi.setAccessToken(data.body['access_token']);
				searchFn(searchQry).then((data) => {
					var results = parseSearchResults(resultType, data);
					printer.printSearchResults(resultType, results);
					prompt.start();
					prompt.get(['selection'], function (err, result) {
						if (err) {
							return process.stdout.write('\n');
						}
						if(results[result.selection-1]){
							var selectedSpotifyURI = results[result.selection-1].spotifyURI;
							spotifyClient.play(selectedSpotifyURI).then(() => {
								spotifyClient.status().then((result) => {
									printer.printPlayerStatus(result);
								});
							});
						}
					});
				});
			}, function(err) {
				console.log('Something went wrong when retrieving an access token', err);
			});
	});

program
	.command('info')
	.alias('i')
	.description('Display information about the current track along with player status')
	.action(() => {
		spotifyClient.status().then((result) => {
			printer.printPlayerStatus(result);
		});
	});

program
	.command('play [uri]')
	.description('Continue playing current track or play the track with the provided URI')
	.action((uri) => {
		if(uri){
			spotifyClient.play(uri).then(() => {
				spotifyClient.status().then((result) => {
					printer.printPlayerStatus(result);
				});
			});
		}
		else {
			spotifyClient.play().then(() => {
				spotifyClient.status().then((result) => {
					printer.printPlayerStatus(result);
				});
			});
		}
	});

program
	.command('pause')
	.description('Pause the current track')
	.action(() => {
		spotifyClient.pause().then(() => {
			spotifyClient.status().then((result) => {
				printer.printPlayerStatus(result);
			});
		});
	});

program
	.command('next')
	.alias('n')
	.description('Play the next track in the queue')
	.action(() => {
		spotifyClient.next().then(() => {
			spotifyClient.status().then((result) => {
				printer.printNext(result);
			});
		});
	});

program
	.command('back')
	.alias('b')
	.description('Play the previous track')
	.action(() => {
		spotifyClient.previous().then(() => {
			spotifyClient.status().then((result) => {
				printer.printPrevious(result);
			});
		});
	});

program
	.command('mute')
	.alias('m')
	.description('Mute player')
	.action(() => {
		spotifyClient.mute().then(() => {
			spotifyClient.getVolume().then((result) => {
				printer.printMute(result);
			});
		});
	});

program
	.command('unmute')
	.alias('u')
	.description('Unmute player')
	.action(() => {
		spotifyClient.unmute().then(() => {
			spotifyClient.getVolume().then((result) => {
				printer.printUnmute(result);
			});
		});
	});

program
	.command('volume [newVolume]')
	.alias('v')
	.description('Display player volume')
	.action((newVolume) => {
		if(newVolume){
			spotifyClient.setVolume(newVolume).then(() => {
				spotifyClient.getVolume().then((result) => {
					printer.printSetVolume(result);
				});
			});
		}
		else {
			spotifyClient.getVolume().then(() => {
				spotifyClient.getVolume().then((result) => {
					printer.printVolume(result);
				});
			});
		}
	});
program
	.command('+ [deltaVolume]')
	.description('Turn the volume up by given amount (0-100), default:10')
	.action((deltaVolume) => {
		var changeInVolume = deltaVolume ? deltaVolume : 10;
		spotifyClient.changeVolume(changeInVolume).then(() => {
			spotifyClient.getVolume().then((result) => {
				printer.printVolumeIncrease(changeInVolume, result);
			});
		});
	});

program
	.command('- [deltaVolume]')
	.description('Turn the volume down by given amount (0-100), default:10')
	.action((deltaVolume) => {
		var changeInVolume = deltaVolume ? -deltaVolume : -10 ;
		spotifyClient.changeVolume(changeInVolume).then(() => {
			spotifyClient.getVolume().then((result) => {
				printer.printVolumeDecrease(changeInVolume, result);
			});
		});
	});

program
	.command('p')
	.description('Toggle play/pause')
	.action(() => {
		spotifyClient.togglePlayPause().then(() => {
			spotifyClient.status().then((result) => {
				printer.printPlayerStatus(result);
			});
		});
	});

program
	.command('replay')
	.alias('r')
	.description('Replay current track')
	.action(() => {
		spotifyClient.replay().then(() => {
			spotifyClient.status().then((result) => {
				printer.printPlayerStatus(result);
			});
		});
	});

program
	.command('position [newPosition]')
	.alias('pos')
	.description('Get or set player position [mm:ss], e.g: pos 1:23')
	.action((newPosition) => {
		if(newPosition){
			spotifyClient.setPosition(newPosition).then(() => {
				spotifyClient.status().then((result) => {
					printer.printPlayerStatus(result);
				});
			});
		}
		else {
			spotifyClient.getPosition().then(() => {
				spotifyClient.status().then((result) => {
					printer.printPlayerStatus(result);
				});
			});
		}
	});

program
	.command('quit')
	.alias('q')
	.description('Quit Spotify :(')
	.action(() =>{
		spotifyClient.quit();
	});

program
	.command('open')
	.alias('o')
	.description('Open Spotify :)')
	.action(() =>{
		spotifyClient.start();
	});

program
	.command('shuffle')
	.alias('ts')
	.description('Toggle shuffle on/off')
	.action(() => {
		spotifyClient.shuffle().then((status) => {
			printer.printToggleShuffle(status);
		});
	});

program
	.command('repeat')
	.alias('tr')
	.description('Toggle repeat on/off')
	.action(() => {
		spotifyClient.repeat().then((status) => {
			printer.printToggleRepeat(status);
		});
	});

program
	.command('share [type]')
	.alias('sh')
	.description('Display share <uri|url> and copy value to clipboard')
	.action((type) => {
		spotifyClient.share(type);
	});

program
	.command('token')
	.alias('tk')
	.description('Change Client Spotify tokens')
	.action(() => {
		setTokens();
	});

program
	.command('lyrics')
	.alias('ly')
	.description('Display the lyrics of currently playing track')
	.action(() => {
		spotifyClient.status().then((trackInfo) => {
			if(!GENIUS_API_KEY_SET){
				console.log('You need to set the Client Access Token for Genius API.');
				console.log('Sign up for API access here: https://genius.com/api-clients');
				console.log('Update config.json file with your credentials');
				return;
			}
			fetchLyrics(lyricist, trackInfo.artist, trackInfo.track);
		});
	});

program
	.command('recommend')
	.alias('rec')
	.description('Recommend other songs based on the song currently playing.')
	.action(() => {
		spotifyApi.clientCredentialsGrant()
			.then(function(data) {
				spotifyApi.setAccessToken(data.body['access_token']);
				spotifyClient.getCurrentSongId().then((data) => {
					spotifyApi.getRecommendations({ seed_tracks: [data] }).then((response) => {
						// Assuming Spotify won't start recommending albums, artists, or playlists
						var results = parseSearchResults('tracks', response);
						printer.printSearchResults('tracks', results);
						prompt.start();
						prompt.get(['selection'], function (err, result) {
							if (err) {
								return process.stdout.write('\n');
							}
							if(results[result.selection-1]){
								var selectedSpotifyURI = results[result.selection-1].spotifyURI;
								spotifyClient.play(selectedSpotifyURI).then(() => {
									spotifyClient.status().then((result) => {
										printer.printPlayerStatus(result);
									});
								});
							}
						});
					});
				});
			}, function(err) {
				console.log('Something went wrong when retrieving an access token', err);
			});
	});

program.parse(process.argv);

/* CHECK Installed CLI version
 * */
let publishedVersion = require('child_process').execSync(`npm info spotify-cli-mac version`);
publishedVersion = publishedVersion.toString().trim().replace(/^\n*/, '').replace(/\n*$/, '');
if(semver.lt(version, semver.clean(publishedVersion))){
	console.log(`Your Spotify CLI is outdated. Latest version is ${publishedVersion}, you're on ${version}`);
	console.log(`Reinstall by doing:`);
	console.log(`npm uninstall -g spotify-cli-mac`);
	console.log(`npm install spotify-cli-mac -g\n`);
}
<commit_msg>added commander for playlist.<commit_after>#! /usr/bin/env node
'use strict';

const program = require('commander');
const spotify = require('spotify-web-api-node');
const prompt = require('prompt');
const parseSearchResults = require('./parsers/');
const printer = require('./printers/');
const spotifyClient = require('./osascripts/');
const nconf = require('nconf');
const path = require('path');
const readlineSync = require('readline-sync');
const fetchLyrics = require('./fetch_lyrics').fetchLyrics;
const version = require('./package.json').version;
const semver = require('semver');
nconf.file(path.join(__dirname, '/config.json'));

// need client access token for genius
let lyricist = require('lyricist/node6');

let GENIUS_API_KEY = nconf.get('GeniusAPIClientKey');
let GENIUS_API_KEY_SET = GENIUS_API_KEY !== 'YOUR_CLIENT_ACCESS_TOKEN_HERE';
if(GENIUS_API_KEY_SET){
	lyricist = new lyricist(GENIUS_API_KEY);
}

let SPOTIFY_CLIENT_ID = nconf.get('spotifyClientID');
let SPOTIFY_CLIENT_ID_SET = SPOTIFY_CLIENT_ID !== 'YOUR_SPOTIFY_CLIENT_ID_HERE';
let SPOTIFY_CLIENT_SECRET = nconf.get('spotifyClientSecret');
let SPOTIFY_CLIENT_SECRET_SET = SPOTIFY_CLIENT_SECRET !== 'YOUR_SPOTIFY_CLIENT_SECRET_HERE';
let spotifyApi = null;

const initSpotifyApi = (client_id, client_secret) => {
	return new spotify({
		clientId : client_id,
		clientSecret : client_secret
	});
};

const setTokens = () => {
	let clientId = readlineSync.question('What is your Spotify Client ID? \n', { hideEchoBack: true });
	let clientSecret = readlineSync.question('What is your Spotify Client Secret? \n', { hideEchoBack: true });
	nconf.set('spotifyClientID', clientId);
	nconf.set('spotifyClientSecret', clientSecret);
	nconf.save();
	printer.printConfig();
};

if(SPOTIFY_CLIENT_ID_SET && SPOTIFY_CLIENT_SECRET_SET) {
	spotifyApi = initSpotifyApi(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET);
}
else {
	setTokens();
	let SPOTIFY_CLIENT_ID = nconf.get('spotifyClientID');
	let SPOTIFY_CLIENT_SECRET = nconf.get('spotifyClientSecret');
	spotifyApi = initSpotifyApi(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET);
}

const SearchOptions = {
	'track': {
		'fn': spotifyApi.searchTracks.bind(spotifyApi),
		'type': 'tracks'
	},
	't': {
		'fn': spotifyApi.searchTracks.bind(spotifyApi),
		'type': 'tracks'
	},
	'artist': {
		'fn': spotifyApi.searchArtists.bind(spotifyApi),
		'type': 'artists'
	},
	'ar': {
		'fn': spotifyApi.searchArtists.bind(spotifyApi),
		'type': 'artists'
	},
	'album': {
		'fn': spotifyApi.searchAlbums.bind(spotifyApi),
		'type': 'albums'
	},
	'al': {
		'fn': spotifyApi.searchAlbums.bind(spotifyApi),
		'type': 'albums'
	},
	'playlist': {
		'fn': spotifyApi.searchPlaylists.bind(spotifyApi),
		'type': 'playlists'
	},
	'p': {
		'fn': spotifyApi.searchPlaylists.bind(spotifyApi),
		'type': 'playlists'
	}
};

program
	.version(version)
	.command('search <type> [query...]')
	.description('Search for a <track (t) | artist (ar) | album (al) | playlist (p) > (searches tracks by default)')
	.alias('s')
	.action((type, query) => {
		// search for tracks by default
		var searchFn = SearchOptions['track'].fn;
		var searchQry = `${type} ${query.join(' ')}`;
		var resultType = SearchOptions['track'].type;

		if (SearchOptions[type]){
			searchFn = SearchOptions[type].fn;
			searchQry = query.join(' ');
			resultType = SearchOptions[type].type;
		}

		// Retrieve an access token.
		spotifyApi.clientCredentialsGrant()
			.then(function(data) {
				spotifyApi.setAccessToken(data.body['access_token']);
				searchFn(searchQry).then((data) => {
					var results = parseSearchResults(resultType, data);
					printer.printSearchResults(resultType, results);
					prompt.start();
					prompt.get(['selection'], function (err, result) {
						if (err) {
							return process.stdout.write('\n');
						}
						if(results[result.selection-1]){
							var selectedSpotifyURI = results[result.selection-1].spotifyURI;
							spotifyClient.play(selectedSpotifyURI).then(() => {
								spotifyClient.status().then((result) => {
									printer.printPlayerStatus(result);
								});
							});
						}
					});
				});
			}, function(err) {
				console.log('Something went wrong when retrieving an access token', err);
			});
	});

program
	.command('info')
	.alias('i')
	.description('Display information about the current track along with player status')
	.action(() => {
		spotifyClient.status().then((result) => {
			printer.printPlayerStatus(result);
		});
	});

program
	.command('play [uri]')
	.description('Continue playing current track or play the track with the provided URI')
	.action((uri) => {
		if(uri){
			spotifyClient.play(uri).then(() => {
				spotifyClient.status().then((result) => {
					printer.printPlayerStatus(result);
				});
			});
		}
		else {
			spotifyClient.play().then(() => {
				spotifyClient.status().then((result) => {
					printer.printPlayerStatus(result);
				});
			});
		}
	});

program
	.command('playlist [username]')
	.description('Get all playlist by user')
	.action(username => {
		if (username) {
			spotifyApi.clientCredentialsGrant().then(function(data) {
				spotifyApi.setAccessToken(data.body['access_token']);
				spotifyApi.getUserPlaylists(username)
					.then(function(data) {
						var results = parseSearchResults('playlistsByUser', data);
						printer.printSearchResults('playlists', results);
					},function(err) {
						console.log('Something went wrong!', err);
					});
			});
		}
	});
program
	.command('pause')
	.description('Pause the current track')
	.action(() => {
		spotifyClient.pause().then(() => {
			spotifyClient.status().then((result) => {
				printer.printPlayerStatus(result);
			});
		});
	});

program
	.command('next')
	.alias('n')
	.description('Play the next track in the queue')
	.action(() => {
		spotifyClient.next().then(() => {
			spotifyClient.status().then((result) => {
				printer.printNext(result);
			});
		});
	});

program
	.command('back')
	.alias('b')
	.description('Play the previous track')
	.action(() => {
		spotifyClient.previous().then(() => {
			spotifyClient.status().then((result) => {
				printer.printPrevious(result);
			});
		});
	});

program
	.command('mute')
	.alias('m')
	.description('Mute player')
	.action(() => {
		spotifyClient.mute().then(() => {
			spotifyClient.getVolume().then((result) => {
				printer.printMute(result);
			});
		});
	});

program
	.command('unmute')
	.alias('u')
	.description('Unmute player')
	.action(() => {
		spotifyClient.unmute().then(() => {
			spotifyClient.getVolume().then((result) => {
				printer.printUnmute(result);
			});
		});
	});

program
	.command('volume [newVolume]')
	.alias('v')
	.description('Display player volume')
	.action((newVolume) => {
		if(newVolume){
			spotifyClient.setVolume(newVolume).then(() => {
				spotifyClient.getVolume().then((result) => {
					printer.printSetVolume(result);
				});
			});
		}
		else {
			spotifyClient.getVolume().then(() => {
				spotifyClient.getVolume().then((result) => {
					printer.printVolume(result);
				});
			});
		}
	});
program
	.command('+ [deltaVolume]')
	.description('Turn the volume up by given amount (0-100), default:10')
	.action((deltaVolume) => {
		var changeInVolume = deltaVolume ? deltaVolume : 10;
		spotifyClient.changeVolume(changeInVolume).then(() => {
			spotifyClient.getVolume().then((result) => {
				printer.printVolumeIncrease(changeInVolume, result);
			});
		});
	});

program
	.command('- [deltaVolume]')
	.description('Turn the volume down by given amount (0-100), default:10')
	.action((deltaVolume) => {
		var changeInVolume = deltaVolume ? -deltaVolume : -10 ;
		spotifyClient.changeVolume(changeInVolume).then(() => {
			spotifyClient.getVolume().then((result) => {
				printer.printVolumeDecrease(changeInVolume, result);
			});
		});
	});

program
	.command('p')
	.description('Toggle play/pause')
	.action(() => {
		spotifyClient.togglePlayPause().then(() => {
			spotifyClient.status().then((result) => {
				printer.printPlayerStatus(result);
			});
		});
	});

program
	.command('replay')
	.alias('r')
	.description('Replay current track')
	.action(() => {
		spotifyClient.replay().then(() => {
			spotifyClient.status().then((result) => {
				printer.printPlayerStatus(result);
			});
		});
	});

program
	.command('position [newPosition]')
	.alias('pos')
	.description('Get or set player position [mm:ss], e.g: pos 1:23')
	.action((newPosition) => {
		if(newPosition){
			spotifyClient.setPosition(newPosition).then(() => {
				spotifyClient.status().then((result) => {
					printer.printPlayerStatus(result);
				});
			});
		}
		else {
			spotifyClient.getPosition().then(() => {
				spotifyClient.status().then((result) => {
					printer.printPlayerStatus(result);
				});
			});
		}
	});

program
	.command('quit')
	.alias('q')
	.description('Quit Spotify :(')
	.action(() =>{
		spotifyClient.quit();
	});

program
	.command('open')
	.alias('o')
	.description('Open Spotify :)')
	.action(() =>{
		spotifyClient.start();
	});

program
	.command('shuffle')
	.alias('ts')
	.description('Toggle shuffle on/off')
	.action(() => {
		spotifyClient.shuffle().then((status) => {
			printer.printToggleShuffle(status);
		});
	});

program
	.command('repeat')
	.alias('tr')
	.description('Toggle repeat on/off')
	.action(() => {
		spotifyClient.repeat().then((status) => {
			printer.printToggleRepeat(status);
		});
	});

program
	.command('share [type]')
	.alias('sh')
	.description('Display share <uri|url> and copy value to clipboard')
	.action((type) => {
		spotifyClient.share(type);
	});

program
	.command('token')
	.alias('tk')
	.description('Change Client Spotify tokens')
	.action(() => {
		setTokens();
	});

program
	.command('lyrics')
	.alias('ly')
	.description('Display the lyrics of currently playing track')
	.action(() => {
		spotifyClient.status().then((trackInfo) => {
			if(!GENIUS_API_KEY_SET){
				console.log('You need to set the Client Access Token for Genius API.');
				console.log('Sign up for API access here: https://genius.com/api-clients');
				console.log('Update config.json file with your credentials');
				return;
			}
			fetchLyrics(lyricist, trackInfo.artist, trackInfo.track);
		});
	});

program
	.command('recommend')
	.alias('rec')
	.description('Recommend other songs based on the song currently playing.')
	.action(() => {
		spotifyApi.clientCredentialsGrant()
			.then(function(data) {
				spotifyApi.setAccessToken(data.body['access_token']);
				spotifyClient.getCurrentSongId().then((data) => {
					spotifyApi.getRecommendations({ seed_tracks: [data] }).then((response) => {
						// Assuming Spotify won't start recommending albums, artists, or playlists
						var results = parseSearchResults('tracks', response);
						printer.printSearchResults('tracks', results);
						prompt.start();
						prompt.get(['selection'], function (err, result) {
							if (err) {
								return process.stdout.write('\n');
							}
							if(results[result.selection-1]){
								var selectedSpotifyURI = results[result.selection-1].spotifyURI;
								spotifyClient.play(selectedSpotifyURI).then(() => {
									spotifyClient.status().then((result) => {
										printer.printPlayerStatus(result);
									});
								});
							}
						});
					});
				});
			}, function(err) {
				console.log('Something went wrong when retrieving an access token', err);
			});
	});

program.parse(process.argv);

/* CHECK Installed CLI version
 * */
let publishedVersion = require('child_process').execSync(`npm info spotify-cli-mac version`);
publishedVersion = publishedVersion.toString().trim().replace(/^\n*/, '').replace(/\n*$/, '');
if(semver.lt(version, semver.clean(publishedVersion))){
	console.log(`Your Spotify CLI is outdated. Latest version is ${publishedVersion}, you're on ${version}`);
	console.log(`Reinstall by doing:`);
	console.log(`npm uninstall -g spotify-cli-mac`);
	console.log(`npm install spotify-cli-mac -g\n`);
}
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var pg = require('pg');
var bodyParser = require('body-parser');
// parse urlencoded request bodies into req.body
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());

app.set('port', (process.env.PORT || 5000));

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

/* ######## REST API ######## */

app.get('/', function(request, response) {
  response.send('Hello World!')
});

app.get('/poll', function(request, response) {
	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		client.query('SELECT * FROM poll;', function(err, result) {
			done();
			if (err) {
				console.error(err);
				response.send("Error " + err);
			} else {
				response.send(result.rows);
			}
		});
	});
});

app.get('/poll/:id', function(request, response) {
	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		client.query('SELECT * FROM poll WHERE poll_id='+request.params.id+';', function(err, result) {
			done();
			if (err) {
				console.error(err);
				response.send("Error " + err);
			} else {
				response.send(result.rows);
			}
		});
	});
});

app.post('/poll', function(req, response) {

	// response.send("HERE-- " + req.body);
	// console.log(req.body);

	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		var q = "INSERT INTO poll (creator_id, question) VALUES ('"
		+ req.body.creator_id + "', '" + req.body.question + "');";

		client.query(q, function(err, result) {
			done();
			if (err) {
				console.error(err);
				response.send("Error " + err);
			} else {
				response.send(req.headers + "
-------
" + result.rows);
			}
		});
	});
});

app.get('/test', function(request, response) {
	response.send("TEST 202");
});

app.get('/db', function(request, response) {
	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		client.query('SELECT * FROM test_table', function(err, result) {
			done();
			if (err) {
				console.error(err);
				response.send("Error " + err);
			} else {
				response.send(result.rows);
			}
		});
	});
});

app.listen(app.get('port'), function() {
  console.log("Node app is running at localhost:" + app.get('port'))
});
<commit_msg>POST /poll fixed<commit_after>var express = require('express');
var app = express();
var pg = require('pg');
var bodyParser = require('body-parser');

// parse urlencoded request bodies into req.body
app.use(bodyParser.urlencoded({	extended: true }));
app.use(bodyParser.json());

app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));

/* -------- REST API -------- */

/* ######## DEBUG ######## */

app.get('/api', function(req, res) {
	res.send('Hello World!')
});

app.get('/api/test', function(req, res) {
	res.send("TEST 202");
});

app.get('/api/db', function(req, res) {
	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		var queryString = "SELECT * FROM test_table";

		client.query(queryString, function(err, result) {
			done();
			if (err) {
				console.error(err);
				res.send("Error " + err);
			} else {
				res.send(result.rows);
			}
		});
	});
});

/* ######## POLL ######## */

app.get('/api/poll', function(req, res) {
	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		var queryString = "SELECT * FROM poll";

		client.query(queryString, function(err, result) {
			done();
			if (err) {
				console.error(err);
				res.send("Error " + err);
			} else {
				res.send(result.rows);
			}
		});
	});
});

app.get('/api/poll/:id', function(req, res) {
	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		var queryString = "SELECT * FROM poll WHERE poll_id=" + req.params.id + ";";

		client.query(queryString, function(err, result) {
			done();
			if (err) {
				console.error(err);
				res.send("Error " + err);
			} else {
				res.send(result.rows);
			}
		});
	});
});

app.post('/api/poll', function(req, res) {
	pg.connect(process.env.DATABASE_URL, function(err, client, done) {
		var queryString = "INSERT INTO poll (creator_id, question) VALUES ('"
		+ req.body.creator_id + "', '" + req.body.question + "');";

		client.query(queryString, function(err, result) {
			done();
			if (err) {
				console.error(err);
				res.send("Error " + err);
			} else {
				res.send(result.rows);
			}
		});
	});
});

app.listen(app.get('port'), function() {
	console.log("Node app is running at localhost:" + app.get('port'))
});
<|endoftext|>


<commit_before>/* StreamBuffer - A streaming buffer for Node.js
 * Copyright (c) 2014, Chris Barrick <cbarrick1@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for
 * any purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/// StreamBuffer
/// ==================================================
/// TODO: document

'use strict';

var assert = require('assert');
var DuplexStream = require('stream').Duplex;

var CircularBuffer = require('circular-buffer');

/// new StreamBuffer([options])
/// --------------------------------------------------
/// TODO: document

module.exports = function StreamBuffer(opts) {

	opts = opts || {};
	opts.autoFlush = opts.autoFlush || true;
	opts.encoding = opts.encoding || 'buffer';

	opts.decodeStrings = true;
	opts.objectMode = false;

	validateEncoding(opts.encoding, true);

	var buffer = new CircularBuffer(opts);

	var self = this;

	// validateEncoding(encoding, [allowBuffer])
	// --------------------------------------------------
	// Returns `true` if `encoding` is a known encoding. Otherwise throws a TypeError, like when
	// the Buffer class sees an unknown encoding. If `allowBuffer` is `true` then the string
	// `"buffer"` is allowed as an encoding.

	function validateEncoding(encoding, allowBuffer) {
		if (Buffer.isEncoding(encoding)) return true;
		if (allowBuffer && encoding === 'buffer') return true;
		throw new TypeError('Unknown encoding: ' + encoding);
	}

	// Stream Interface //

	DuplexStream.call(this, opts);
	this._write = _write;
	this._read = _read;

	this.on('finish', flush);

	function _read(n) {
		self.push(buffer.read(n, 'buffer'), opts.encoding);
	}

	function _write(chunk, encoding, callback) {
		assert(chunk instanceof Buffer);
		assert(encoding === 'buffer', 'Expected encoding to be "buffer", received: ' + encoding);
		if (opts.autoFlush && chunk.length + buffer.length >= buffer.size) self.flush();
		buffer.write(chunk);
		process.nextTick(callback);
	}

	// Public Interface //

	this.flush = flush;
	this.setEncoding = setEncoding;

	/// StreamBuffer#flush()
	/// --------------------------------------------------
	/// TODO: document

	function flush() {
		self.push(buffer.read('buffer'), opts.encoding);
	}

	/// StreamBuffer#setEncoding(encoding)
	/// --------------------------------------------------
	/// TODO: document

	function setEncoding(encoding) {
		validateEncoding(encoding);

		// Recode the buffer to the new encoding
		opts.encoding = encoding;
		var newBuffer = new CircularBuffer(opts);
		if (buffer.length > 0) newBuffer.write(buffer.read());
		buffer = newBuffer;

		return DuplexStream.setEncoding.call(self, encoding);
	}

};

module.exports.prototype = Object.create(DuplexStream.prototype);
<commit_msg>:lipstick:<commit_after>// StreamBuffer - A streaming buffer for Node.js
// Copyright (c) 2014, Chris Barrick <cbarrick1@gmail.com>
//
// Permission to use, copy, modify, and/or distribute this software for
// any purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

/// StreamBuffer
/// ==================================================
/// TODO: document

'use strict';

var assert = require('assert');
var DuplexStream = require('stream').Duplex;

var CircularBuffer = require('circular-buffer');

/// new StreamBuffer([options])
/// --------------------------------------------------
/// TODO: document

module.exports = function StreamBuffer(opts) {

	opts = opts || {};
	opts.autoFlush = opts.autoFlush || true;
	opts.encoding = opts.encoding || 'buffer';

	opts.decodeStrings = true;
	opts.objectMode = false;

	validateEncoding(opts.encoding, true);

	var buffer = new CircularBuffer(opts);

	var self = this;

	// validateEncoding(encoding, [allowBuffer])
	// --------------------------------------------------
	// Returns `true` if `encoding` is a known encoding. Otherwise throws a TypeError, like when
	// the Buffer class sees an unknown encoding. If `allowBuffer` is `true` then the string
	// `"buffer"` is allowed as an encoding.

	function validateEncoding(encoding, allowBuffer) {
		if (Buffer.isEncoding(encoding)) return true;
		if (allowBuffer && encoding === 'buffer') return true;
		throw new TypeError('Unknown encoding: ' + encoding);
	}

	// Stream Interface //

	DuplexStream.call(this, opts);
	this._write = _write;
	this._read = _read;

	this.on('finish', flush);

	function _read(n) {
		self.push(buffer.read(n, 'buffer'), opts.encoding);
	}

	function _write(chunk, encoding, callback) {
		assert(chunk instanceof Buffer);
		assert(encoding === 'buffer', 'Expected encoding to be "buffer", received: ' + encoding);
		if (opts.autoFlush && chunk.length + buffer.length >= buffer.size) self.flush();
		buffer.write(chunk);
		process.nextTick(callback);
	}

	// Public Interface //

	this.flush = flush;
	this.setEncoding = setEncoding;

	/// StreamBuffer#flush()
	/// --------------------------------------------------
	/// TODO: document

	function flush() {
		self.push(buffer.read('buffer'), opts.encoding);
	}

	/// StreamBuffer#setEncoding(encoding)
	/// --------------------------------------------------
	/// TODO: document

	function setEncoding(encoding) {
		validateEncoding(encoding);

		// Recode the buffer to the new encoding
		opts.encoding = encoding;
		var newBuffer = new CircularBuffer(opts);
		if (buffer.length > 0) newBuffer.write(buffer.read());
		buffer = newBuffer;

		return DuplexStream.setEncoding.call(self, encoding);
	}

};

module.exports.prototype = Object.create(DuplexStream.prototype);
<|endoftext|>


<commit_before>var repo = require('github-repositories');
var moment = require('moment');
var chalk = require('chalk');

module.exports = function(title) {
    repo(title, function(error, response) {
        response.forEach(function(repo) {
            console.log(chalk.bold.blue(repo.name), chalk.green(moment(repo.created_at).calendar()));
        });
    });
};
<commit_msg>Change to sorted version<commit_after>var repo = require('github-repositories');
var moment = require('moment');
var chalk = require('chalk');

module.exports = function(title, opts) {
    opts = opts || {};
    repo(title, function(error, response) {
        repos = [];
        response.forEach(function(repo) {
            repos.push([repo.name, repo.created_at]);
        });

        result = repos.sort(function(item1, item2){
            if (moment(item1[1]).isBefore(item2[1])) {
                return 1;
            } else {
                return -1;
            }
        });

        result.forEach(function(repo){
            console.log(chalk.bold.green(repo[0]), chalk.bold.blue(moment(repo[1]).calendar()));
        });
    });
};
<|endoftext|>


<commit_before>const postcss = require('postcss');

const pluginName = 'plumber';
const unitRegExp = /^(\d+(?:\.\d+)?)([a-z]{1,4})$/;
const defaults = {
    fontSize: 2,
    gridHeight: '1rem',
    lineHeight: 3,
    leadingTop: 1,
    leadingBottom: 2,
    useBaselineOrigin: false
};

// Converts css property names (including custom properties) to their javascript counterparts e.g.
// font-size -> fontSize
// --grid-height -> gridHeight
const toCamelCase = (value) => {
    return value.replace(/^-+/, '').replace(/-([a-z])/g, (nothing, match) => match.toUpperCase());
};

// Converts javascript property names to their css counterparts e.g.
// fontSize -> font-size
const toKebabCase = (value) => {
    return value.replace(/([A-Z])/g, (match) => '-' + match.toLowerCase());
};

// Round value to the nearest quarter pixel
const round = (value) => Math.round(value * 4) / 4;

const sanitizeParams = (params) => {
    Object.keys(params).forEach(prop => {
        let value = params[prop];
        // separate value and unit
        if (prop === 'gridHeight') {
            const match = unitRegExp.exec(value);
            value = {
                gridHeight: Number(match[1]),
                unit: match[2]
            };
        } else {
            value = Number(value);
        }
        params[prop] = value;
    });

    return params;
};

const generateDeclarations = (values, unit) => {
    let declarations = [];
    Object.keys(values).forEach(prop => {
        // http://stackoverflow.com/a/18358056
        const value = Number(Math.round(values[prop] + 'e+6') + 'e-6');

        declarations.push(
            postcss.decl({
                prop: toKebabCase(prop),
                value: value + (value === 0 ? '' : unit)
            })
        );
    });

    return declarations;
};

const getBaselineCorrection = (lineHeight, fontSize, baseline) => {
    // the distance of the original baseline from the bottom
    const baselineFromBottom = (lineHeight - fontSize) / 2 + fontSize * baseline;
    // the corrected baseline will be on the nearest gridline
    const correctedBaseline = Math.round(baselineFromBottom);
    // the difference between the original and the corrected baseline
    const baselineDifference = correctedBaseline - baselineFromBottom;

    return { correctedBaseline, baselineDifference };
};

module.exports = postcss.plugin(pluginName, (options = {}) => {
    // merge default and passed options
    options = Object.assign(defaults, options);
    return function (css) {
        css.walkAtRules(pluginName, rule => {
            // merge current parameters into options
            let params = Object.assign({}, options);
            rule.walkDecls(decl => {
                params[toCamelCase(decl.prop)] = decl.value;
            });

            // sanitize values
            params = sanitizeParams(params);

            const { baseline } = params;
            const { gridHeight, unit } = params.gridHeight;
            let { fontSize, lineHeight, leadingTop, leadingBottom } = params;
            let marginTop, marginBottom, paddingTop, paddingBottom;

            const { correctedBaseline, baselineDifference } = getBaselineCorrection(
                lineHeight,
                fontSize,
                baseline
            );

            if (params.useBaselineOrigin) {
                // substract the distance of the baseline from the edges
                leadingTop -= (lineHeight - correctedBaseline);
                leadingBottom -= correctedBaseline;
            }

            const shift = baselineDifference < 0 ? 0 : 1;

            fontSize = fontSize * gridHeight;
            lineHeight = lineHeight * gridHeight;
            marginTop = (leadingTop - shift) * gridHeight;
            paddingTop = (shift - baselineDifference) * gridHeight;
            paddingBottom = (1 - shift + baselineDifference) * gridHeight;
            marginBottom = (leadingBottom + shift - 1) * gridHeight;

            let computedValues = {
                lineHeight,
                marginTop,
                paddingTop,
                paddingBottom,
                marginBottom
            };

            if (unit === 'px') {
                Object.keys(computedValues).forEach(function (prop) {
                    computedValues[prop] = round(computedValues[prop]);
                });
            }

            Object.assign(computedValues, { fontSize });

            rule.replaceWith(generateDeclarations(computedValues, unit));
        });
    };
});
<commit_msg>useBaselineOrigin accepts 0 or 1 for now<commit_after>const postcss = require('postcss');

const pluginName = 'plumber';
const unitRegExp = /^(\d+(?:\.\d+)?)([a-z]{1,4})$/;
const defaults = {
    fontSize: 2,
    gridHeight: '1rem',
    lineHeight: 3,
    leadingTop: 1,
    leadingBottom: 2,
    useBaselineOrigin: 0
};

// Converts css property names (including custom properties) to their javascript counterparts e.g.
// font-size -> fontSize
// --grid-height -> gridHeight
const toCamelCase = (value) => {
    return value.replace(/^-+/, '').replace(/-([a-z])/g, (nothing, match) => match.toUpperCase());
};

// Converts javascript property names to their css counterparts e.g.
// fontSize -> font-size
const toKebabCase = (value) => {
    return value.replace(/([A-Z])/g, (match) => '-' + match.toLowerCase());
};

// Round value to the nearest quarter pixel
const round = (value) => Math.round(value * 4) / 4;

const sanitizeParams = (params) => {
    Object.keys(params).forEach(prop => {
        let value = params[prop];
        // separate value and unit
        if (prop === 'gridHeight') {
            const match = unitRegExp.exec(value);
            value = {
                gridHeight: Number(match[1]),
                unit: match[2]
            };
        } else {
            value = Number(value);
        }
        params[prop] = value;
    });

    return params;
};

const generateDeclarations = (values, unit) => {
    let declarations = [];
    Object.keys(values).forEach(prop => {
        // http://stackoverflow.com/a/18358056
        const value = Number(Math.round(values[prop] + 'e+6') + 'e-6');

        declarations.push(
            postcss.decl({
                prop: toKebabCase(prop),
                value: value + (value === 0 ? '' : unit)
            })
        );
    });

    return declarations;
};

const getBaselineCorrection = (lineHeight, fontSize, baseline) => {
    // the distance of the original baseline from the bottom
    const baselineFromBottom = (lineHeight - fontSize) / 2 + fontSize * baseline;
    // the corrected baseline will be on the nearest gridline
    const correctedBaseline = Math.round(baselineFromBottom);
    // the difference between the original and the corrected baseline
    const baselineDifference = correctedBaseline - baselineFromBottom;

    return { correctedBaseline, baselineDifference };
};

module.exports = postcss.plugin(pluginName, (options = {}) => {
    // merge default and passed options
    // todo validate passed options
    options = Object.assign(defaults, options);
    return function (css) {
        css.walkAtRules(pluginName, rule => {
            // merge current parameters into options
            let params = Object.assign({}, options);
            rule.walkDecls(decl => {
                // todo validate params
                params[toCamelCase(decl.prop)] = decl.value;
            });

            // sanitize values
            params = sanitizeParams(params);

            const { baseline } = params;
            const { gridHeight, unit } = params.gridHeight;
            let { fontSize, lineHeight, leadingTop, leadingBottom } = params;
            let marginTop, marginBottom, paddingTop, paddingBottom;

            const { correctedBaseline, baselineDifference } = getBaselineCorrection(
                lineHeight,
                fontSize,
                baseline
            );

            if (params.useBaselineOrigin) {
                // substract the distance of the baseline from the edges
                leadingTop -= (lineHeight - correctedBaseline);
                leadingBottom -= correctedBaseline;
            }

            const shift = baselineDifference < 0 ? 0 : 1;

            fontSize = fontSize * gridHeight;
            lineHeight = lineHeight * gridHeight;
            marginTop = (leadingTop - shift) * gridHeight;
            paddingTop = (shift - baselineDifference) * gridHeight;
            paddingBottom = (1 - shift + baselineDifference) * gridHeight;
            marginBottom = (leadingBottom + shift - 1) * gridHeight;

            let computedValues = {
                lineHeight,
                marginTop,
                paddingTop,
                paddingBottom,
                marginBottom
            };

            if (unit === 'px') {
                Object.keys(computedValues).forEach(function (prop) {
                    computedValues[prop] = round(computedValues[prop]);
                });
            }

            Object.assign(computedValues, { fontSize });

            rule.replaceWith(generateDeclarations(computedValues, unit));
        });
    };
});
<|endoftext|>


<commit_before>var colors = ["blue", "red"];

function feld20er (num1, num2) {
  // started with paste from
  // http://www.html5canvastutorials.com/tutorials/html5-canvas-circles/
  var canvas = document.createElement('canvas');
  canvas.id = 'ZahlenfelderPlot' + num1 + num2;
  var space =  window.outerWidth / 13;
  var step = space / 12;
  var radius = step * 4.5;
  var distance = step * 5;
  canvas.width = window.outerWidth;
  canvas.height = space * 2 ;
  document.querySelector('body').appendChild(document.createElement('p'));
  document.querySelector('body').appendChild(document.createElement('hr'));
  document.querySelector('body').appendChild(canvas);
  // var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  for (var i = 0; i < 20; i ++) {
    var centerX =  distance + (i % 10) * space;
    if ((i % 10) > 4) {
      centerX += step * 2;
    }
    var centerY = distance;
    if (i > 9) {
      centerY += step * 11;
    }

    context.beginPath();
    context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
    if (i < num1) {
      context.fillStyle = colors[0];
      context.fill();
    } else if (i < num1 + num2) {
      context.fillStyle = colors[1];
      context.fill();
    }
    context.lineWidth = step / 2;
    context.strokeStyle = '#003300';
    context.stroke();
  }
}

document.body.innerHTML = '';

function rand(limit) {
  return Math.floor(Math.random() * limit);
}

function feld20Zahl (num) {
  if (! num) {
    num = rand(21);
  }
  feld20er(num);
};

function feld20Plus (num1, num2) {
  if (! num1) {
    num1 = rand(10);
  }

  if (num1 < 20) {
    num2 = num1 + rand(11);
  };

  feld20er(num1, num2);
};

for (var i = 0; i < 7; i++) {
  var zahlen = [8, 9, 14, 11, 15, 17, 18];
  feld20Zahl(zahlen[i]);
};

for (var i = 0; i < 11; i++) {
  feld20Plus();
};
<commit_msg>Drucke alle Zahlen von 1-19 und danach 18 zufällige Additionen<commit_after>var colors = ["blue", "red"];

function feld20er (num1, num2) {
  // started with paste from
  // http://www.html5canvastutorials.com/tutorials/html5-canvas-circles/
  var canvas = document.createElement('canvas');
  canvas.id = 'ZahlenfelderPlot' + num1 + num2;
  var space =  window.outerWidth / 13;
  var step = space / 12;
  var radius = step * 4.5;
  var distance = step * 5;
  canvas.width = window.outerWidth;
  canvas.height = space * 2 ;
  document.querySelector('body').appendChild(document.createElement('p'));
  document.querySelector('body').appendChild(document.createElement('hr'));
  document.querySelector('body').appendChild(canvas);
  // var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  for (var i = 0; i < 20; i ++) {
    var centerX =  distance + (i % 10) * space;
    if ((i % 10) > 4) {
      centerX += step * 2;
    }
    var centerY = distance;
    if (i > 9) {
      centerY += step * 11;
    }

    context.beginPath();
    context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
    if (i < num1) {
      context.fillStyle = colors[0];
      context.fill();
    } else if (i < num1 + num2) {
      context.fillStyle = colors[1];
      context.fill();
    }
    context.lineWidth = step / 2;
    context.strokeStyle = '#003300';
    context.stroke();
  }
}

document.body.innerHTML = '';

function rand(limit) {
  return Math.floor(Math.random() * limit);
}

function feld20Zahl (num) {
  if (! num) {
    num = rand(21);
  }
  feld20er(num);
};

function feld20Plus (num1, num2) {
  if (! num1) {
    num1 = rand(9) + 1;
  }

  if (num1 < 20) {
    num2 = num1 + rand(10) + 1;
  };

  feld20er(num1, num2);
};

for (var i = 1; i < 20; i++) {
  feld20Zahl(i);
};

for (var i = 0; i < 18; i++) {
  feld20Plus();
};
<|endoftext|>


<commit_before>
function indexPathOf(arr, item) {

  for (var i = 0, l = arr.length; i < l; i++) {

    if (!Array.isArray(arr[i])) {
      if (arr[i] == item) {
        return [i];
       }
    }
    else {
      var result = indexPathOf(arr[i], item);
      if (result.length > 0) {
        var results = [];
        results.push(i);
        result.forEach(function (e) {
          results.push(e);
        });
        return results;
      }
    }

  }

  return -1;
}

function indexPathsOf(arr, item) {

  var results = [];

  for (var i = 0, l = arr.length; i < l; i++) {
    if (!Array.isArray(arr[i])) {
      if (arr[i] == item) {
        results.push([i]);
      }
    }
    else {

      for (var j = 0, jl = arr[i].length; j < jl; j++) {
        if (!Array.isArray(arr[i][j])) {
          if (arr[i][j] == item) {
            results.push([i, j]);
          }
        }
        else {

          var result = indexPathsOf(arr[i][j], item);

          if (result.length) {
            result.forEach(function (e) {

              results.push([i, j]);

              e.forEach(function (ee) {
                results[results.length - 1].push(ee);
              });

            });
          }

        }

      }

    }

  }

  if (!results.length) {
    return -1;
  }

  return results;
}

function indexesOf(arr, item) {

  var results = [];

  for (var i = 0; i < arr.length; i++) {
    if (arr[i] == item) results.push(i);
  }

  if (!results.length) return -1;

  return results;
}

module.exports.indexPathOf = indexPathOf;
module.exports.indexPathsOf = indexPathsOf;
module.exports.indexesOf = indexesOf;
<commit_msg>added setIndexPathOf<commit_after>
function indexPathOf(arr, item) {

  for (var i = 0, l = arr.length; i < l; i++) {

    if (!Array.isArray(arr[i])) {
      if (arr[i] == item) {
        return [i];
       }
    }
    else {
      var result = indexPathOf(arr[i], item);
      if (result.length > 0) {
        var results = [];
        results.push(i);
        result.forEach(function (e) {
          results.push(e);
        });
        return results;
      }
    }

  }

  return -1;
}

function indexPathsOf(arr, item) {

  var results = [];

  for (var i = 0, l = arr.length; i < l; i++) {
    if (!Array.isArray(arr[i])) {
      if (arr[i] == item) {
        results.push([i]);
      }
    }
    else {

      for (var j = 0, jl = arr[i].length; j < jl; j++) {
        if (!Array.isArray(arr[i][j])) {
          if (arr[i][j] == item) {
            results.push([i, j]);
          }
        }
        else {

          var result = indexPathsOf(arr[i][j], item);

          if (result.length) {
            result.forEach(function (e) {

              results.push([i, j]);

              e.forEach(function (ee) {
                results[results.length - 1].push(ee);
              });

            });
          }

        }

      }

    }

  }

  if (!results.length) {
    return -1;
  }

  return results;
}

function indexesOf(arr, item) {

  var results = [];

  for (var i = 0; i < arr.length; i++) {
    if (arr[i] == item) results.push(i);
  }

  if (!results.length) return -1;

  return results;
}

function setIndexPathOf(arr, path, item) {

  for (var i = 0, l = path.length - 1; i < l; i++) {
    arr = arr[path[i]];
  }

  arr[path[path.length - 1]] = item;

}

module.exports.indexPathOf = indexPathOf;
module.exports.indexPathsOf = indexPathsOf;
module.exports.indexesOf = indexesOf;
module.exports.setIndexPathOf = setIndexPathOf;
<|endoftext|>


<commit_before>'use strict';
var through2 = require('through2'),
    inquirer = require('inquirer'),
    gutil = require('gulp-util'),
    diff = require('diff'),
    fs = require('fs'),
    path = require('path'),
    pkg = require('./package');

var choices = [
  {
    key: 'y',
    name: 'replace',
    value: 'replace'
  }, {
    key: 'n',
    name: 'do not replace',
    value: 'skip'
  }, {
    key: 'a',
    name: 'replace this and all others',
    value: 'replaceAll'
  }, {
    key: 's',
    name: 'skip this and all others',
    value: 'skipAll'
  }, {
    key: 'x',
    name: 'abort',
    value: 'end'
  }, {
    key: 'd',
    name: 'show the differences between the old and the new',
    value: 'diff'
  }
];

module.exports = function conflict (dest, opt) {
  if (!dest) {
    error('Missing destination dir parameter!');
  }

  opt = opt || {};

  var replaceAll = opt.replaceAll || false;
  var skipAll = opt.skipAll || false;
  var defaultChoice = opt.defaultChoice || null;

  var defaultChoiceIndex = null;

  choices.forEach(function(choice, index) {
    if (choice.key === defaultChoice) {
      defaultChoiceIndex = index;
    }
  });
  var logger = opt.logger || log;

  return through2.obj(function (file, enc, cb) {
    var newPath = path.resolve(opt.cwd || process.cwd(), dest, file.relative);
    fs.stat(newPath, function (err, stat) {
      if (!replaceAll && stat && !stat.isDirectory()) {
        fs.readFile(newPath, 'utf8', function (err, contents) {
          if (err) {
            error('Reading old file for comparison failed with: ' + err.message);
          }
          if (contents === String(file.contents)) {
            logFile({
              message: 'Skipping',
              file: file,
              stat: stat,
              extraText: '(identical)',
              logger: logger
            });
            return cb();
          }

          if (skipAll) {
            logFile({
              message: 'Skipping',
              file: file,
              stat: stat,
              logger: logger
            });
            return cb();
          }

          var askCb = function askCb (action) {
            switch (action) {
              case 'replaceAll':
                replaceAll = true;
                /* falls through */
              case 'replace':
                logFile({
                  message: 'Overwriting',
                  file: file,
                  stat: stat,
                  logger: logger
                });
                this.push(file);
                break;
              case 'skipAll':
                skipAll = true;
                /* falls through */
              case 'skip':
                logFile({
                  message: 'Skipping',
                  file: file,
                  stat: stat,
                  logger: logger
                });
                break;
              case 'end':
                log(gutil.colors.red('Aborting...'));
                process.exit(0);
                break;
              case 'diff':
                logFile({
                  message: 'Showing diff for',
                  file: file,
                  stat: stat,
                  logger: logger
                });
                diffFiles(file, newPath);
                ask(file, defaultChoiceIndex, askCb.bind(this));
                return;
            }
            cb();
          };
          ask(file, defaultChoiceIndex, askCb.bind(this));
        }.bind(this));
      } else {
        logFile({
          message: 'Creating',
          file: file,
          stat: stat,
          logger: logger
        });
        this.push(file);
        cb();
      }
    }.bind(this));
  });
};

function ask (file, defaultChoiceIndex, cb) {

  inquirer.prompt([{
    type: 'expand',
    name: 'replace',
    message: 'Replace ' + file.relative + '?',
    default: defaultChoiceIndex,
    choices: choices
  }],
  function (answers) {
    cb(answers.replace);
  });
}

function diffFiles (newFile, oldFilePath) {
  if (newFile.isStream()) {
    error('Diff does not support file streams');
  }
  try {
    var content = fs.readFileSync(oldFilePath, 'utf8');
    var differences = diff.diffLines(content, String(newFile.contents));
    log('File differences: ' + gutil.colors.bgGreen('added') + ' ' + gutil.colors.bgRed('removed') + '\n\n' + differences.map(formatPart).join(''));
  } catch (err) {
    error('Reading old file for diff failed with: ' + err.message);
  }
}

function formatPart (part, i) {
  var indent = new Array(8).join(' ');
  return (!i ? indent : '') + part.value.split('\n').map(function (line) {
    return gutil.colors[colorFromPart(part)](line);
  }).join('\n' + indent);
}

function colorFromPart (part) {
  if (part.added) {
    return 'bgGreen';
  } else if (part.removed) {
    return 'bgRed';
  }
  return 'grey';
}

/*
 * Args: message, file, stat, extraText
 */
function logFile(options){
  var message   = options.message,
      file      = options.file,
      stat      = options.stat,
      extraText = options.extraText,
      logger    = options.logger;

  if (!file || !file.relative || (stat && stat.isDirectory())) {
    return;
  }
  var fileName = gutil.colors.magenta(file.relative);
  if (extraText) {
    logger(message, fileName, extraText);
  } else {
    logger(message, fileName);
  }
}

function log () {
  if (isTest()) {
    return;
  }
  var logger = gutil.log.bind(gutil, '[' + gutil.colors.cyan('conflict') + ']');
  logger.apply(logger, arguments);
}

function error (message) {
  throw new gutil.PluginError(pkg.name, message);
}

function isTest () {
  return process.env.NODE_ENV === 'test';
}

<commit_msg>- leveraging a fork of gulp-conflict to better control what log messages are displayed, only displaying those that actually come into conflict vs every file<commit_after>'use strict';
var through2 = require('through2'),
    inquirer = require('inquirer'),
    gutil    = require('gulp-util'),
    diff     = require('diff'),
    fs       = require('fs'),
    path     = require('path'),
    pkg      = require('./package');

var choices = [
  {
    key: 'y',
    name: 'replace',
    value: 'replace'
  }, {
    key: 'n',
    name: 'do not replace',
    value: 'skip'
  }, {
    key: 'a',
    name: 'replace this and all others',
    value: 'replaceAll'
  }, {
    key: 's',
    name: 'skip this and all others',
    value: 'skipAll'
  }, {
    key: 'x',
    name: 'abort',
    value: 'end'
  }, {
    key: 'd',
    name: 'show the differences between the old and the new',
    value: 'diff'
  }
];

var logLevels = {
  normal: 'normal',
  lite: 'lite'
};

module.exports = function conflict(dest, opt) {
  if (!dest) {
    error('Missing destination dir parameter!');
  }

  opt = opt || {};

  var replaceAll = opt.replaceAll || false;
  var skipAll = opt.skipAll || false;
  var defaultChoice = opt.defaultChoice || null;
  var logLevel = opt.logLevel || logLevels.normal;

  var defaultChoiceIndex = null;

  choices.forEach(function (choice, index) {
    if (choice.key === defaultChoice) {
      defaultChoiceIndex = index;
    }
  });
  var logger = opt.logger || log;

  return through2.obj(function (file, enc, cb) {
    var newPath = path.resolve(opt.cwd || process.cwd(), dest, file.relative);
    fs.stat(newPath, function (err, stat) {
      if (!replaceAll && stat && !stat.isDirectory()) {
        fs.readFile(newPath, 'utf8', function (err, contents) {
          if (err) {
            error('Reading old file for comparison failed with: ' + err.message);
          }
          if (contents === String(file.contents)) {
            if (logLevel === logLevels.normal) {
              logFile({
                message: 'Skipping',
                file: file,
                stat: stat,
                extraText: '(identical)',
                logger: logger
              });
            }
            return cb();
          }

          if (skipAll) {
            if (logLevel === logLevels.normal) {
              logFile({
                message: 'Skipping',
                file: file,
                stat: stat,
                logger: logger
              });
            }
            return cb();
          }

          var askCb = function askCb(action) {
            switch (action) {
              case 'replaceAll':
                replaceAll = true;
              /* falls through */
              case 'replace':
                logFile({
                  message: 'Overwriting',
                  file: file,
                  stat: stat,
                  logger: logger
                });
                this.push(file);
                break;
              case 'skipAll':
                skipAll = true;
              /* falls through */
              case 'skip':
                logFile({
                  message: 'Skipping',
                  file: file,
                  stat: stat,
                  logger: logger
                });
                break;
              case 'end':
                log(gutil.colors.red('Aborting...'));
                process.exit(0);
                break;
              case 'diff':
                logFile({
                  message: 'Showing diff for',
                  file: file,
                  stat: stat,
                  logger: logger
                });
                diffFiles(file, newPath);
                ask(file, defaultChoiceIndex, askCb.bind(this));
                return;
            }
            cb();
          };
          ask(file, defaultChoiceIndex, askCb.bind(this));
        }.bind(this));
      } else {
        if (logLevel === logLevels.normal) {
          logFile({
            message: 'Creating',
            file: file,
            stat: stat,
            logger: logger
          });
        }
        this.push(file);
        cb();
      }
    }.bind(this));
  });
};

function ask(file, defaultChoiceIndex, cb) {

  inquirer.prompt([
      {
        type: 'expand',
        name: 'replace',
        message: 'Replace ' + file.relative + '?',
        default: defaultChoiceIndex,
        choices: choices
      }
    ],
    function (answers) {
      cb(answers.replace);
    });
}

function diffFiles(newFile, oldFilePath) {
  if (newFile.isStream()) {
    error('Diff does not support file streams');
  }
  try {
    var content = fs.readFileSync(oldFilePath, 'utf8');
    var differences = diff.diffLines(content, String(newFile.contents));
    log('File differences: ' + gutil.colors.bgGreen('added') + ' ' + gutil.colors.bgRed('removed') + '\n\n' + differences.map(formatPart).join(''));
  } catch (err) {
    error('Reading old file for diff failed with: ' + err.message);
  }
}

function formatPart(part, i) {
  var indent = new Array(8).join(' ');
  return (!i ? indent : '') + part.value.split('\n').map(function (line) {
      return gutil.colors[colorFromPart(part)](line);
    }).join('\n' + indent);
}

function colorFromPart(part) {
  if (part.added) {
    return 'bgGreen';
  } else if (part.removed) {
    return 'bgRed';
  }
  return 'grey';
}

/*
 * Args: message, file, stat, extraText
 */
function logFile(options) {
  var message   = options.message,
      file      = options.file,
      stat      = options.stat,
      extraText = options.extraText,
      logger    = options.logger;

  if (!file || !file.relative || (stat && stat.isDirectory())) {
    return;
  }
  var fileName = gutil.colors.magenta(file.relative);
  if (extraText) {
    logger(message, fileName, extraText);
  } else {
    logger(message, fileName);
  }
}

function log() {
  if (isTest()) {
    return;
  }
  var logger = gutil.log.bind(gutil, '[' + gutil.colors.cyan('conflict') + ']');
  logger.apply(logger, arguments);
}

function error(message) {
  throw new gutil.PluginError(pkg.name, message);
}

function isTest() {
  return process.env.NODE_ENV === 'test';
}

<|endoftext|>


<commit_before>var _ = require("underscore");

module.exports = function(config) {

  function matchUser(match,request) {
    if(!_.isArray(match.users)) {
      match.users = [match.users];
    }
    if(_.contains(match.users,request.user)) {
      return true;
    } else {
      return false;
    }
  }

  function selectFeature(feature,request) {
    var matchLevel = [];
    var currentLevel = 0;
    var retVal = false;
    feature.forEach(function(featureLevel){
      if(featureLevel.level === 0) {
        return;
      }
      var level = featureLevel.level;
      if(featureLevel.match) {
        var match = false;
        if(featureLevel.match.type === "user" ) {
          match = matchUser(featureLevel.match,request);
        } else {
          try {
            match = require(featureLevel.match.type)(featureLevel.match,
            request);
          } catch(error) {

          }
        }
        if(!match) {
          level = -1;
        }
        if(match && level > 100) {
          retVal = featureLevel.value;
        }
      }
      if(level > 100 && !retVal) {
        retVal = featureLevel.value;
      } else if(level > -1) {
        matchLevel.push({
          min:currentLevel,
          max:currentLevel+level,
          value:featureLevel.value
        });
        currentLevel+=level;
      }
    });
    if(!retVal) {

      var luckyNumber = _.random(0,currentLevel);
      matchLevel.forEach(function(match){
        if(match.min < luckyNumber && luckyNumber <= match.max) {
          retVal = match.value;
        }
      });
    }
    return retVal;
  }

  function middleware(request,response,next) {
    var features = {};
    if(request.cookies.features) {
      features = request.cookies.features;
    }
    Object.keys(features).forEach(function(name) {
      if(!api.featuresConfig[name]) {
        delete features[name];
      }
    });

    Object.keys(api.featuresConfig).forEach(function(name) {
      if(!features[name]) {
        features[name] = selectFeature(api.featuresConfig[name],request);
      }
      if(request.query["feature-"+name]) {
        features[name]=request.query["feature-"+name];
      }
    });
    request.features = features;
    function isEnabled(name,value) {
      var retVal = false;
      if(value === undefined) {
        if(features[name]) {
          retVal = true;
        }
      } else if(features[name] === value) {
        retVal = true;
      }
      return retVal;
    }
    function atLeast(name,value) {
      var retVal = false;
      if( typeof(value) === "number" &&
          typeof(features[name]) === "number") {
          retVal = features[name] <= value;
      } else {
        retVal = features.isEnabled(name,value);
      }
      return retVal;
    }
    Object.defineProperty(features,"isEnabled",{
      value:isEnabled
    });
    Object.defineProperty(features,"atLeast",{
      value:atLeast
    });
    next();
  }

  var api = middleware;

  api.featuresConfig = config;

  return api;
};<commit_msg>stored the features in a cookie<commit_after>var _ = require("underscore");

module.exports = function(config) {

  function matchUser(match,request) {
    if(!_.isArray(match.users)) {
      match.users = [match.users];
    }
    if(_.contains(match.users,request.user)) {
      return true;
    } else {
      return false;
    }
  }

  function selectFeature(feature,request) {
    var matchLevel = [];
    var currentLevel = 0;
    var retVal = false;
    feature.forEach(function(featureLevel){
      if(featureLevel.level === 0) {
        return;
      }
      var level = featureLevel.level;
      if(featureLevel.match) {
        var match = false;
        if(featureLevel.match.type === "user" ) {
          match = matchUser(featureLevel.match,request);
        } else {
          try {
            match = require(featureLevel.match.type)(featureLevel.match,
            request);
          } catch(error) {

          }
        }
        if(!match) {
          level = -1;
        }
        if(match && level > 100) {
          retVal = featureLevel.value;
        }
      }
      if(level > 100 && !retVal) {
        retVal = featureLevel.value;
      } else if(level > -1) {
        matchLevel.push({
          min:currentLevel,
          max:currentLevel+level,
          value:featureLevel.value
        });
        currentLevel+=level;
      }
    });
    if(!retVal) {

      var luckyNumber = _.random(0,currentLevel);
      matchLevel.forEach(function(match){
        if(match.min < luckyNumber && luckyNumber <= match.max) {
          retVal = match.value;
        }
      });
    }
    return retVal;
  }

  function middleware(request,response,next) {
    var features = {};
    if(request.cookies.features) {
      features = request.cookies.features;
    }
    Object.keys(features).forEach(function(name) {
      if(!api.featuresConfig[name]) {
        delete features[name];
      }
    });

    Object.keys(api.featuresConfig).forEach(function(name) {
      if(!features[name]) {
        features[name] = selectFeature(api.featuresConfig[name],request);
      }
      if(request.query["feature-"+name]) {
        features[name]=request.query["feature-"+name];
      }
    });
    request.features = features;
    function isEnabled(name,value) {
      var retVal = false;
      if(value === undefined) {
        if(features[name]) {
          retVal = true;
        }
      } else if(features[name] === value) {
        retVal = true;
      }
      return retVal;
    }
    function atLeast(name,value) {
      var retVal = false;
      if( typeof(value) === "number" &&
          typeof(features[name]) === "number") {
          retVal = features[name] <= value;
      } else {
        retVal = features.isEnabled(name,value);
      }
      return retVal;
    }
    response.cookie("features", features);
    Object.defineProperty(features,"isEnabled",{
      value:isEnabled
    });
    Object.defineProperty(features,"atLeast",{
      value:atLeast
    });

    next();
  }

  var api = middleware;

  api.featuresConfig = config;

  return api;
};<|endoftext|>


<commit_before>var ss = require('simple-statistics');
var inside = require('turf-inside');

/**
* Calculates the minimum value of a field for {@link Point} features within a set of {@link Polygon} features.
*
* @module turf/min
* @param {FeatureCollection} polygons a FeatureCollection of {@link Polygon} features
* @param {FeatureCollection} points a FeatureCollection of {@link Point} features
* @param {string} inField the field in input data to analyze
* @param {string} outField the field in which to store results
* @return {FeatureCollection} a FeatureCollection of {@link Polygon} features
* with properties listed as `outField` values in `aggregations`
* @example
* var polygons = turf.featurecollection([
*   turf.polygon([[[0,0],[10,0],[10,10],[0,10],[0,0]]]),
*   turf.polygon([[[10,0],[20,10],[20,20], [20,0]]])]);
* var points = turf.featurecollection([
*   turf.point(5,5, {population: 200}),
*   turf.point(1,3, {population: 600}),
*   turf.point(14,2, {population: 100}),
*   turf.point(13,1, {population: 200}),
*   turf.point(19,7, {population: 300})]);
* var aggregated = turf.min(polygons, points, 'population', 'min');
* //=polygons
* //=points
* //=aggregated
*/
module.exports = function(polyFC, ptFC, inField, outField){
  polyFC.features.forEach(function(poly){
    if(!poly.properties){
      poly.properties = {};
    }
    var values = [];
    ptFC.features.forEach(function(pt){
      if (inside(pt, poly)) {
        values.push(pt.properties[inField]);
      }
    });
    poly.properties[outField] = ss.min(values);
  });

  return polyFC;
};
<commit_msg>Change description of result<commit_after>var ss = require('simple-statistics');
var inside = require('turf-inside');

/**
* Calculates the minimum value of a field for {@link Point} features within a set of {@link Polygon} features.
*
* @module turf/min
* @param {FeatureCollection} polygons a FeatureCollection of {@link Polygon} features
* @param {FeatureCollection} points a FeatureCollection of {@link Point} features
* @param {string} inField the field in input data to analyze
* @param {string} outField the field in which to store results
* @return {FeatureCollection} a FeatureCollection of {@link Polygon} features
* with properties listed as `outField` values
* @example
* var polygons = turf.featurecollection([
*   turf.polygon([[[0,0],[10,0],[10,10],[0,10],[0,0]]]),
*   turf.polygon([[[10,0],[20,10],[20,20], [20,0]]])]);
* var points = turf.featurecollection([
*   turf.point(5,5, {population: 200}),
*   turf.point(1,3, {population: 600}),
*   turf.point(14,2, {population: 100}),
*   turf.point(13,1, {population: 200}),
*   turf.point(19,7, {population: 300})]);
* var aggregated = turf.min(polygons, points, 'population', 'min');
* //=polygons
* //=points
* //=aggregated
*/
module.exports = function(polyFC, ptFC, inField, outField){
  polyFC.features.forEach(function(poly){
    if(!poly.properties){
      poly.properties = {};
    }
    var values = [];
    ptFC.features.forEach(function(pt){
      if (inside(pt, poly)) {
        values.push(pt.properties[inField]);
      }
    });
    poly.properties[outField] = ss.min(values);
  });

  return polyFC;
};
<|endoftext|>


<commit_before>// Required Libraries
var util = require('util');
var events = require('events');
var io = require('socket.io-client');
var jscrypto = require('jsrsasign');

function CryptoCapital (cfg) {

    var CRYPTOCAP_API = 'https://api.cryptocapital.co';

    // Setup Event Emitter
    events.EventEmitter.call(this);

    // Configuration
    this.debug = typeof cfg.debug !== undefined ? cfg.debug : false;
    this.cckey = cfg.key;
    this.ccpub = cfg.pub;

    // Open Socket
    this.socket = io(CRYPTOCAP_API);

//    // Socket Event Listeners
//    this.socket.on('connect', function () {
//        this.emit('connect');
//    });

//    this.socket.on('ack', function (data) {
//        this.emit('ack', JSON.parse(data));
//    });

//    this.socket.on('err', function (data) {
//        this.emit('err', JSON.parse(data));
//    });

//    this.socket.on('error', function (data) {
//        this.emit('error', JSON.parse(data));
//    });

//    this.socket.on('transfer', function (data) {
//        this.emit('transfer', JSON.parse(data));
//    });

//    this.socket.on('account', function (data) {
//        this.emit('account', JSON.parse(data));
//    });

}

util.inherits(CryptoCapital, events.EventEmitter);

CryptoCapital.prototype.auth = function (args, callback) {

    var self = this;

    var msg = { apiVersion: 2,
                key: self.ccpub,
                nonce: Date.now(),
                params: args };
    msg.signed = doSign(self.cckey, 'AUTH' + msg.key.toString() + msg.nonce.toString());
    self.socket.emit('auth', JSON.stringify(msg));
    callback(msg);

};

CryptoCapital.prototype.transfer = function (args, callback) {

    var self = this;

    var msg = { apiVersion: 2,
                key: self.ccpub,
                nonce: Date.now(),
                params: args };
    msg.signed = doSign(self.cckey, 'TRANSFER' + msg.key.toString() + msg.nonce.toString() + args.accountNumber.toString() + args.beneficiary.toString() + args.currency.toString() + args.amount.toString());
    self.socket.emit('transfer', JSON.stringify(msg));
    callback(msg);

};

CryptoCapital.prototype.statement = function (args, callback) {

    var self = this;

    var msg = { apiVersion: 2,
                key: self.ccpub,
                nonce: Date.now(),
                params: args };
    msg.signed = doSign(self.cckey, 'STATEMENT' + msg.key.toString() + msg.nonce.toString() + args.accountNumber.toString());
    self.socket.emit('statement', JSON.stringify(msg));
    callback(msg);

};

CryptoCapital.prototype.account = function (args, callback) {

    var self = this;

    var msg = { apiVersion: 2,
                key: self.ccpub,
                nonce: Date.now(),
                params: args };
    msg.signed = doSign(self.cckey, 'ACCOUNT' + msg.key.toString() + msg.nonce.toString() + args.accountNumber.toString());
    self.socket.emit('account', JSON.stringify(msg));
    callback(msg);

};

module.exports = CryptoCapital;

function doSign(prvkey, message) {

  var hexkey = new Buffer(prvkey, 'base64').toString('hex');

  var curve = 'secp256k1';
  var sigalg = 'SHA256withECDSA';

  var sig = new KJUR.crypto.Signature({"alg": sigalg, "prov": "cryptojs/jsrsa"});
  sig.initSign({'ecprvhex': hexkey, 'eccurvename': curve});
  sig.updateString(message);
  var sigValueHex = sig.sign();

  return new Buffer(sigValueHex, 'hex').toString('base64');

}
<commit_msg>Reenabled connect event<commit_after>// Required Libraries
var util = require('util');
var events = require('events');
var io = require('socket.io-client');
var jscrypto = require('jsrsasign');

function CryptoCapital (cfg) {

    var CRYPTOCAP_API = 'https://api.cryptocapital.co';

    // Setup Event Emitter
    events.EventEmitter.call(this);

    // Configuration
    this.debug = typeof cfg.debug !== undefined ? cfg.debug : false;
    this.cckey = cfg.key;
    this.ccpub = cfg.pub;

    // Open Socket
    this.socket = io(CRYPTOCAP_API);

    // Socket Event Listeners
    this.socket.on('connect', function () {
        this.emit('connect');
    });

//    this.socket.on('ack', function (data) {
//        this.emit('ack', JSON.parse(data));
//    });

//    this.socket.on('err', function (data) {
//        this.emit('err', JSON.parse(data));
//    });

//    this.socket.on('error', function (data) {
//        this.emit('error', JSON.parse(data));
//    });

//    this.socket.on('transfer', function (data) {
//        this.emit('transfer', JSON.parse(data));
//    });

//    this.socket.on('account', function (data) {
//        this.emit('account', JSON.parse(data));
//    });

}

util.inherits(CryptoCapital, events.EventEmitter);

CryptoCapital.prototype.auth = function (args, callback) {

    var self = this;

    var msg = { apiVersion: 2,
                key: self.ccpub,
                nonce: Date.now(),
                params: args };
    msg.signed = doSign(self.cckey, 'AUTH' + msg.key.toString() + msg.nonce.toString());
    self.socket.emit('auth', JSON.stringify(msg));
    callback(msg);

};

CryptoCapital.prototype.transfer = function (args, callback) {

    var self = this;

    var msg = { apiVersion: 2,
                key: self.ccpub,
                nonce: Date.now(),
                params: args };
    msg.signed = doSign(self.cckey, 'TRANSFER' + msg.key.toString() + msg.nonce.toString() + args.accountNumber.toString() + args.beneficiary.toString() + args.currency.toString() + args.amount.toString());
    self.socket.emit('transfer', JSON.stringify(msg));
    callback(msg);

};

CryptoCapital.prototype.statement = function (args, callback) {

    var self = this;

    var msg = { apiVersion: 2,
                key: self.ccpub,
                nonce: Date.now(),
                params: args };
    msg.signed = doSign(self.cckey, 'STATEMENT' + msg.key.toString() + msg.nonce.toString() + args.accountNumber.toString());
    self.socket.emit('statement', JSON.stringify(msg));
    callback(msg);

};

CryptoCapital.prototype.account = function (args, callback) {

    var self = this;

    var msg = { apiVersion: 2,
                key: self.ccpub,
                nonce: Date.now(),
                params: args };
    msg.signed = doSign(self.cckey, 'ACCOUNT' + msg.key.toString() + msg.nonce.toString() + args.accountNumber.toString());
    self.socket.emit('account', JSON.stringify(msg));
    callback(msg);

};

module.exports = CryptoCapital;

function doSign(prvkey, message) {

  var hexkey = new Buffer(prvkey, 'base64').toString('hex');

  var curve = 'secp256k1';
  var sigalg = 'SHA256withECDSA';

  var sig = new KJUR.crypto.Signature({"alg": sigalg, "prov": "cryptojs/jsrsa"});
  sig.initSign({'ecprvhex': hexkey, 'eccurvename': curve});
  sig.updateString(message);
  var sigValueHex = sig.sign();

  return new Buffer(sigValueHex, 'hex').toString('base64');

}
<|endoftext|>


<commit_before>require("./style.css");
import React from 'react';
import classNames from 'classnames';
import throttle from 'lodash/function/throttle.js';
import ScreenAttributes, {getScreenAttributes} from 'screen-attributes-mixin';
import {isDesktop} from 'ua.js';

const Scroller = React.createClass({
    mixins: [ScreenAttributes],
    getInitialState(){
        let {screenHeight} = getScreenAttributes();
        return {
            screenHeight
        };
    },
    componentDidMount(){
        this.scrollBottom();
        if(this.props.onScroll){
            this.throttledOnScroll = throttle(this.props.onScroll, 500);
        }
    },
    componentWillUpdate(nextProps, nextState){
        let ctn = this.refs.scroller.getDOMNode();
        if (ctn.scrollTop + ctn.offsetHeight >= ctn.scrollHeight) {
            if(this.props.marginBottom < nextProps.marginBottom || this.state.screenHeight !== nextState.screenHeight){
                this.needScrollToBottom = true;
            }
        }
    },
    componentDidUpdate(prevProps, prevState){
        if(this.needScrollToBottom){
            this.needScrollToBottom = false;
            this.scrollBottom();
        }
    },
    needScrollToBottom: false,
    preventOnScrollEvent: false,
    throttledOnScroll: null,
    getScrollHeight(){
        return this.refs.scroller.getDOMNode().scrollHeight;
    },
    onScroll(e) {
        if(this.preventOnScrollEvent){
            this.preventOnScrollEvent = false;
            return;
        }
        if (e.target.scrollTop + e.target.offsetHeight >= e.target.scrollHeight) {
            if (this.props.onScrollBottom) {
                this.props.onScrollBottom();
            }
        } else if (e.target.scrollHeight > e.target.offsetHeight && e.target.scrollTop <= 0) {
            if (this.props.onScrollTop) {
                this.props.onScrollTop();
            }
        }
        if (this.props.onScroll) {
            this.throttledOnScroll(e.target.scrollTop);
        }
    },
    scrollBottom() {
        this.preventOnScrollEvent = true;
        let ctn = this.refs.scroller.getDOMNode();
        ctn.scrollTop = ctn.scrollHeight - ctn.offsetHeight;
    },
    setScrollTop(scrollTop) {
        this.preventOnScrollEvent = true;
        this.refs.scroller.getDOMNode().scrollTop = scrollTop;
    },
    render() {
        let marginTop = this.props.marginTop;
        let marginBottom = this.props.marginBottom;

        if (typeof marginTop !== 'number') {
            marginTop = isDesktop() ? 0 : 49;
        }

        if (typeof marginBottom !== 'number') {
            marginBottom = isDesktop() ? 0 : 49;
        }

        let style = {
            height: this.state.screenHeight - marginTop - marginBottom,
            marginTop
        };

        Object.assign(style, this.props.style);

        return (

                {this.props.children}

        );
    }
});

export default Scroller;
<commit_msg>把react-scroller预留的顶部在微信情况下去掉<commit_after>require("./style.css");
import React from 'react';
import classNames from 'classnames';
import throttle from 'lodash/function/throttle.js';
import ScreenAttributes, {getScreenAttributes} from 'screen-attributes-mixin';
import {isDesktop, isWeChat} from 'ua.js';

const Scroller = React.createClass({
    mixins: [ScreenAttributes],
    getInitialState(){
        let {screenHeight} = getScreenAttributes();
        return {
            screenHeight
        };
    },
    componentDidMount(){
        this.scrollBottom();
        if(this.props.onScroll){
            this.throttledOnScroll = throttle(this.props.onScroll, 500);
        }
    },
    componentWillUpdate(nextProps, nextState){
        let ctn = this.refs.scroller.getDOMNode();
        if (ctn.scrollTop + ctn.offsetHeight >= ctn.scrollHeight) {
            if(this.props.marginBottom < nextProps.marginBottom || this.state.screenHeight !== nextState.screenHeight){
                this.needScrollToBottom = true;
            }
        }
    },
    componentDidUpdate(prevProps, prevState){
        if(this.needScrollToBottom){
            this.needScrollToBottom = false;
            this.scrollBottom();
        }
    },
    needScrollToBottom: false,
    preventOnScrollEvent: false,
    throttledOnScroll: null,
    getScrollHeight(){
        return this.refs.scroller.getDOMNode().scrollHeight;
    },
    onScroll(e) {
        if(this.preventOnScrollEvent){
            this.preventOnScrollEvent = false;
            return;
        }
        if (e.target.scrollTop + e.target.offsetHeight >= e.target.scrollHeight) {
            if (this.props.onScrollBottom) {
                this.props.onScrollBottom();
            }
        } else if (e.target.scrollHeight > e.target.offsetHeight && e.target.scrollTop <= 0) {
            if (this.props.onScrollTop) {
                this.props.onScrollTop();
            }
        }
        if (this.props.onScroll) {
            this.throttledOnScroll(e.target.scrollTop);
        }
    },
    scrollBottom() {
        this.preventOnScrollEvent = true;
        let ctn = this.refs.scroller.getDOMNode();
        ctn.scrollTop = ctn.scrollHeight - ctn.offsetHeight;
    },
    setScrollTop(scrollTop) {
        this.preventOnScrollEvent = true;
        this.refs.scroller.getDOMNode().scrollTop = scrollTop;
    },
    render() {
        let marginTop = this.props.marginTop;
        let marginBottom = this.props.marginBottom;

        if (typeof marginTop !== 'number') {
            marginTop = (isDesktop() || isWeChat()) ? 0 : 49;
        }

        if (typeof marginBottom !== 'number') {
            marginBottom = isDesktop() ? 0 : 49;
        }

        let style = {
            height: this.state.screenHeight - marginTop - marginBottom,
            marginTop
        };

        Object.assign(style, this.props.style);

        return (

                {this.props.children}

        );
    }
});

export default Scroller;
<|endoftext|>


<commit_before>/*!
 * index
 * Version: 0.0.1
 * Date: 2016/8/1
 * https://github.com/Nuintun/fengine
 *
 * Original Author: http://www.jsbug.com/lab/samples/fengine/
 *
 * This is licensed under the MIT License (MIT).
 * For details, see: https://github.com/Nuintun/fengine/blob/master/LICENSE
 */

'use strict';

// lib
var fs = require('fs');
var path = require('path');
var yaml = require('js-yaml');
var colors = require('colors');
var util = require('./lib/util');
var Fengine = require('./lib/fengine');

// variable declaration
var CWD = process.cwd();

/**
 * file exists sync
 * @param src
 * @returns {boolean}
 */
function fileExistsSync(src){
  if (!src) return false;

  try {
    return fs.statSync(src).isFile();
  } catch (error) {
    // check exception. if ENOENT - no such file or directory ok, file doesn't exist.
    // otherwise something else went wrong, we don't have rights to access the file, ...
    if (error.code != 'ENOENT') {
      throw error;
    }

    return false;
  }
}

/**
 * assert port
 * @param port
 * @returns {boolean}
 */
function assertPort(port){
  return util.number(port) && !util.nan(port) && !util.infinity(port);
}

/**
 * assert watch
 * @param watch
 * @returns {Array}
 */
function formatWatch(watch){
  var unique = {};
  var result = [];

  watch.forEach(function (value){
    value = value.toLowerCase();

    if (!unique[value]) {
      unique[value] = true;

      result.push(value);
    }
  });

  return result;
}

/**
 * run
 * @param port
 */
module.exports.run = function (port){
  var yml = path.resolve(CWD, 'fengine.yml');

  // file config
  if (fileExistsSync(yml)) {
    // parse yaml
    var source = fs.readFileSync(yml);

    yml = yaml.safeLoad(source, { filename: yml });
  } else {
    yml = {};
  }

  // format options
  yml.root = CWD;
  yml.layout = yml.layout || null;
  yml.data = util.extend({}, yml.data);
  yml.hostname = yml.hostname || '127.0.0.1';
  yml.base = util.string(yml.base) ? path.join(CWD, yml.base) : CWD;
  yml.port = port !== null ? port : assertPort(yml.port) ? Math.abs(yml.port) : null;
  yml.watch = util.array(yml.watch)
    ? formatWatch(yml.watch.concat(['.htm', '.html']))
    : ['.htm', '.html'];

  console.log(yml.watch);

  // run fengine
  new Fengine(yml);
};
<commit_msg>improve code<commit_after>/*!
 * index
 * Version: 0.0.1
 * Date: 2016/8/1
 * https://github.com/Nuintun/fengine
 *
 * Original Author: http://www.jsbug.com/lab/samples/fengine/
 *
 * This is licensed under the MIT License (MIT).
 * For details, see: https://github.com/Nuintun/fengine/blob/master/LICENSE
 */

'use strict';

// lib
var fs = require('fs');
var path = require('path');
var yaml = require('js-yaml');
var colors = require('colors');
var util = require('./lib/util');
var Fengine = require('./lib/fengine');

// variable declaration
var CWD = process.cwd();

/**
 * file exists sync
 * @param src
 * @returns {boolean}
 */
function fileExistsSync(src){
  if (!src) return false;

  try {
    return fs.statSync(src).isFile();
  } catch (error) {
    // check exception. if ENOENT - no such file or directory ok, file doesn't exist.
    // otherwise something else went wrong, we don't have rights to access the file, ...
    if (error.code != 'ENOENT') {
      throw error;
    }

    return false;
  }
}

/**
 * assert port
 * @param port
 * @returns {boolean}
 */
function assertPort(port){
  return util.number(port) && !util.nan(port) && !util.infinity(port);
}

/**
 * format watch
 * @param watch
 * @returns {Array}
 */
function formatWatch(watch){
  var unique = {};
  var result = [];

  watch.forEach(function (value){
    value = value.toLowerCase();

    if (!unique[value]) {
      unique[value] = true;

      result.push(value);
    }
  });

  return result;
}

/**
 * run
 * @param port
 */
module.exports.run = function (port){
  var yml = path.resolve(CWD, 'fengine.yml');

  // file config
  if (fileExistsSync(yml)) {
    // parse yaml
    var source = fs.readFileSync(yml);

    yml = yaml.safeLoad(source, { filename: yml });
  } else {
    yml = {};
  }

  // format options
  yml.root = CWD;
  yml.layout = yml.layout || null;
  yml.data = util.extend({}, yml.data);
  yml.hostname = yml.hostname || '127.0.0.1';
  yml.base = util.string(yml.base) ? path.join(CWD, yml.base) : CWD;
  yml.port = port !== null ? port : assertPort(yml.port) ? Math.abs(yml.port) : null;
  yml.watch = util.array(yml.watch)
    ? formatWatch(yml.watch.concat(['.htm', '.html']))
    : ['.htm', '.html'];

  // run fengine
  new Fengine(yml);
};
<|endoftext|>


<commit_before>// project/index.js
var jsonServer = require('json-server');

var server = jsonServer.create();
var router = jsonServer.router('./db.json');

server.use(jsonServer.defaults());
server.use(router);

server.listen(3000);
<commit_msg>use dynamic port number<commit_after>// project/index.js
var jsonServer = require('json-server');

var server = jsonServer.create();
var router = jsonServer.router('./db.json');
var port = process.env.PORT || 3000;

server.use(jsonServer.defaults());
server.use(router);

server.listen(port);
<|endoftext|>