<commit_before>'use strict';
var queries = angular.module('cliffhanger.queries', ['ngRoute', 'ngSanitize', 'ngCsv']);
queries.controller('QueryWizardCtrl', function ($scope, $uibModalInstance, $log, datasets, queryService) {
    $scope.query = {}; //container for query
    $scope.alerts = [];
    $scope.tableResult = {};
    $scope.selected = {};
    $scope.step = 1; //which step in the modal is on
    $scope.maxSteps = 5; //number of steps in modal
    $scope.datasets = datasets;
    $scope.tags = []; //TODO load based upon datasets
    $scope.addJoinColumn = false; //whether to include joined column in select
    $scope.selectedDatasets = []; //datasets selected to be joined
    $scope.selectedTags = []; //selected join tags
    $scope.selectedColumns = []; //select columns for query
    //for save query dropdown
    $scope.isCollapsed = true;
    $scope.download = false;
    $scope.loadingPreview = false;
    //method responsible for handling changes due to checkboxes
    //d -> item selected/deselected
    //selections -> array to add/remove item
    $scope.change = function (d, selections) {
            if (d.selected) {
                selections.push(d);
            } else {
                for (var i = 0; i < selections.length; i++) {
                    $log.debug(selections[i]);
                    if (selections[i].name == d.name) {
                        selections.splice(i, 1);
                    }
                }
            }
            $log.debug(selections);
        }
        //method responsible for handling changes due to checkboxes
        //d -> item selected/deselected
        //selections -> array to add/remove item
    $scope.changeColumns = function (column, selections, dataset) {
            if (column.selected) {
                column.db_table_name = dataset.db_table_name;
                selections.push(column);
            } else {
                for (var i = 0; i < selections.length; i++) {
                    $log.debug(selections[i]);
                    if (selections[i].name == column.name) {
                        selections.splice(i, 1);
                    }
                }
            }
            $log.debug(selections);
        }
        //load the joinable tags only in the selected datasets
    $scope.loadTags = function () {
            for (var i = 0; i < $scope.selectedDatasets[0].tags.length; i++) {
                var tagA = $scope.selectedDatasets[0].tags[i];
                for (var j = 0; j < $scope.selectedDatasets[1].tags.length; j++) {
                    var tagB = $scope.selectedDatasets[1].tags[j];
                    //if tags match, aren't EMPTY and are not a duplicate
                    if (tagA.name == tagB.name && tagA.name != '<EMPTY>' && $scope.tags.indexOf(tagA) == -1) {
                        $scope.tags.push(tagA);
                        break;
                    }
                }
            }
            $log.debug($scope.tags);
        }
        //advance the modal to the next step
    $scope.next = function () {
        $scope.step++;
        if ($scope.step == 2) {
            $scope.loadTags();
        } else if ($scope.step == 4) $scope.buildQuery();
        else if ($scope.step == 5) {
            $scope.runQuery($scope.query);
        }
    };
    //go back a step in the modal
    $scope.previous = function () {
        $scope.step--;
        if ($scope.step < $scope.maxSteps) {
            $scope.progressType = null;
            $scope.tableResult = null;
        }
    };

    $scope.selectAllFromDataset = function (dataset) {

        for (var i = 0; i < dataset.attributes.length; i++) {
            var a = dataset.attributes[i];
            if ($scope.selected[dataset.name]) {
                if (a.tag.name != $scope.selectedTags[0].name) {
                    a.db_table_name = dataset.db_table_name;
                    a.selected = true;
                    $scope.selectedColumns.push(a);
                }
            } else {
                a.selected = false;
                for (var j = 0; j < $scope.selectedColumns.length; j++) {
                    if ($scope.selectedColumns[j].name == a.name) {
                        $scope.selectedColumns.splice(j, 1);
                    }
                }
            }
        }
    }

    //dismiss the modal
    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
    //add where and limit clause to SQL query string
    $scope.addToQuery = function () {
        if (($scope.statement.where == null && $scope.statement.limit == null) || ($scope.statement.where == "" && $scope.statement.limit == "") || ($scope.statement.where == null && $scope.statement.limit == "") || ($scope.statement.where == "" && $scope.statement.limit == null)) {
            $scope.query = $scope.query.replace(";", "");
            $scope.statement.text = ";";
        }
        //adding both WHERE and LIMIT statement
        else if ($scope.statement.where != null && $scope.statement.limit != null) {
            $scope.query = $scope.query.replace(";", "");
            $scope.statement.text = "\nWHERE " + $scope.statement.where + "\n" + "LIMIT " + $scope.statement.limit + ";";
        }
        //adding WHERE and not LIMIT
        else if (($scope.statement.where != null && $scope.statement.limit == null) || ($scope.statement.where != null && $scope.statement.limit == "")) {
            $scope.query = $scope.query.replace(";", "");
            $scope.statement.text = "\nWHERE " + $scope.statement.where + ";";
        }
        //adding LIMIT and not WHERE
        else if (($scope.statement.where == null && $scope.statement.limit != null) || ($scope.statement.where == "" && $scope.statement.limit != null)) {
            $scope.query = $scope.query.replace(";", "");
            $scope.statement.text = "\nLIMIT " + $scope.statement.limit + ";";
        }
        $log.debug($scope.statement);
    };
    //build a new query given the user's choices
    $scope.buildQuery = function () {
        //query input packaged
        var queryInput = {
            datasets: $scope.selectedDatasets,
            joinTag: $scope.selectedTags,
            addJoinColumn: $scope.addJoinColumn,
            columns: $scope.selectedColumns
        }
        queryService.buildQuery(queryInput).then(function (response) {
            //success callback
            if (response.status == 'Success') {
                $scope.query = response.data;
                $scope.progressType = 'success';
                //failure callback
            } else {
                $scope.progressType = 'danger';
                $scope.buildQueryError = true;
                $log.error(response.data);
            }
        });
    };
    //complete the modal
    $scope.save = function () {
        if ($scope.statement.text != null) {
            $scope.newQuery.sqlString = $scope.query + $scope.statement.text;
        } else {
            $scope.newQuery.sqlString = $scope.query;
        }
        queryService.saveQuery($scope.newQuery).then(function (data) {
            if (data.status == 'Success') {
                $log.debug(data);
            } else {
                $scope.alerts.push({
                    msg: data,
                    type: 'danger'
                });
            }
        }, function (data) {
            $scope.alerts.push({
                msg: 'Failed to create Query',
                type: 'danger'
            });
        })
    };
    $scope.runQuery = function () {
        $scope.loadingPreview = true;
        var query = $scope.query;
        queryService.runQuery(query).then(function (response) { //success callback
                $scope.loadingPreview = false;
                $scope.tableResult = response;
                $scope.progressType = 'success';
            }, //failure to connect
            function (data) {
                $scope.loadingPreview = false;
                $scope.progressType = 'danger';
                $scope.runQueryError = true;
                $log.error('Failed to connect to server');
            });
    };
});
<commit_msg>better comments/documentation<commit_after>'use strict';
var queries = angular.module('cliffhanger.queries', ['ngRoute', 'ngSanitize', 'ngCsv']);
queries.controller('QueryWizardCtrl', function ($scope, $uibModalInstance, $log, datasets, queryService) {
    $scope.query = {}; //container for query
    $scope.alerts = [];
    $scope.tableResult = {};
    $scope.selected = {};
    $scope.step = 1; //which step in the modal is on
    $scope.maxSteps = 5; //number of steps in modal
    $scope.datasets = datasets;
    $scope.tags = []; //TODO load based upon datasets
    $scope.addJoinColumn = false; //whether to include joined column in select
    $scope.selectedDatasets = []; //datasets selected to be joined
    $scope.selectedTags = []; //selected join tags
    $scope.selectedColumns = []; //select columns for query
    //for save query dropdown
    $scope.isCollapsed = true;
    $scope.download = false;
    $scope.loadingPreview = false;
    //method responsible for handling changes due to checkboxes
    //d -> item selected/deselected
    //selections -> array to add/remove item
    $scope.change = function (d, selections) {
            if (d.selected) {
                selections.push(d);
            } else {
                for (var i = 0; i < selections.length; i++) {
                    $log.debug(selections[i]);
                    if (selections[i].name == d.name) {
                        selections.splice(i, 1);
                    }
                }
            }
            $log.debug(selections);
        }
        //method responsible for handling changes due to checkboxes
        //d -> item selected/deselected
        //selections -> array to add/remove item
    $scope.changeColumns = function (column, selections, dataset) {
            if (column.selected) {
                column.db_table_name = dataset.db_table_name;
                selections.push(column);
            } else {
                for (var i = 0; i < selections.length; i++) {
                    $log.debug(selections[i]);
                    if (selections[i].name == column.name) {
                        selections.splice(i, 1);
                    }
                }
            }
            $log.debug(selections);
        }
        //load the joinable tags only in the selected datasets
    $scope.loadTags = function () {
            for (var i = 0; i < $scope.selectedDatasets[0].tags.length; i++) {
                var tagA = $scope.selectedDatasets[0].tags[i];
                for (var j = 0; j < $scope.selectedDatasets[1].tags.length; j++) {
                    var tagB = $scope.selectedDatasets[1].tags[j];
                    //if tags match, aren't EMPTY and are not a duplicate
                    if (tagA.name == tagB.name && tagA.name != '<EMPTY>' && $scope.tags.indexOf(tagA) == -1) {
                        $scope.tags.push(tagA);
                        break;
                    }
                }
            }
            $log.debug($scope.tags);
        }
        //advance the modal to the next step
    $scope.next = function () {
        $scope.step++;
        if ($scope.step == 2) {
            $scope.loadTags();
        } else if ($scope.step == 4) $scope.buildQuery();
        else if ($scope.step == 5) {
            $scope.runQuery($scope.query);
        }
    };
    //go back a step in the modal
    $scope.previous = function () {
        $scope.step--;
        if ($scope.step < $scope.maxSteps) {
            $scope.progressType = null;
            $scope.tableResult = null;
        }
    };

    $scope.selectAllFromDataset = function (dataset) {

        for (var i = 0; i < dataset.attributes.length; i++) {
            var a = dataset.attributes[i];
            //select all
            if ($scope.selected[dataset.name]) {
                //add column to selection
                if (a.tag.name != $scope.selectedTags[0].name) {
                    a.db_table_name = dataset.db_table_name;
                    a.selected = true;
                    $scope.selectedColumns.push(a);
                }
            }
            //deselect all
            else {
                a.selected = false;
                //remove column from selection
                for (var j = 0; j < $scope.selectedColumns.length; j++) {
                    if ($scope.selectedColumns[j].name == a.name) {
                        $scope.selectedColumns.splice(j, 1);
                    }
                }
            }
        }
    }

    //dismiss the modal
    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
    //add where and limit clause to SQL query string
    $scope.addToQuery = function () {
        if (($scope.statement.where == null && $scope.statement.limit == null) || ($scope.statement.where == "" && $scope.statement.limit == "") || ($scope.statement.where == null && $scope.statement.limit == "") || ($scope.statement.where == "" && $scope.statement.limit == null)) {
            $scope.query = $scope.query.replace(";", "");
            $scope.statement.text = ";";
        }
        //adding both WHERE and LIMIT statement
        else if ($scope.statement.where != null && $scope.statement.limit != null) {
            $scope.query = $scope.query.replace(";", "");
            $scope.statement.text = "\nWHERE " + $scope.statement.where + "\n" + "LIMIT " + $scope.statement.limit + ";";
        }
        //adding WHERE and not LIMIT
        else if (($scope.statement.where != null && $scope.statement.limit == null) || ($scope.statement.where != null && $scope.statement.limit == "")) {
            $scope.query = $scope.query.replace(";", "");
            $scope.statement.text = "\nWHERE " + $scope.statement.where + ";";
        }
        //adding LIMIT and not WHERE
        else if (($scope.statement.where == null && $scope.statement.limit != null) || ($scope.statement.where == "" && $scope.statement.limit != null)) {
            $scope.query = $scope.query.replace(";", "");
            $scope.statement.text = "\nLIMIT " + $scope.statement.limit + ";";
        }
        $log.debug($scope.statement);
    };
    //build a new query given the user's choices
    $scope.buildQuery = function () {
        //query input packaged
        var queryInput = {
            datasets: $scope.selectedDatasets,
            joinTag: $scope.selectedTags,
            addJoinColumn: $scope.addJoinColumn,
            columns: $scope.selectedColumns
        }
        queryService.buildQuery(queryInput).then(function (response) {
            //success callback
            if (response.status == 'Success') {
                $scope.query = response.data;
                $scope.progressType = 'success';
                //failure callback
            } else {
                $scope.progressType = 'danger';
                $scope.buildQueryError = true;
                $log.error(response.data);
            }
        });
    };
    //complete the modal
    $scope.save = function () {
        if ($scope.statement.text != null) {
            $scope.newQuery.sqlString = $scope.query + $scope.statement.text;
        } else {
            $scope.newQuery.sqlString = $scope.query;
        }
        queryService.saveQuery($scope.newQuery).then(function (data) {
            if (data.status == 'Success') {
                $log.debug(data);
            } else {
                $scope.alerts.push({
                    msg: data,
                    type: 'danger'
                });
            }
        }, function (data) {
            $scope.alerts.push({
                msg: 'Failed to create Query',
                type: 'danger'
            });
        })
    };
    $scope.runQuery = function () {
        $scope.loadingPreview = true;
        var query = $scope.query;
        queryService.runQuery(query).then(function (response) { //success callback
                $scope.loadingPreview = false;
                $scope.tableResult = response;
                $scope.progressType = 'success';
            }, //failure to connect
            function (data) {
                $scope.loadingPreview = false;
                $scope.progressType = 'danger';
                $scope.runQueryError = true;
                $log.error('Failed to connect to server');
            });
    };
});
<|endoftext|>


<commit_before>const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');

const server = express();

const Bookmark = require('./models/bookmark');

server.use(bodyParser.json());

server.use('/views', express.static(path.resolve(__dirname, 'public', 'views')));

server.get('/', (req, res) => {
  res.sendFile(path.resolve(__dirname, 'index.html'));
});

const apiV1Route = express.Router();

apiV1Route.get('/bookmarks', async (req, res) => {
  const bookmarks = await Bookmark.findAll();
  res.json(bookmarks);
});

apiV1Route.post('/bookmarks', async (req, res) => {
  const { repo_id, full_name } = req.body;

  try {
    const bookmarks = await Bookmark.findOrCreate({ where: { repo_id, full_name } });

    res.json(bookmarks[0]);
  } catch (error) {
    res
      .status(400)
      .json({ message: error.message });
  };
});

apiV1Route.delete('/bookmarks/:repo_id', async (req, res) => {
  const { repo_id } = req.params;

  try {
    await Bookmark.destroy({ where: { repo_id } });

    res.sendStatus(204);
  } catch (error) {
    res
      .status(400)
      .json({ message: error.messsage });
  }
})

server.use('/api/v1', apiV1Route);

server.listen('3000', () => {
  console.log('> Server is ready on port 3000.')
});
<commit_msg>Add parameter check.<commit_after>const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');

const server = express();

const Bookmark = require('./models/bookmark');

server.use(bodyParser.json());

server.use('/views', express.static(path.resolve(__dirname, 'public', 'views')));

server.get('/', (req, res) => {
  res.sendFile(path.resolve(__dirname, 'index.html'));
});

const apiV1Route = express.Router();

apiV1Route.get('/bookmarks', async (req, res) => {
  const bookmarks = await Bookmark.findAll();
  res.json(bookmarks);
});

apiV1Route.post('/bookmarks', async (req, res) => {
  const { repo_id, full_name } = req.body;

  try {
    if (!repo_id || !full_name) {
      throw new Error('Missing parameters');
    }

    const bookmarks = await Bookmark.findOrCreate({ where: { repo_id, full_name } });

    res.json(bookmarks[0]);
  } catch (error) {
    res
      .status(400)
      .json({ message: error.message });
  };
});

apiV1Route.delete('/bookmarks/:repo_id', async (req, res) => {
  const { repo_id } = req.params;

  try {
    await Bookmark.destroy({ where: { repo_id } });

    res.sendStatus(204);
  } catch (error) {
    res
      .status(400)
      .json({ message: error.messsage });
  }
})

server.use('/api/v1', apiV1Route);

server.listen('3000', () => {
  console.log('> Server is ready on port 3000.')
});
<|endoftext|>


<commit_before>/*
** Server of the poker application - www.smartgames.tv
** Development contact: aimeric.seguin(at)gmail.com
** Project started: 20/08/2014.
** Last update: 13/10/2014.
** Copyright © 2014 Ngine Networks - All Rights Reserved.
*/

/*******************************************/
/*          	  MAJOR                    */
/*******************************************/
var		cfg = require("./conf.json");		       // Configuration file, mainly to use aliases/macros.
var		express = require("express");			   // Web application framework we use.
var		app = express();			   			   // Express server handle.
var		http = require("http").createServer(app);  // Web server object with express server as request listener.
var		io = require("socket.io")(http);		   // Socket interface, server side.
var		nsp = require("express-namespace");		   // Namespace utility.
var		shortId = require("shortid");			   // Universal short unique-ID generator.
var		table_name;		   	   					   // Common table name prefix.
var		table_id;								   // Unique table name suffix. (example: /pokertable-Zqc9qQWZf).
var		seat_nb;								   // Seat number (1 to 6 included).
var		fs = require("fs");						   // Files parsing utility.
var		device_client;							   // Identify client type.
var 	_ = require("underscore");				   // Required.
var 	texas = require("texas");				   // Poker Hands evaluator we use.

/*******************************************/
/*          	ROUTING                    */
/*******************************************/
var	tables_ids = new Array();					  // List of tables ID (in order to check the existence of a table).

app.get("/", function(request, response)
{
	table_id = shortId.generate(); // "pro" for test only.
	table_name = "pokertable-" + table_id;
	tables_ids.push(table_id);
	response.redirect(cfg.conf.host + ":" + cfg.conf.port + "/" + table_name);
});

var router = express.Router();					// Express router we use.

router.get("/pokertable-:name", function(request, response)
{
	table_id = request.params.name;	// Table ID is which indicates on the URL.
	if (tables_ids.indexOf(table_id) != -1)
	{
		device_client = false;
		response.sendFile("public/index.html", {root: __dirname });
	}
	else
	{
		response.status(404);
		response.sendFile("public/table_not_found.html", {root: __dirname });
	}
});

router.get("/seat-:name", function(request, response)
{
	if (tables_ids.indexOf(request.params.name.substr(5)) != -1)
	{
		device_client = true;
		seat_nb = +request.params.name[0];
		table_id = request.params.name.substr(5);	// Indicate we are not on a table.
		if (seat_nb <= 0 || seat_nb >= 7)
		{
			response.status(404);
			response.sendFile("public/2nd_screen/page_not_found.html", {root: __dirname });
		}
		response.sendFile("public/2nd_screen/login.html", {root: __dirname });
	}
	else if (request.params.name == "disconnected.html")
	{
		response.sendFile("public/2nd_screen/disconnected.html", {root: __dirname });
	}
	else
	{
		response.status(404);
		response.sendFile("public/2nd_screen/page_not_found.html", {root: __dirname });
	}
});

app.use('/', router);

/*******************************************/
/*          	PATH                   	   */
/*******************************************/
app.use(express.static(__dirname + '/public'));		// Serve files in ./public using the express.static() middleware.
app.use(express.static(__dirname + '/public/img'));
app.use(express.static(__dirname + '/public/styles'));
app.use(express.static(__dirname + '/public/2nd_screen'));
app.use(express.static(__dirname + '/public/2nd_screen/js2'));

/*******************************************/
/*            SPECIAL STATUS               */
/*******************************************/
// When Express has executed all middleware/routes, and found that none of them responded then...
app.use(function(request, response)
{
	response.status(404);
	response.sendFile("public/2nd_screen/page_not_found.html", {root: __dirname });
});

/********************************************/
/*          	PORT                        */
//*******************************************/
http.listen(cfg.conf.port, function(request, response)
{
	console.log("Running at " + cfg.conf.host + " from " + __dirname);
});

/*******************************************/
/*           SERVER INCLUDED OBJECTS       */
/*******************************************/
eval(fs.readFileSync("sv/objects.js").toString());
eval(fs.readFileSync("sv/new_table.js").toString());
eval(fs.readFileSync("sv/new_table_seats.js").toString());
eval(fs.readFileSync("sv/get_table.js").toString());
eval(fs.readFileSync("sv/get_private_id.js").toString());
eval(fs.readFileSync("sv/table_general_socket.js").toString());
eval(fs.readFileSync("sv/players_general_socket.js").toString());
eval(fs.readFileSync("sv/send_qrcodes.js").toString());
eval(fs.readFileSync("sv/send_seats_infos.js").toString());
eval(fs.readFileSync("sv/send_bets.js").toString());
eval(fs.readFileSync("sv/get_seat.js").toString());
eval(fs.readFileSync("sv/cash_game/fisher_shuffle.js").toString());
eval(fs.readFileSync("sv/cash_game/timer.js").toString());
eval(fs.readFileSync("sv/cash_game/check_blanks.js").toString());
eval(fs.readFileSync("sv/cash_game/new_cashgame.js").toString());
eval(fs.readFileSync("sv/cash_game/show_down.js").toString());
eval(fs.readFileSync("sv/cash_game/end_game.js").toString());
eval(fs.readFileSync("sv/cash_game/evalhand.js").toString());
eval(fs.readFileSync("sv/cash_game/deal_board.js").toString());
eval(fs.readFileSync("sv/cash_game/remove_last_actions.js").toString());
eval(fs.readFileSync("sv/cash_game/check_bets.js").toString());

/*******************************************/
/*          SOCKET INTERACTIONS            */
/*******************************************/
var		tables = new Array();			// Array of tables objects.
var		table;							// Current table handler.
var		private_channel;				// Device private channel.
var		clients = [];

io.on("connection", function(socket)
{
    var client_ip = socket.request.connection.remoteAddress;
    var	curgame;

   	if (typeof table_id === "undefined")
    	return ;
    console.log("New connection from " + client_ip);
    if ((table = get_table(table_id, tables)) == "not found" && !device_client)
    {
    	var		deck = new Array('2c', '3c', '4c', '5c', '6c', '7c', '8c', '9c', 'tc', 'jc', 'qc', 'kc', '1c',
								'2s', '3s', '4s', '5s', '6s', '7s', '8s', '9s', 'ts', 'js', 'qs', 'ks', '1s',
								'2d', '3d', '4d', '5d', '6d', '7d', '8d', '9d', 'td', 'jd', 'qd', 'kd', '1d',
								'2h', '3h', '4h', '5h', '6h', '7h', '8h', '9h', 'th', 'jh', 'qh', 'kh', '1h');
    	console.log("Creating a new table...\nTable ID: " + table_id);
    	curgame = new Game(deck, -1, -1, cfg.conf.small_blind, -1, cfg.conf.big_blind, 0, 0, 0, 0, "waiting", 0, new Array());
	    table = new_table(table_id, 0, "waiting", new Array(),
	    	    +cfg.conf.start_bankroll, new_table_seats(), curgame, new Array(), new Array()); // We're also calling a function.
	    tables.push(table);
	    socket.join(table.id);
   		send_qrcodes(table, table.seats);
   		table.game.turn_to = "joiners";

		io.to(table.id).emit('tableId', table.id, get_table(table.id, tables), get_table(table.id, tables).game);

		socket.on('get tableId and tableGame', function(id) {
			io.to(id).emit('give tableId and tableGame', get_table(id, tables), get_table(id, tables).game);
		});

		socket.on('re init', function(table, game) {
			remove_last_actions(table, 2);
			show_down(table, game);
		});
	}
   	if (device_client)
   	{
   		console.log(table.private_ids);
   		private_channel = table_id + seat_nb;//shortId.generate() + seat_nb;
   		if (!get_private_id(table.private_ids, seat_nb))
   			table.private_ids.push(private_channel);
   		socket.on("get private channel", function()
   		{
   			socket.emit("private channel", private_channel, seat_nb);
   		});
   		socket.join(private_channel);
   		console.log("Joining private channel " + private_channel);
		hide_qr(table, seat_nb);
   	}
	socket.on("disconnect", function() {
		re_qr(table, seat_nb);
	});
		//io.to(table.id).emit("double blind", cfg.conf.small_blind, cfg.conf.big_blind);
	/*  socket.on("get qrcodes", function()
	{
		send_qrcodes(table, table.seats);
	});*/
	socket.on("ask buttons", function()
	{
			if (table.game.highlights_pos)
			{
				io.to(table.id).emit("place button", "sb", table.game.sb_pos);	// Respect this sending order.
				io.to(table.id).emit("place button", "dealer", table.game.d_pos);
				io.to(table.id).emit("place button", "bb", table.game.bb_pos);
			}
			io.to(table.id).emit("highlights", table.game.highlights_pos);
	});
	socket.on('get pot amount', function() {
		socket.emit('pot amount', table.game.pot_amount);
	});
	socket.on('need Id', function() {
		io.to(table.id).emit('give Idx', table_id);
	});
	io.to(table.id).emit("pot modification", table.game.pot_amount);
	send_bets(table); // Currents bets on the table.
	socket_listens_players(socket, table);
    socket_listens_global_settings(socket, table, table.seats);	// Event handler for major events.
});
<commit_msg>trying to fix restart function<commit_after>/*
** Server of the poker application - www.smartgames.tv
** Development contact: aimeric.seguin(at)gmail.com
** Project started: 20/08/2014.
** Last update: 13/10/2014.
** Copyright © 2014 Ngine Networks - All Rights Reserved.
*/

/*******************************************/
/*          	  MAJOR                    */
/*******************************************/
var		cfg = require("./conf.json");		       // Configuration file, mainly to use aliases/macros.
var		express = require("express");			   // Web application framework we use.
var		app = express();			   			   // Express server handle.
var		http = require("http").createServer(app);  // Web server object with express server as request listener.
var		io = require("socket.io")(http);		   // Socket interface, server side.
var		nsp = require("express-namespace");		   // Namespace utility.
var		shortId = require("shortid");			   // Universal short unique-ID generator.
var		table_name;		   	   					   // Common table name prefix.
var		table_id;								   // Unique table name suffix. (example: /pokertable-Zqc9qQWZf).
var		seat_nb;								   // Seat number (1 to 6 included).
var		fs = require("fs");						   // Files parsing utility.
var		device_client;							   // Identify client type.
var 	_ = require("underscore");				   // Required.
var 	texas = require("texas");				   // Poker Hands evaluator we use.

/*******************************************/
/*          	ROUTING                    */
/*******************************************/
var	tables_ids = new Array();					  // List of tables ID (in order to check the existence of a table).

app.get("/", function(request, response)
{
	table_id = shortId.generate(); // "pro" for test only.
	table_name = "pokertable-" + table_id;
	tables_ids.push(table_id);
	response.redirect(cfg.conf.host + ":" + cfg.conf.port + "/" + table_name);
});

var router = express.Router();					// Express router we use.

router.get("/pokertable-:name", function(request, response)
{
	table_id = request.params.name;	// Table ID is which indicates on the URL.
	if (tables_ids.indexOf(table_id) != -1)
	{
		device_client = false;
		response.sendFile("public/index.html", {root: __dirname });
	}
	else
	{
		response.status(404);
		response.sendFile("public/table_not_found.html", {root: __dirname });
	}
});

router.get("/seat-:name", function(request, response)
{
	if (tables_ids.indexOf(request.params.name.substr(5)) != -1)
	{
		device_client = true;
		seat_nb = +request.params.name[0];
		table_id = request.params.name.substr(5);	// Indicate we are not on a table.
		if (seat_nb <= 0 || seat_nb >= 7)
		{
			response.status(404);
			response.sendFile("public/2nd_screen/page_not_found.html", {root: __dirname });
		}
		response.sendFile("public/2nd_screen/login.html", {root: __dirname });
	}
	else if (request.params.name == "disconnected.html")
	{
		response.sendFile("public/2nd_screen/disconnected.html", {root: __dirname });
	}
	else
	{
		response.status(404);
		response.sendFile("public/2nd_screen/page_not_found.html", {root: __dirname });
	}
});

app.use('/', router);

/*******************************************/
/*          	PATH                   	   */
/*******************************************/
app.use(express.static(__dirname + '/public'));		// Serve files in ./public using the express.static() middleware.
app.use(express.static(__dirname + '/public/img'));
app.use(express.static(__dirname + '/public/styles'));
app.use(express.static(__dirname + '/public/2nd_screen'));
app.use(express.static(__dirname + '/public/2nd_screen/js2'));

/*******************************************/
/*            SPECIAL STATUS               */
/*******************************************/
// When Express has executed all middleware/routes, and found that none of them responded then...
app.use(function(request, response)
{
	response.status(404);
	response.sendFile("public/2nd_screen/page_not_found.html", {root: __dirname });
});

/********************************************/
/*          	PORT                        */
//*******************************************/
http.listen(cfg.conf.port, function(request, response)
{
	console.log("Running at " + cfg.conf.host + " from " + __dirname);
});

/*******************************************/
/*           SERVER INCLUDED OBJECTS       */
/*******************************************/
eval(fs.readFileSync("sv/objects.js").toString());
eval(fs.readFileSync("sv/new_table.js").toString());
eval(fs.readFileSync("sv/new_table_seats.js").toString());
eval(fs.readFileSync("sv/get_table.js").toString());
eval(fs.readFileSync("sv/get_private_id.js").toString());
eval(fs.readFileSync("sv/table_general_socket.js").toString());
eval(fs.readFileSync("sv/players_general_socket.js").toString());
eval(fs.readFileSync("sv/send_qrcodes.js").toString());
eval(fs.readFileSync("sv/send_seats_infos.js").toString());
eval(fs.readFileSync("sv/send_bets.js").toString());
eval(fs.readFileSync("sv/get_seat.js").toString());
eval(fs.readFileSync("sv/cash_game/fisher_shuffle.js").toString());
eval(fs.readFileSync("sv/cash_game/timer.js").toString());
eval(fs.readFileSync("sv/cash_game/check_blanks.js").toString());
eval(fs.readFileSync("sv/cash_game/new_cashgame.js").toString());
eval(fs.readFileSync("sv/cash_game/show_down.js").toString());
eval(fs.readFileSync("sv/cash_game/end_game.js").toString());
eval(fs.readFileSync("sv/cash_game/evalhand.js").toString());
eval(fs.readFileSync("sv/cash_game/deal_board.js").toString());
eval(fs.readFileSync("sv/cash_game/remove_last_actions.js").toString());
eval(fs.readFileSync("sv/cash_game/check_bets.js").toString());

/*******************************************/
/*          SOCKET INTERACTIONS            */
/*******************************************/
var		tables = new Array();			// Array of tables objects.
var		table;							// Current table handler.
var		private_channel;				// Device private channel.
var		clients = [];

io.on("connection", function(socket)
{
    var client_ip = socket.request.connection.remoteAddress;
    var	curgame;

   	if (typeof table_id === "undefined")
    	return ;
    console.log("New connection from " + client_ip);
    if ((table = get_table(table_id, tables)) == "not found" && !device_client)
    {
    	var		deck = new Array('2c', '3c', '4c', '5c', '6c', '7c', '8c', '9c', 'tc', 'jc', 'qc', 'kc', '1c',
								'2s', '3s', '4s', '5s', '6s', '7s', '8s', '9s', 'ts', 'js', 'qs', 'ks', '1s',
								'2d', '3d', '4d', '5d', '6d', '7d', '8d', '9d', 'td', 'jd', 'qd', 'kd', '1d',
								'2h', '3h', '4h', '5h', '6h', '7h', '8h', '9h', 'th', 'jh', 'qh', 'kh', '1h');
    	console.log("Creating a new table...\nTable ID: " + table_id);
    	curgame = new Game(deck, -1, -1, cfg.conf.small_blind, -1, cfg.conf.big_blind, 0, 0, 0, 0, "waiting", 0, new Array());
	    table = new_table(table_id, 0, "waiting", new Array(),
	    	    +cfg.conf.start_bankroll, new_table_seats(), curgame, new Array(), new Array()); // We're also calling a function.
	    tables.push(table);
	    socket.join(table.id);
   		send_qrcodes(table, table.seats);
   		table.game.turn_to = "joiners";

		io.to(table.id).emit('tableId', table.id, get_table(table.id, tables), get_table(table.id, tables).game);

		socket.on('get tableId and tableGame', function(id) {
			io.to(id).emit('give tableId and tableGame', get_table(id, tables), get_table(id, tables).game);
		});

		socket.on('re init', function(table, game) {
			table.game.curbet = "0";
			game.moment = "river";
			remove_last_actions(table, 2);
			deal_river(table, game);
			evalhand(table, game);
			show_down(table, game);
		});
	}
   	if (device_client)
   	{
   		console.log(table.private_ids);
   		private_channel = table_id + seat_nb;//shortId.generate() + seat_nb;
   		if (!get_private_id(table.private_ids, seat_nb))
   			table.private_ids.push(private_channel);
   		socket.on("get private channel", function()
   		{
   			socket.emit("private channel", private_channel, seat_nb);
   		});
   		socket.join(private_channel);
   		console.log("Joining private channel " + private_channel);
		hide_qr(table, seat_nb);
   	}
	socket.on("disconnect", function() {
		re_qr(table, seat_nb);
	});
		//io.to(table.id).emit("double blind", cfg.conf.small_blind, cfg.conf.big_blind);
	/*  socket.on("get qrcodes", function()
	{
		send_qrcodes(table, table.seats);
	});*/
	socket.on("ask buttons", function()
	{
			if (table.game.highlights_pos)
			{
				io.to(table.id).emit("place button", "sb", table.game.sb_pos);	// Respect this sending order.
				io.to(table.id).emit("place button", "dealer", table.game.d_pos);
				io.to(table.id).emit("place button", "bb", table.game.bb_pos);
			}
			io.to(table.id).emit("highlights", table.game.highlights_pos);
	});
	socket.on('get pot amount', function() {
		socket.emit('pot amount', table.game.pot_amount);
	});
	socket.on('need Id', function() {
		io.to(table.id).emit('give Idx', table_id);
	});
	io.to(table.id).emit("pot modification", table.game.pot_amount);
	send_bets(table); // Currents bets on the table.
	socket_listens_players(socket, table);
    socket_listens_global_settings(socket, table, table.seats);	// Event handler for major events.
});
<|endoftext|>


<commit_before>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

/**
 * @name HitResult
 *
 * @class
 *
 * @extends CurveLocation
 */
HitResult = Base.extend(/** @lends HitResult# */{
	initialize: function(type, item, values) {
		this.type = type;
		this.item = item;
		if (values) {
			// Copy over passed values, depending on use case.
			// DOCS: HitResult#location, #segment, #point
			Base.each(values, function(value, key) {
				this[key] = value;
			}, this);
		}
	},

	statics: {
		/**
		 * Merges default options into options hash for #hitTest() calls, and
		 * marks as merged, to prevent repeated merging in nested calls.
		 *
		 * @private
		 */
		getOptions: function(point, options) {
			// TODO: Consier moving to HitResult / HitEvent?
			return options && options._merged ? options : Base.merge({
				// Use the converted options object to perform point conversion
				// only once.
				point: Point.read(arguments, 0, 1),
				// Type of item, for instanceof check: PathItem, TexItem, etc
				type: Item,
				// Tolerance
				tolerance: 2,
				// Hit the fill of items
				fill: true,
				// Hit the curves of path items, taking into account the stroke
				// width.
				stroke: true,
				// Hit the part of segments that curves pass through, excluding
				// its segments (Segment#point)
				segments: true,
				// Hit the parts of segments that define the curvature
				handles: false,
				// Only first or last segment hits on path (mutually exclusive
				// with segments: true)
				ends: false,
				// Hit test the center of the bounds
				center: false,
				// Hit test the corners and side-centers of the boudning box
				bounds: false,
				//  Hit items that are marked as guides
				guides: false,
				// Only hit selected objects
				selected: false,
				// Mark as merged, so next time Base.merge isn't called
				_merged: true
			}, options);
		}
	}
});
<commit_msg>Add comment about missing documentation.<commit_after>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

/**
 * @name HitResult
 *
 * @class
 *
 * @extends CurveLocation
 */
HitResult = Base.extend(/** @lends HitResult# */{
	initialize: function(type, item, values) {
		this.type = type;
		this.item = item;
		if (values) {
			// Copy over passed values, depending on use case.
			// DOCS: HitResult#location, #segment, #name, #point
			Base.each(values, function(value, key) {
				this[key] = value;
			}, this);
		}
	},

	statics: {
		/**
		 * Merges default options into options hash for #hitTest() calls, and
		 * marks as merged, to prevent repeated merging in nested calls.
		 *
		 * @private
		 */
		getOptions: function(point, options) {
			// TODO: Consier moving to HitResult / HitEvent?
			return options && options._merged ? options : Base.merge({
				// Use the converted options object to perform point conversion
				// only once.
				point: Point.read(arguments, 0, 1),
				// Type of item, for instanceof check: PathItem, TexItem, etc
				type: Item,
				// Tolerance
				tolerance: 2,
				// Hit the fill of items
				fill: true,
				// Hit the curves of path items, taking into account the stroke
				// width.
				stroke: true,
				// Hit the part of segments that curves pass through, excluding
				// its segments (Segment#point)
				segments: true,
				// Hit the parts of segments that define the curvature
				handles: false,
				// Only first or last segment hits on path (mutually exclusive
				// with segments: true)
				ends: false,
				// Hit test the center of the bounds
				center: false,
				// Hit test the corners and side-centers of the boudning box
				bounds: false,
				//  Hit items that are marked as guides
				guides: false,
				// Only hit selected objects
				selected: false,
				// Mark as merged, so next time Base.merge isn't called
				_merged: true
			}, options);
		}
	}
});
<|endoftext|>


<commit_before>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

var PathStyle = this.PathStyle = Base.extend(new function() {
	var keys = ['windingRule', 'resolution', 'strokeColor', 'strokeWidth',
			'strokeCap', 'strokeJoin', 'dashOffset','dashArray', 'miterLimit',
			'strokeOverprint', 'fillColor', 'fillOverprint'],
		strokeFlags = {
			strokeWidth: true,
			strokeCap: true,
			strokeJoin: true,
			miterLimit: true
		};

	var fields = {
		beans: true,

		initialize: function(style) {
			// Note: This relies on bean setters that get implicetly
			// called when setting values on this[key].
			for (var i = 0, l = style && keys.length; i < l; i++) {
				var key = keys[i],
					value = style[key];
				if (value !== undefined)
					this[key] = value;
			}
		},

		statics: {
			create: function(item) {
				var style = new PathStyle(PathStyle.dont);
				style._item = item;
				return style;
			}
		}
	};

	Item.inject(Base.each(keys, function(key) {
		var isColor = !!key.match(/Color$/),
			part = Base.capitalize(key),
			set = 'set' + part,
			get = 'get' + part;

		fields[set] = function(value) {
			var children = this._item && this._item._children;
			value = isColor ? Color.read(arguments) : value;
			if (children) {
				for (var i = 0, l = children.length; i < l; i++)
					children[i]._style[set](value);
			} else {
				var old = this['_' + key];
				if (old != value && !(old && old.equals && old.equals(value))) {
					this['_' + key] = value;
					if (this._item) {
						this._item._changed(ChangeFlags.STYLE
							| (strokeFlags[key] ? ChangeFlags.STROKE : 0));
					}
				}
			}
			return this;
		};

		fields[get] = function() {
			var children = this._item && this._item._children,
				style;
			// If this item has children, walk through all of them and see if
			// they all have the same style.
			if (children) {
				for (var i = 0, l = children.length; i < l; i++) {
					var childStyle = children[i]._style[get]();
					if (!style) {
						style = childStyle;
					} else if (style != childStyle) {
						// If there is another item with a different style,
						// the style is not defined:
						// PORT: Change this in Sg (currently returns null)
						return undefined;
					}
				}
				return style;
			} else {
				return this['_' + key];
			}
		};

		// 'this' = the Base.each() side-car = the object that is returned from
		// Base.each and injected into Item above:
		this[set] = function(value) {
			this._style[set](value);
			return this;
		};

		this[get] = function() {
			return this._style[get]();
		};
	}, { beans: true }));

	return fields;
});
<commit_msg>Change PathStyle to clone values in setters if they provide a clone function. This requires also using equals() wherevere they are checked to be the same or different.<commit_after>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

var PathStyle = this.PathStyle = Base.extend(new function() {
	var keys = ['windingRule', 'resolution', 'strokeColor', 'strokeWidth',
			'strokeCap', 'strokeJoin', 'dashOffset','dashArray', 'miterLimit',
			'strokeOverprint', 'fillColor', 'fillOverprint'],
		strokeFlags = {
			strokeWidth: true,
			strokeCap: true,
			strokeJoin: true,
			miterLimit: true
		};

	var fields = {
		beans: true,

		initialize: function(style) {
			// Note: This relies on bean setters that get implicetly
			// called when setting values on this[key].
			for (var i = 0, l = style && keys.length; i < l; i++) {
				var key = keys[i],
					value = style[key];
				if (value !== undefined)
					this[key] = value;
			}
		},

		statics: {
			create: function(item) {
				var style = new PathStyle(PathStyle.dont);
				style._item = item;
				return style;
			}
		}
	};

	Item.inject(Base.each(keys, function(key) {
		var isColor = !!key.match(/Color$/),
			part = Base.capitalize(key),
			set = 'set' + part,
			get = 'get' + part;

		fields[set] = function(value) {
			var children = this._item && this._item._children;
			value = isColor ? Color.read(arguments) : value;
			if (children) {
				for (var i = 0, l = children.length; i < l; i++)
					children[i]._style[set](value);
			} else {
				var old = this['_' + key];
				if (old != value && !(old && old.equals && old.equals(value))) {
					this['_' + key] = value && value.clone ? value.clone() : value;
					if (this._item) {
						this._item._changed(ChangeFlags.STYLE
							| (strokeFlags[key] ? ChangeFlags.STROKE : 0));
					}
				}
			}
			return this;
		};

		fields[get] = function() {
			var children = this._item && this._item._children,
				style;
			// If this item has children, walk through all of them and see if
			// they all have the same style.
			if (children) {
				for (var i = 0, l = children.length; i < l; i++) {
					var childStyle = children[i]._style[get]();
					if (!style) {
						style = childStyle;
					} else if (style != childStyle && !(style && style.equals
							&& style.equals(childStyle))) {
						// If there is another item with a different style,
						// the style is not defined:
						// PORT: Change this in Sg (currently returns null)
						return undefined;
					}
				}
				return style;
			} else {
				return this['_' + key];
			}
		};

		// Style-getters and setters for Item:
		// 'this' = the Base.each() side-car = the object that is returned from
		// Base.each and injected into Item above:
		this[set] = function(value) {
			this._style[set](value);
			return this;
		};

		this[get] = function() {
			return this._style[get]();
		};
	}, { beans: true }));

	return fields;
});
<|endoftext|>


<commit_before>var fs         = require('fs'),
    exec       = require('child_process').exec,
    sys        = require('sys'),
    path       = require('path'),
    http       = require('http'),
    formidable = require('./lib/formidable'),
    paperboy   = require('./lib/paperboy');

var PUBLIC = path.join(path.dirname(__filename), 'public');
var devmode = true;
var port = 8126;
if (devmode){
  port = 8124;
}
var statuses = {};
var progresses = {};
var metadata   = {};

var child;

function puts(error, stdout, stderr) { sys.puts(stdout) };
function logsAndFlagsFresh(error,uuid,stdout,stderr){
  sys.puts(stdout);
  var setFresh = function(){
    statuses[uuid]="transcription fresh";
    sys.print("\nProcessed uuid: "+uuid+" set to: "+statuses[uuid]+"\n\n");
  }
  return setFresh;
};

http.createServer(function(req, res) {
  /*TODO check for API key and non banned install id in this regex */
  regex = new RegExp('/upload/(.+)');
  match = regex.exec(req.url);
  if (match && req.method.toLowerCase() == 'post') {
    var uuid = match[1];
    uuid = uuid.replace(/.mp3/,"");
    uuid = uuid.replace(/.srt/,"");
    uuid = uuid.replace(/_client/,"");
    uuid = uuid.replace(/_server/,"");
    sys.print("Receiving transcription request: "+uuid+'\n');

    var form = new formidable.IncomingForm();
    form.uploadDir = './data';
    form.keepExtensions = true;

    // keep track of progress.
    form.addListener('progress', function(recvd, expected) {
      progress = (recvd / expected * 100).toFixed(2);
      progresses[uuid] = progress;
    });

    form.parse(req, function(error, fields, files) {
      var path     = files['file']['path'],
          filename = files['file']['filename'],
          mime     = files['file']['mime'];
      sys.print('Users file: '+filename + ':filename\nIs server file: ' + path +  ':path\n');

      /*
       * Rename to original name (sanitize, although it shoudl already be sanitized by the android client.)
       */
      var safeFilename=filename.replace(/[^\w\.]/g,"_");
      safeFilename=safeFilename.replace(/[;:|@&*/\\]/g,"_");
      //safeFilename=safeFilename.replace(/_client\./,".");
      safeFilename=safeFilename.replace(/\.mp3/,".amr");
      var tempdir = "../nodejs-pocketsphinxtemp/";
      fs.renameSync(path,tempdir+safeFilename);
      safeFilenameServer = safeFilename.replace(/_client/,"_server");

      var subtitleregex = new RegExp('(.+).srt');
      var matchsubtitle = subtitleregex.exec(filename);
      res.writeHead(200, {'content-type': 'text/html'});
      if(matchsubtitle){
        if(statuses[uuid] === "dictation recieved"){
          res.write("Transcription machine is thinking...\n");
        }else{
          res.write("Processing.\n");
        }
        res.write(filename + ':filename\n' + path + ':path\n');

        if (statuses[uuid] === "dictation received"){
          var runTranscription = function(uuid) {
            var uuidchange = uuid; //local variable bound by closure
            exec("sh audio2text.sh "+ safeFilename.replace(/_client\.srt/,""),puts);
            var setFresh = function(){
              statuses[uuidchange]="transcription fresh";
              sys.print("Processed uuid: "+uuidchange+" set to: "+statuses[uuidchange]);
            }
            //http://stackoverflow.com/questions/111102/how-do-javascript-closures-work
            return setFresh;
          }
          var resultFresh = runTranscription(uuid);
          setTimeout(resultFresh,30000); //this is running before exec finishes.
        }

        /*
         * copy the file to the response, if the status was dictation received
         * and we just got the client .srt, then thi should copy the client .srt
         * with the timecode from audio2text saying that the transcription
         * will apear below when it is ready
         *
         * other wise if the transcription is fresh it will provide
         * the transcription
         */
        fs.readFile(tempdir+safeFilenameServer,"binary", function(err, file){
          if(err){
            //res.sendHeader(500, {"Content-Type": "text/plain"});
            sys.print("There was an err reading the file"+err+"\nReturning nothing to the user\n");
            //res.write("The machine transcription hasn't returned any hypotheses yet.\n");
            //sys.print("The machine transcription hasn't returned any hypotheses yet.\n");

          }else{
            sys.print("\nReturning the machine transcription to the user.\n");
            sys.print("___________________________+++_____________________\n");
            res.write(file,"binary");
            res.end();
            sys.print(file);
            sys.print("___________________________+++_____________________\n");
            exec("date",puts);
            sys.print("Returned above transcription to user.\n");
          }
        });
        statuses[uuid]="transcription nothing fresh"
        sys.print("Server's transcription was returned to client. "+'\n');
      }else{
        //if the user just sent an mp3/amr
        res.write("Dictation sent for transcription.\n");
        res.write(filename + ':filename\n' + path + ':path\n');
        res.end();
        statuses[uuid]="dictation received";
      }
      exec("date",puts);
      sys.print("\tFinished upload processing."+'\n');
    });

    return;
  }

  // (update) metadata
  regex = new RegExp('/update/(.+)');
  match = regex.exec(req.url);
  if (match && req.method.toLowerCase() == 'post') {
    uuid = match[1];
    var form = new formidable.IncomingForm();
    form.addListener('field', function(name, value) {
      sys.print("fresh metadata for "+uuid+": "+name+" => "+value+"\n")
      metadata[name] = value;
    });
    form.parse(req);
  }
  // respond to status queries
  regex = new RegExp('/status/(.+)');
  match = regex.exec(req.url);
  if (match) {
    uuid = match[1];
    uuid = uuid.replace(/.mp3/,"");
    uuid = uuid.replace(/.srt/,"");
    uuid = uuid.replace(/_client/,"");
    uuid = uuid.replace(/_server/,"");

    res.writeHead(200, {'content-type': 'application/json'});
    res.write(JSON.stringify({'status': statuses[uuid]}));
    res.end();

    exec("date",puts);
    sys.print(uuid+"\nReplied to status request: "+JSON.stringify({'status': statuses[uuid]}));
    sys.print("\n\n");
  }

  // respond to progress queries.
  regex = new RegExp('/progress/(.+)');
  match = regex.exec(req.url);
  if (match) {
    uuid = match[1];
    res.writeHead(200, {'content-type': 'application/json'});
    res.write(JSON.stringify({'progress': progresses[uuid]}));
    res.end();
  }

  // let paperboy handle any static content.
  paperboy
    .deliver(PUBLIC, req, res)
    .after(function(statCode) {
      sys.log('Served Request: ' + statCode + ' ' + req.url)
    })
    .otherwise(function() {
      res.writeHead(404, {'Content-Type': 'text/plain'});
      res.write('Not Found');
      res.end();
    });

}).listen(port);

sys.log('ready at http://localhost:'+port+'/')
<commit_msg>running sphinx any time client asks for transcript, this gives client more control over the freshness of the transcript and can be refactored later<commit_after>var fs         = require('fs'),
    exec       = require('child_process').exec,
    sys        = require('sys'),
    path       = require('path'),
    http       = require('http'),
    formidable = require('./lib/formidable'),
    paperboy   = require('./lib/paperboy');

var PUBLIC = path.join(path.dirname(__filename), 'public');
var devmode = true;
var port = 8126;
if (devmode){
  port = 8124;
}
var statuses = {};
var progresses = {};
var metadata   = {};

var child;

function puts(error, stdout, stderr) { sys.puts(stdout) };
function logsAndFlagsFresh(error,uuid,stdout,stderr){
  sys.puts(stdout);
  var setFresh = function(){
    statuses[uuid]="transcription fresh";
    sys.print("\nProcessed uuid: "+uuid+" set to: "+statuses[uuid]+"\n\n");
  }
  return setFresh;
};

http.createServer(function(req, res) {
  /*TODO check for API key and non banned install id in this regex */
  regex = new RegExp('/upload/(.+)');
  match = regex.exec(req.url);
  if (match && req.method.toLowerCase() == 'post') {
    var uuid = match[1];
    uuid = uuid.replace(/.mp3/,"");
    uuid = uuid.replace(/.srt/,"");
    uuid = uuid.replace(/_client/,"");
    uuid = uuid.replace(/_server/,"");
    sys.print("Receiving transcription request: "+uuid+'\n');

    var form = new formidable.IncomingForm();
    form.uploadDir = './data';
    form.keepExtensions = true;

    // keep track of progress.
    form.addListener('progress', function(recvd, expected) {
      progress = (recvd / expected * 100).toFixed(2);
      progresses[uuid] = progress;
    });

    form.parse(req, function(error, fields, files) {
      var path     = files['file']['path'],
          filename = files['file']['filename'],
          mime     = files['file']['mime'];
      sys.print('Users file: '+filename + ':filename\nIs server file: ' + path +  ':path\n');

      /*
       * Rename to original name (sanitize, although it shoudl already be sanitized by the android client.)
       */
      var safeFilename=filename.replace(/[^\w\.]/g,"_");
      safeFilename=safeFilename.replace(/[;:|@&*/\\]/g,"_");
      //safeFilename=safeFilename.replace(/_client\./,".");
      safeFilename=safeFilename.replace(/\.mp3/,".amr");
      var tempdir = "../nodejs-pocketsphinxtemp/";
      fs.renameSync(path,tempdir+safeFilename);
      safeFilenameServer = safeFilename.replace(/_client/,"_server");

      var subtitleregex = new RegExp('(.+).srt');
      var matchsubtitle = subtitleregex.exec(filename);
      res.writeHead(200, {'content-type': 'text/html'});
      if(matchsubtitle){
        if(statuses[uuid] === "dictation recieved"){
          res.write("Transcription machine is thinking...\n");
        }else{
          res.write("Processing.\n");
        }
        res.write(filename + ':filename\n' + path + ':path\n');
       //not using closure to set fresh, instead, running sphinx every time the user uploads the srt of the same uuid. this lets the user control the transcription more.
        if (statuses[uuid] === "dictation received" || statuses[uuid] === "transcription nothing fresh" ){
          var runTranscription = function(uuid) {
            var uuidchange = uuid; //local variable bound by closure
            exec("sh audio2text.sh "+ safeFilename.replace(/_client\.srt/,""),puts);
            var setFresh = function(){
              statuses[uuidchange]="transcription fresh";
              sys.print("Processed uuid: "+uuidchange+" set to: "+statuses[uuidchange]);
            }
            //http://stackoverflow.com/questions/111102/how-do-javascript-closures-work
            return setFresh;
          }
          var resultFresh = runTranscription(uuid);
          setTimeout(resultFresh,30000); //this is running before exec finishes.
        }

        /*
         * copy the file to the response, if the status was dictation received
         * and we just got the client .srt, then thi should copy the client .srt
         * with the timecode from audio2text saying that the transcription
         * will apear below when it is ready
         *
         * other wise if the transcription is fresh it will provide
         * the transcription
         */
        fs.readFile(tempdir+safeFilenameServer,"binary", function(err, file){
          if(err){
            //res.sendHeader(500, {"Content-Type": "text/plain"});
            sys.print("There was an err reading the file"+err+"\nReturning nothing to the user\n");
            //res.write("The machine transcription hasn't returned any hypotheses yet.\n");
            //sys.print("The machine transcription hasn't returned any hypotheses yet.\n");

          }else{
            sys.print("\nReturning the machine transcription to the user.\n");
            sys.print("___________________________+++_____________________\n");
            res.write(file,"binary");
            res.end();
            sys.print(file);
            sys.print("___________________________+++_____________________\n");
            exec("date",puts);
            sys.print("Returned above transcription to user.\n");
          }
        });
        statuses[uuid]="transcription nothing fresh"
        sys.print("Server's transcription was returned to client. "+'\n');
      }else{
        //if the user just sent an mp3/amr
        res.write("Dictation sent for transcription.\n");
        res.write(filename + ':filename\n' + path + ':path\n');
        res.end();
        statuses[uuid]="dictation received";
      }
      exec("date",puts);
      sys.print("\tFinished upload processing."+'\n');
    });

    return;
  }

  // (update) metadata
  regex = new RegExp('/update/(.+)');
  match = regex.exec(req.url);
  if (match && req.method.toLowerCase() == 'post') {
    uuid = match[1];
    var form = new formidable.IncomingForm();
    form.addListener('field', function(name, value) {
      sys.print("fresh metadata for "+uuid+": "+name+" => "+value+"\n")
      metadata[name] = value;
    });
    form.parse(req);
  }
  // respond to status queries
  regex = new RegExp('/status/(.+)');
  match = regex.exec(req.url);
  if (match) {
    uuid = match[1];
    uuid = uuid.replace(/.mp3/,"");
    uuid = uuid.replace(/.srt/,"");
    uuid = uuid.replace(/_client/,"");
    uuid = uuid.replace(/_server/,"");

    res.writeHead(200, {'content-type': 'application/json'});
    res.write(JSON.stringify({'status': statuses[uuid]}));
    res.end();

    exec("date",puts);
    sys.print(uuid+"\nReplied to status request: "+JSON.stringify({'status': statuses[uuid]}));
    sys.print("\n\n");
  }

  // respond to progress queries.
  regex = new RegExp('/progress/(.+)');
  match = regex.exec(req.url);
  if (match) {
    uuid = match[1];
    res.writeHead(200, {'content-type': 'application/json'});
    res.write(JSON.stringify({'progress': progresses[uuid]}));
    res.end();
  }

  // let paperboy handle any static content.
  paperboy
    .deliver(PUBLIC, req, res)
    .after(function(statCode) {
      sys.log('Served Request: ' + statCode + ' ' + req.url)
    })
    .otherwise(function() {
      res.writeHead(404, {'Content-Type': 'text/plain'});
      res.write('Not Found');
      res.end();
    });

}).listen(port);

sys.log('ready at http://localhost:'+port+'/')
<|endoftext|>


<commit_before>'use strict';
const path = require('path');
const fs = require('fs');
const _ = require('lodash');
const globby = require('globby');
const debug = require('debug')('yeoman:environment');
const spawn = require('cross-spawn');

const win32 = process.platform === 'win32';
const nvm = process.env.NVM_HOME;

/**
 * @mixin
 * @alias env/resolver
 */
const resolver = module.exports;

/**
 * Search for generators and their sub generators.
 *
 * A generator is a `:lookup/:name/index.js` file placed inside an npm package.
 *
 * Defaults lookups are:
 *   - ./
 *   - generators/
 *   - lib/generators/
 *
 * So this index file `node_modules/generator-dummy/lib/generators/yo/index.js` would be
 * registered as `dummy:yo` generator.
 *
 * @param {boolean|Object} [options]
 * @param {boolean} [options.localOnly = false] - Set true to skip lookups of
 *                                               globally-installed generators.
 * @param {string|Array} [options.packagePaths] - Paths to look for generators.
 * @param {string|Array} [options.npmPaths] - Repository paths to look for generators packages.
 * @param {string|Array} [options.filePatterns='*\/index.js'] - File pattern to look for.
 * @param {string|Array} [options.packagePatterns='generator-*'] - Package pattern to look for.
 * @param {function} cb - Callback called once the lookup is done. Take err as first
 *                        parameter.
 */
resolver.lookup = function (options = {localOnly: false}, cb) {
  // Resolve signature where options is omitted.
  if (typeof options === 'function') {
    cb = options;
    options = {localOnly: false};
  // Resolve signature where options is boolean.
  } else if (typeof options === 'boolean') {
    options = {localOnly: options};
  }

  options.filePatterns = options.filePatterns || this.lookups.map(prefix => path.join(prefix, '*/index.js'));

  if (options.packagePaths) {
    options.packagePaths = Array.isArray(options.packagePaths) ? options.packagePaths : [options.packagePaths];
  } else {
    options.npmPaths = options.npmPaths || this.getNpmPaths(options).reverse();
    options.packagePaths = this.findGeneratorsIn(options.npmPaths, options);
  }

  debug('Running lookup with options %o', options);

  for (const modulePath of options.packagePaths) {
    for (const filename of globby.sync(options.filePatterns, {cwd: modulePath, absolute: true, deep: 1})) {
      this._tryRegistering(filename, modulePath);
    }
  }

  if (typeof cb === 'function') {
    return cb(null);
  }
};

/**
 * Search npm for every available generators.
 * Generators are npm packages who's name start with `generator-` and who're placed in the
 * top level `node_module` path. They can be installed globally or locally.
 *
 * @param {Array}  List of search paths
 * @param {Object}  [options]
 * @param {boolean} [options.packagePatterns='generator-*'] - Pattern pattern.
 * @return {Array} List of the generator modules path
 */
resolver.findGeneratorsIn = function (searchPaths, options = {}) {
  if (typeof options === 'string') {
    options = {packagePatterns: options};
  }

  options.packagePatterns = options.packagePatterns || 'generator-*';
  searchPaths = Array.isArray(searchPaths) ? searchPaths : [searchPaths];

  // Remove undefined values and convert paths to absolute
  searchPaths = searchPaths.filter(npmPath => npmPath).map(npmPath => path.resolve(npmPath));

  let modules = [];
  for (const root of searchPaths) {
    // Some folders might not be readable to the current user. For those, we add a try
    // catch to handle the error gracefully as globby doesn't have an option to skip
    // restricted folders.
    try {
      modules = modules.concat(globby.sync(
        options.packagePatterns,
        {cwd: root, onlyFiles: false, absolute: true, deep: 0}
      ));

      // To limit recursive lookups into non-namespace folders within globby,
      // fetch all namespaces in root, then search each namespace separately
      // for generator modules
      const scopes = globby.sync(
        ['@*'],
        {cwd: root, onlyFiles: false, absolute: true, deep: 0}
      );

      for (const scope of scopes) {
        modules = modules.concat(globby.sync(
          options.packagePatterns,
          {cwd: scope, onlyFiles: false, absolute: true, deep: 0}
        ));
      }
    } catch (err) {
      debug('Could not access %s (%s)', root, err);
    }
  }

  return modules;
};

/**
 * Try registering a Generator to this environment.
 * @private
 * @param  {String} generatorReference A generator reference, usually a file path.
 */
resolver._tryRegistering = function (generatorReference, packagePath) {
  let namespace;
  const realPath = fs.realpathSync(generatorReference);

  try {
    debug('found %s, trying to register', generatorReference);

    if (realPath !== generatorReference) {
      namespace = this.namespace(generatorReference);
    }

    this.register(realPath, namespace, packagePath);
  } catch (err) {
    console.error('Unable to register %s (Error: %s)', generatorReference, err.message);
  }
};

/**
 * Get the npm lookup directories (`node_modules/`)
 * @param {boolean|Object} [options]
 * @param {boolean} [options.localOnly = false] - Set true to skip lookups of
 *                                               globally-installed generators.
 * @param {boolean} [options.filterPaths = false] - Remove paths that don't ends
 *                       with a supported path (don't touch at NODE_PATH paths).
 * @return {Array} lookup paths
 */
resolver.getNpmPaths = function (options = {}) {
  // Resolve signature where options is boolean (localOnly).
  if (typeof options === 'boolean') {
    options = {localOnly: options};
  }
  // Start with the local paths.
  let paths = this._getLocalNpmPaths();

  // Append global paths, unless they should be excluded.
  if (!options.localOnly) {
    paths = paths.concat(this._getGlobalNpmPaths(options.filterPaths));
  }

  return _.uniq(paths);
};

/**
 * Get the local npm lookup directories
 * @private
 * @return {Array} lookup paths
 */
resolver._getLocalNpmPaths = function () {
  const paths = [];

  // Walk up the CWD and add `node_modules/` folder lookup on each level
  process.cwd().split(path.sep).forEach((part, i, parts) => {
    let lookup = path.join(...parts.slice(0, i + 1), 'node_modules');

    if (!win32) {
      lookup = `/${lookup}`;
    }

    paths.push(lookup);
  });

  return _.uniq(paths.reverse());
};

/**
 * Get the global npm lookup directories
 * Reference: https://nodejs.org/api/modules.html
 * @private
 * @return {Array} lookup paths
 */
resolver._getGlobalNpmPaths = function (filterPaths = false) {
  let paths = [];

  // Node.js will search in the following list of GLOBAL_FOLDERS:
  // 1: $HOME/.node_modules
  // 2: $HOME/.node_libraries
  // 3: $PREFIX/lib/node
  const filterValidNpmPath = function (path, ignore = false) {
    return ignore ? path : ['/node_modules', '/.node_modules', '/.node_libraries', '/node'].find(dir => path.endsWith(dir)) ? path : undefined;
  };

  // Default paths for each system
  if (nvm) {
    paths.push(path.join(process.env.NVM_HOME, process.version, 'node_modules'));
  } else if (win32) {
    paths.push(path.join(process.env.APPDATA, 'npm/node_modules'));
  } else {
    paths.push('/usr/lib/node_modules');
    paths.push('/usr/local/lib/node_modules');
  }

  // Add NVM prefix directory
  if (process.env.NVM_PATH) {
    paths.push(path.join(path.dirname(process.env.NVM_PATH), 'node_modules'));
  }

  // Adding global npm directories
  // We tried using npm to get the global modules path, but it haven't work out
  // because of bugs in the parseable implementation of `ls` command and mostly
  // performance issues. So, we go with our best bet for now.
  if (process.env.NODE_PATH) {
    paths = _.compact(process.env.NODE_PATH.split(path.delimiter)).concat(paths);
  }

  // Global node_modules should be 4 or 2 directory up this one (most of the time)
  // Ex: /usr/another_global/node_modules/yeoman-denerator/node_modules/yeoman-environment/lib (1 level dependency)
  paths.push(filterValidNpmPath(path.join(__dirname, '../../../..'), !filterPaths));
  // Ex: /usr/another_global/node_modules/yeoman-environment/lib (installed directly)
  paths.push(path.join(__dirname, '../..'));

  // Get yarn global directory and infer the module paths from there
  const testYarn = spawn.sync('yarn', ['global', 'dir'], {encoding: 'utf8'});
  if (!testYarn.error) {
    const yarnBase = testYarn.stdout.trim();
    paths.push(path.resolve(yarnBase, 'node_modules'));
    paths.push(path.resolve(yarnBase, '../link/'));
  }

  // Get npm global prefix and infer the module paths from there
  const testNpm = spawn.sync('npm', ['-g', 'prefix'], {encoding: 'utf8'});
  if (!testNpm.error) {
    const npmBase = testNpm.stdout.trim();
    const globalInstall = win32 ? `${npmBase}/node_modules` : `${npmBase}/lib/node_modules`;
    paths.push(path.resolve(globalInstall));
  }

  // Adds support for generator resolving when yeoman-generator has been linked
  if (process.argv[1]) {
    paths.push(filterValidNpmPath(path.join(path.dirname(process.argv[1]), '../..'), !filterPaths));
  }

  return _.uniq(paths.filter(path => path).reverse());
};

/**
 * Get or create an alias.
 *
 * Alias allows the `get()` and `lookup()` methods to search in alternate
 * filepath for a given namespaces. It's used for example to map `generator-*`
 * npm package to their namespace equivalent (without the generator- prefix),
 * or to default a single namespace like `angular` to `angular:app` or
 * `angular:all`.
 *
 * Given a single argument, this method acts as a getter. When both name and
 * value are provided, acts as a setter and registers that new alias.
 *
 * If multiple alias are defined, then the replacement is recursive, replacing
 * each alias in reverse order.
 *
 * An alias can be a single String or a Regular Expression. The finding is done
 * based on .match().
 *
 * @param {String|RegExp} match
 * @param {String} value
 *
 * @example
 *
 *     env.alias(/^([a-zA-Z0-9:\*]+)$/, 'generator-$1');
 *     env.alias(/^([^:]+)$/, '$1:app');
 *     env.alias(/^([^:]+)$/, '$1:all');
 *     env.alias('foo');
 *     // => generator-foo:all
 */
resolver.alias = function (match, value) {
  if (match && value) {
    this.aliases.push({
      match: match instanceof RegExp ? match : new RegExp(`^${match}$`),
      value
    });
    return this;
  }

  const aliases = this.aliases.slice(0).reverse();

  return aliases.reduce((res, alias) => {
    if (!alias.match.test(res)) {
      return res;
    }

    return res.replace(alias.match, alias.value);
  }, match);
};
<commit_msg>Change lookup to return structure with package details (#146)<commit_after>'use strict';
const path = require('path');
const fs = require('fs');
const _ = require('lodash');
const globby = require('globby');
const debug = require('debug')('yeoman:environment');
const spawn = require('cross-spawn');

const win32 = process.platform === 'win32';
const nvm = process.env.NVM_HOME;

/**
 * @mixin
 * @alias env/resolver
 */
const resolver = module.exports;

/**
 * Search for generators and their sub generators.
 *
 * A generator is a `:lookup/:name/index.js` file placed inside an npm package.
 *
 * Defaults lookups are:
 *   - ./
 *   - generators/
 *   - lib/generators/
 *
 * So this index file `node_modules/generator-dummy/lib/generators/yo/index.js` would be
 * registered as `dummy:yo` generator.
 *
 * @param {boolean|Object} [options]
 * @param {boolean} [options.localOnly = false] - Set true to skip lookups of
 *                                               globally-installed generators.
 * @param {string|Array} [options.packagePaths] - Paths to look for generators.
 * @param {string|Array} [options.npmPaths] - Repository paths to look for generators packages.
 * @param {string|Array} [options.filePatterns='*\/index.js'] - File pattern to look for.
 * @param {string|Array} [options.packagePatterns='generator-*'] - Package pattern to look for.
 * @param {function} cb - Callback called once the lookup is done. Take err as first
 *                        parameter.
 * @return {Array} List of generators
 */
resolver.lookup = function (options = {localOnly: false}, cb) {
  // Resolve signature where options is omitted.
  if (typeof options === 'function') {
    cb = options;
    options = {localOnly: false};
  // Resolve signature where options is boolean.
  } else if (typeof options === 'boolean') {
    options = {localOnly: options};
  }

  options.filePatterns = options.filePatterns || this.lookups.map(prefix => path.join(prefix, '*/index.js'));

  if (options.packagePaths) {
    options.packagePaths = Array.isArray(options.packagePaths) ? options.packagePaths : [options.packagePaths];
  } else {
    options.npmPaths = options.npmPaths || this.getNpmPaths(options).reverse();
    options.packagePaths = this.findGeneratorsIn(options.npmPaths, options);
  }

  debug('Running lookup with options %o', options);

  const generators = [];
  for (const packagePath of options.packagePaths) {
    for (const generatorPath of globby.sync(options.filePatterns, {cwd: packagePath, absolute: true, deep: 1})) {
      const namespace = this.namespace(generatorPath);
      const registered = this._tryRegistering(generatorPath, packagePath, namespace);
      generators.push({generatorPath, packagePath, namespace, registered});
    }
  }

  if (typeof cb === 'function') {
    return cb(null);
  }
  return generators;
};

/**
 * Search npm for every available generators.
 * Generators are npm packages who's name start with `generator-` and who're placed in the
 * top level `node_module` path. They can be installed globally or locally.
 *
 * @param {Array}  List of search paths
 * @param {Object}  [options]
 * @param {boolean} [options.packagePatterns='generator-*'] - Pattern pattern.
 * @return {Array} List of the generator modules path
 */
resolver.findGeneratorsIn = function (searchPaths, options = {}) {
  if (typeof options === 'string') {
    options = {packagePatterns: options};
  }

  options.packagePatterns = options.packagePatterns || 'generator-*';
  searchPaths = Array.isArray(searchPaths) ? searchPaths : [searchPaths];

  // Remove undefined values and convert paths to absolute
  searchPaths = searchPaths.filter(npmPath => npmPath).map(npmPath => path.resolve(npmPath));

  let modules = [];
  for (const root of searchPaths) {
    // Some folders might not be readable to the current user. For those, we add a try
    // catch to handle the error gracefully as globby doesn't have an option to skip
    // restricted folders.
    try {
      modules = modules.concat(globby.sync(
        options.packagePatterns,
        {cwd: root, onlyFiles: false, absolute: true, deep: 0}
      ));

      // To limit recursive lookups into non-namespace folders within globby,
      // fetch all namespaces in root, then search each namespace separately
      // for generator modules
      const scopes = globby.sync(
        ['@*'],
        {cwd: root, onlyFiles: false, absolute: true, deep: 0}
      );

      for (const scope of scopes) {
        modules = modules.concat(globby.sync(
          options.packagePatterns,
          {cwd: scope, onlyFiles: false, absolute: true, deep: 0}
        ));
      }
    } catch (err) {
      debug('Could not access %s (%s)', root, err);
    }
  }

  return modules;
};

/**
 * Try registering a Generator to this environment.
 * @private
 * @param  {String} generatorReference A generator reference, usually a file path.
 * @param  {String} [packagePath] - Generator's package path.
 * @param  {String} [namespace] - namespace of the generator.
 * @return {boolean} true if the generator have been registered.
 */
resolver._tryRegistering = function (generatorReference, packagePath, namespace) {
  const realPath = fs.realpathSync(generatorReference);

  try {
    debug('found %s, trying to register', generatorReference);

    if (!namespace && realPath !== generatorReference) {
      namespace = this.namespace(generatorReference);
    }

    this.register(realPath, namespace, packagePath);
    return true;
  } catch (err) {
    console.error('Unable to register %s (Error: %s)', generatorReference, err.message);
    return false;
  }
};

/**
 * Get the npm lookup directories (`node_modules/`)
 * @param {boolean|Object} [options]
 * @param {boolean} [options.localOnly = false] - Set true to skip lookups of
 *                                               globally-installed generators.
 * @param {boolean} [options.filterPaths = false] - Remove paths that don't ends
 *                       with a supported path (don't touch at NODE_PATH paths).
 * @return {Array} lookup paths
 */
resolver.getNpmPaths = function (options = {}) {
  // Resolve signature where options is boolean (localOnly).
  if (typeof options === 'boolean') {
    options = {localOnly: options};
  }
  // Start with the local paths.
  let paths = this._getLocalNpmPaths();

  // Append global paths, unless they should be excluded.
  if (!options.localOnly) {
    paths = paths.concat(this._getGlobalNpmPaths(options.filterPaths));
  }

  return _.uniq(paths);
};

/**
 * Get the local npm lookup directories
 * @private
 * @return {Array} lookup paths
 */
resolver._getLocalNpmPaths = function () {
  const paths = [];

  // Walk up the CWD and add `node_modules/` folder lookup on each level
  process.cwd().split(path.sep).forEach((part, i, parts) => {
    let lookup = path.join(...parts.slice(0, i + 1), 'node_modules');

    if (!win32) {
      lookup = `/${lookup}`;
    }

    paths.push(lookup);
  });

  return _.uniq(paths.reverse());
};

/**
 * Get the global npm lookup directories
 * Reference: https://nodejs.org/api/modules.html
 * @private
 * @return {Array} lookup paths
 */
resolver._getGlobalNpmPaths = function (filterPaths = false) {
  let paths = [];

  // Node.js will search in the following list of GLOBAL_FOLDERS:
  // 1: $HOME/.node_modules
  // 2: $HOME/.node_libraries
  // 3: $PREFIX/lib/node
  const filterValidNpmPath = function (path, ignore = false) {
    return ignore ? path : ['/node_modules', '/.node_modules', '/.node_libraries', '/node'].find(dir => path.endsWith(dir)) ? path : undefined;
  };

  // Default paths for each system
  if (nvm) {
    paths.push(path.join(process.env.NVM_HOME, process.version, 'node_modules'));
  } else if (win32) {
    paths.push(path.join(process.env.APPDATA, 'npm/node_modules'));
  } else {
    paths.push('/usr/lib/node_modules');
    paths.push('/usr/local/lib/node_modules');
  }

  // Add NVM prefix directory
  if (process.env.NVM_PATH) {
    paths.push(path.join(path.dirname(process.env.NVM_PATH), 'node_modules'));
  }

  // Adding global npm directories
  // We tried using npm to get the global modules path, but it haven't work out
  // because of bugs in the parseable implementation of `ls` command and mostly
  // performance issues. So, we go with our best bet for now.
  if (process.env.NODE_PATH) {
    paths = _.compact(process.env.NODE_PATH.split(path.delimiter)).concat(paths);
  }

  // Global node_modules should be 4 or 2 directory up this one (most of the time)
  // Ex: /usr/another_global/node_modules/yeoman-denerator/node_modules/yeoman-environment/lib (1 level dependency)
  paths.push(filterValidNpmPath(path.join(__dirname, '../../../..'), !filterPaths));
  // Ex: /usr/another_global/node_modules/yeoman-environment/lib (installed directly)
  paths.push(path.join(__dirname, '../..'));

  // Get yarn global directory and infer the module paths from there
  const testYarn = spawn.sync('yarn', ['global', 'dir'], {encoding: 'utf8'});
  if (!testYarn.error) {
    const yarnBase = testYarn.stdout.trim();
    paths.push(path.resolve(yarnBase, 'node_modules'));
    paths.push(path.resolve(yarnBase, '../link/'));
  }

  // Get npm global prefix and infer the module paths from there
  const testNpm = spawn.sync('npm', ['-g', 'prefix'], {encoding: 'utf8'});
  if (!testNpm.error) {
    const npmBase = testNpm.stdout.trim();
    const globalInstall = win32 ? `${npmBase}/node_modules` : `${npmBase}/lib/node_modules`;
    paths.push(path.resolve(globalInstall));
  }

  // Adds support for generator resolving when yeoman-generator has been linked
  if (process.argv[1]) {
    paths.push(filterValidNpmPath(path.join(path.dirname(process.argv[1]), '../..'), !filterPaths));
  }

  return _.uniq(paths.filter(path => path).reverse());
};

/**
 * Get or create an alias.
 *
 * Alias allows the `get()` and `lookup()` methods to search in alternate
 * filepath for a given namespaces. It's used for example to map `generator-*`
 * npm package to their namespace equivalent (without the generator- prefix),
 * or to default a single namespace like `angular` to `angular:app` or
 * `angular:all`.
 *
 * Given a single argument, this method acts as a getter. When both name and
 * value are provided, acts as a setter and registers that new alias.
 *
 * If multiple alias are defined, then the replacement is recursive, replacing
 * each alias in reverse order.
 *
 * An alias can be a single String or a Regular Expression. The finding is done
 * based on .match().
 *
 * @param {String|RegExp} match
 * @param {String} value
 *
 * @example
 *
 *     env.alias(/^([a-zA-Z0-9:\*]+)$/, 'generator-$1');
 *     env.alias(/^([^:]+)$/, '$1:app');
 *     env.alias(/^([^:]+)$/, '$1:all');
 *     env.alias('foo');
 *     // => generator-foo:all
 */
resolver.alias = function (match, value) {
  if (match && value) {
    this.aliases.push({
      match: match instanceof RegExp ? match : new RegExp(`^${match}$`),
      value
    });
    return this;
  }

  const aliases = this.aliases.slice(0).reverse();

  return aliases.reduce((res, alias) => {
    if (!alias.match.test(res)) {
      return res;
    }

    return res.replace(alias.match, alias.value);
  }, match);
};
<|endoftext|>


<commit_before>var express = require('express'),
	bodyParser = require('body-parser'),
	basicAuth = require('basic-auth-connect'),
	redis = require("redis"),
	url = require('url'),
	client;

require("redis-scanstreams")(redis);

if (process.env.REDISTOGO_URL) {
	var redisURL = url.parse(process.env.REDISTOGO_URL);

	client = redis.createClient(redisURL.port, redisURL.hostname, {no_ready_check: true});
	client.auth(redisURL.auth.split(":")[1]);
} else {
    client = redis.createClient();
}

var
	app = express();

var port = process.env.PORT || 3000;

app.use(bodyParser.json())
app.use(bodyParser.urlencoded())

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

var protect = (process.env.USER && process.env.PASS) ?
	basicAuth(process.env.USER, process.env.PASS) :
	function(_,_,next){return next()};

/*
	Set a value for a given key
	POST /set/keyname {value:20 }
*/
app.post('/set/:key', protect, function(req,res){

	var key = req.param('key'),
		value = req.param('value'),
		now = +new Date;

	if(value) client.zadd(key, -now, [now,value].join(' '))

	res.send(
		value ? 200 : 403,
		{status: value ? 'ok' : 'missing key'}
	);

})

app.post('/clear/:key', protect, function(req,res){
	client.del(req.param('key'))
	res.send({status:'cleared'})
})

app.get('/data/:key', function(req, res){

	var keys = [];

	client.zscan(req.param('key'), {count: 3})
	.on('data', function(s){
		keys.push(
			s.key.split(' ').map(function(n){
				return parseInt(n,10)
			}));
	})
	.on('end', function(){
		res.send(keys)
	})

})

// all keys on the system
app.get('/keys', function(req, res){

	var keys = [];

	client.scan({count:100})
	.on('data', function(s){
		keys.push(s);
	})
	.on('end', function(){
		res.send(keys)
	});

})

app.listen(port);

module.exports = app;
<commit_msg>switch to lists<commit_after>var express = require('express'),
	bodyParser = require('body-parser'),
	basicAuth = require('basic-auth-connect'),
	redis = require("redis"),
	url = require('url'),
	client;

require("redis-scanstreams")(redis);

if (process.env.REDISTOGO_URL) {
	var redisURL = url.parse(process.env.REDISTOGO_URL);

	client = redis.createClient(redisURL.port, redisURL.hostname, {no_ready_check: true});
	client.auth(redisURL.auth.split(":")[1]);
} else {
    client = redis.createClient();
}

var LIST_LENGTH = 500;
var
	app = express();

var port = process.env.PORT || 3000;

app.use(bodyParser.json())
app.use(bodyParser.urlencoded())

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

var protect = (process.env.USER && process.env.PASS) ?
	basicAuth(process.env.USER, process.env.PASS) :
	function(_,_,next){return next()};

/*
	Set a value for a given key
	POST /set/keyname {value:20 }
*/
app.post('/set/:key', protect, function(req,res){

	var key = req.param('key'),
		value = req.param('value'),
		now = +new Date;

	var listkey = 'stat-' + key;
	if(value) client.lpush(listkey, [now,value].join(' '), redis.print)

	res.send(
		value ? 200 : 403,
		{status: value ? 'ok' : 'missing key'}
	);

	client.ltrim(listkey, 0, LIST_LENGTH)

})

app.post('/clear/:key', protect, function(req,res){
	var listkey = 'stat-' + req.param('key');
	res.send({status:'cleared'})
})

app.get('/data/:key', function(req, res){

	var listkey = 'stat-' + req.param('key');
	client.lrange(listkey,0, LIST_LENGTH, function(err, resp){
		var keys = resp.map(function(item){
			return item.split(' ').map(function(n){
				return parseInt(n,10)
			});
		});
		res.send(keys)
	})

})

// all keys on the system
app.get('/keys', function(req, res){

	var keys = [];

	client.scan({pattern:'stat-*'})
	.on('data', function(s){
		keys.push(s.substr(5));
	})
	.on('end', function(){
		res.send(keys)
	});

})

app.listen(port);

module.exports = app;
<|endoftext|>