<commit_before>// Server-side code
/* jshint node: true, curly: true, eqeqeq: true, forin: true, immed: true, indent: 4, latedef: true, newcap: true, nonew: true, quotmark: double, undef: true, unused: true, strict: true, trailing: true */

"use strict";

// Config
var httpPort = 3000;
var redisPort = 6379;
var line_history = [];
var usernames = {};
var xyzzy = null;
var define = null;
var topics = ["bird", "mammal", "fish", "machine" ];
var room_names = ["freeforall"];

// Depends
var express = require("express");
var io = require("socket.io");
var redis = require("redis");
var request = require("request");
var random = require("random-js")();

// Initialize
var app = express();
app.use(express.static("./"));
var server = null;
var guesswhat = null;
var redisClient = null;
var db = false;

// Functions
function defineFromAPI(word) {
    var onelook = "http://www.onelook.com/?xml=1&w=";
    var url = onelook + word;

    request(url, function (error, response, body) {
        if (!error && response.statusCode === 200) {
            var xml = Array.prototype.join.call(body, "");
            var lines = xml.split("\n");
            var max = 10;

            if (lines.length < 10) {
                max = lines.length;
            }

            var count = 0;
            var stop = false;
            var found = false;

            while (!stop) {
                if (lines[count] === "<OLQuickDef>") {
                    found = true;
                }
                else if (lines[count] === "</OLQuickDef>") {
                    stop = true;
                }
                else if (count >= max) {
                    stop = true;
                }
                else if (found) {
                    define = lines[count].split("&")[0];
                }

                ++count;
            }

            console.log("==> definition:", define);
        }
    });
}

function wordsFromAPI(salt) {
    var colors = [ "red", "green", "blue", "yellow", "black", "pink", "white" ];
    var seed = random.integer(0, colors.length-1);
    var adjective = colors[seed];
    var limit = 50;

    if (salt) {
        console.log("salting with", salt);
        topics.pop();
        topics.push(salt);
    }

    var categories = topics.join(",");
    //console.log(categories);

    var datamuse = "http://api.datamuse.com/words?";
    var url = datamuse + "rel_jja=" + adjective + "&topics=" + categories + "&max=" + limit;

    request(url, function (error, response, body) {
        if (!error && response.statusCode === 200) {
            var json = JSON.parse(body);
            //console.log(json);

            var pick = random.integer(0, json.length-1);
            xyzzy = json[pick].word;
            console.log("==> magicword:", xyzzy);
            defineFromAPI(xyzzy);
        }
    });
}

function connectDB() {
    var flag = false;
    redisClient = redis.createClient(redisPort);

    redisClient.on("error", function(err) {
        console.error("Redis server refused connection on port", redisPort);
        console.log(err);
        db = false;
    });

    redisClient.on("end", function() {
        console.log("Connection to Redis Server closed");
        db = false;
    });

    redisClient.on("connect", function() {
        console.log("Connected to Redis Server on port", redisPort);
        db = true;
    });
}

function startServer() {
    var process = io.listen(app.listen(httpPort).on("error", function(err) {
        if (!err) {
            console.log("Starting express server on httpPort", httpPort);
        }
        else if (err.errno === "EADDRINUSE") {
            console.log("Port", httpPort, "busy. Unable to start express server");
            console.log("To debug: $ lsof -i :" + httpPort);
        }
        else {
            console.log(err);
        }
    }));

    return process;

}

function reveal(socket) {
    // echo new word
    socket.emit("displayword", xyzzy, define);
}

function userLogin(socket) {
    // when the client emits "adduser", this listens and executes
    socket.on("adduser", function(mode, username, groupname) {
        console.log(mode, username, groupname);
        // detect game mode
        if (mode === 1) {
            // we store the username in the socket session for this client
            socket.username = username;
            //we store the room information in the socket session
            socket.room = "freeforall";
            socket.join(socket.room);
            console.log("Free-for-all mode");
             // echo to client they've connected
            socket.emit("updatechat", "SERVER", "you have connected as '" + username + "'");
        }

        else if (mode === 2) {
            if(room_names.indexOf(groupname) === -1){
                redisClient.sadd("teamnames", groupname);
            }
            //error handling needed....
            console.log(groupname);
            // we store the username in the socket session for this client
            socket.username = username;
            //we store the room information in the socket session
            socket.room = groupname;
            socket.join(groupname);
            console.log("Teams mode");
             // echo to client they've connected
            socket.emit("updatechat", "SERVER", "you have connected as '" + username + "'");
        }

        else {
            console.log("Invalid mode", mode);
        }

        // store username in Redis database
        if (db) {
            redisClient.exists(username, function(err, object) {
                if (object !== 1) {
                    // initialize scores to 0
                    redisClient.hmset(username, {
                        "wins": 0,
                        "groupname": groupname,
                        "socketid": socket.id
                    });
                    redisClient.sadd("users", username);
                }
            });

            redisClient.smembers("users", function(err, items) {
                if (err) {
                    console.log("Error in getting elements of user list");
                }
                items.forEach(function(item) {
                   usernames[item] = item;
                });
                // update the list of users in chat, client-side
                guesswhat.to(socket.room).emit("updateusers", usernames);
            });
        }

            // echo globally (all clients) that a person has connected
            guesswhat.to(socket.room).emit("updatechat", "SERVER", username + " has connected");
            recordDraw(socket.room);

        if (server.engine.clientsCount === 1) {
            reveal(socket);
        }
    });
}

function userLogout(socket) {
    // when the user disconnects.. perform this
    socket.on("disconnect", function() {
        console.log("User:", socket.username, "Disconnected");
        // remove the username from global usernames list
        delete usernames[socket.username];

        // remove username from Redis database
        if (db) {
            redisClient.srem("users", 1,  socket.username, function(err) {
                if (err) {
                    console.log("User Removed form list");
                }
            });

            redisClient.hdel(socket.username, "wins");
            redisClient.hdel(socket.username, "groupname");
            redisClient.hdel(socket.username, "socketid");
        }

        // update list of users in chat, client-side
        guesswhat.to(socket.room).emit("updateusers", usernames);
        // echo globally that this client has left
        socket.broadcast.emit("updatechat", "SERVER", socket.username + " has disconnected");

        if (server.engine.clientsCount === 1) {
            reveal(socket);
        }
    });
}

function recordDraw(roomname) {
    var room = roomname;
    console.log("for sending: "+ room)
    line_history.length = 0;
    redisClient.lrange(room, 0, -1, function(err, items){
        if (err) {
                    console.log("Error in getting elements of user list");
                }
                if(items !== null){
                    items.forEach(function(item) {
                   line_history.push(JSON.parse(item));
                });
                    console.log("ready");
                    for (var i in line_history) {
                        if (line_history[i] !== null) {
                            console.log("emitting.."+room);
                            //socket.emit("draw_line", line_history[i]);
                            console.log(line_history[i]);
                            guesswhat.to(room).emit("draw_line", line_history[i]);

                            }
                         else {
                            console.log("Drawing null");
                        }
                    }
                }
    });

}

function transmitDraw(socket) {

    socket.on("draw_line", function(data) {
         if(db){
            redisClient.exists(socket.room, function(err, object) {
                if (object !== 1) {
                   redisClient.rpush(socket.room, JSON.stringify(data));
                }
                else{
                     redisClient.rpush(socket.room, JSON.stringify(data));
                }
            });
         }
        guesswhat.to(socket.room).emit("draw_line", data);
    });
}

function winner(socket) {
    var winuser = socket.username;
    console.log("Winner", winuser);

    // echo to client they've won
    socket.emit("updateword", "You win!");
    socket.emit("updateword", "The word was '" + xyzzy + "'");
    // echo globally (all clients) that a person has won
    guesswhat.to(socket.room).emit("updateword", "The word was '" + xyzzy + "'");
    guesswhat.to(socket.room).emit("updateword", "Player '" + winuser + "' was the winner");

    // get new word
    wordsFromAPI(xyzzy);
    reveal(socket);
}

function parseChat(socket, data) {
    var line = Array.prototype.join.call(data, "");
    var words = line.split(" ");

    for (var i = 0; i < words.length; ++i) {
        var guess = words[i].replace(/[^a-zA-Z]/g, "");
        console.log("raw:" + words[i], "alpha:" + guess, "this:" + xyzzy);

        if (guess === xyzzy) {
            winner(socket);
        }
        // fuzzy matching
        else if (guess.replace(/s$/, "") === xyzzy) {
            console.log("trimmed 's'");
            winner(socket);
        }
        else if (guess.replace(/y$/, "ies") === xyzzy) {
            console.log("expanded 's'");
            winner(socket);
        }
        else if (guess === xyzzy + "s") {
            console.log("appended 's'");
            winner(socket);
        }
    }
}

function transmitChat(socket) {
    // when the client emits "sendchat", this listens and executes
    socket.on("sendchat", function(data) {
        // we tell the client to execute "updatechat" with 2 parameters
        //server.sockets.emit("updatechat", socket.username, data);
        guesswhat.to(socket.room).emit("updatechat", socket.username, data);
        // check for magic word
        parseChat(socket, data);
    });
}

function clearCanvas(socket) {
    socket.on("clearcanvas", function() {
        line_history.length = 0;
        console.log("cleared....");
        guesswhat.to(socket.room).emit("clearcanvas");
    });
}

// Run server
server = startServer();
connectDB();
guesswhat = server.of("/guesswhat");
wordsFromAPI();

// Main
guesswhat.on("connection", function(socket) {
    console.log("Connected: %s", socket.id);
    userLogin(socket);
    //recordDraw(socket);

    transmitDraw(socket);
    transmitChat(socket);
    userLogout(socket);
    clearCanvas(socket);
});
<commit_msg>Better DB handling and solved bug #11<commit_after>// Server-side code
/* jshint node: true, curly: true, eqeqeq: true, forin: true, immed: true, indent: 4, latedef: true, newcap: true, nonew: true, quotmark: double, undef: true, unused: true, strict: true, trailing: true */

"use strict";

// Config
var httpPort = 3000;
var redisPort = 6379;
var line_history = [];
var usernames = [];
var xyzzy = null;
var define = null;
var topics = ["bird", "mammal", "fish", "machine" ];
var room_names = ["freeforall"];

// Depends
var express = require("express");
var io = require("socket.io");
var redis = require("redis");
var request = require("request");
var random = require("random-js")();

// Initialize
var app = express();
app.use(express.static("./"));
var server = null;
var guesswhat = null;
var redisClient = null;
var db = false;

// Functions
function defineFromAPI(word) {
    var onelook = "http://www.onelook.com/?xml=1&w=";
    var url = onelook + word;

    request(url, function (error, response, body) {
        if (!error && response.statusCode === 200) {
            var xml = Array.prototype.join.call(body, "");
            var lines = xml.split("\n");
            var max = 10;

            if (lines.length < 10) {
                max = lines.length;
            }

            var count = 0;
            var stop = false;
            var found = false;

            while (!stop) {
                if (lines[count] === "<OLQuickDef>") {
                    found = true;
                }
                else if (lines[count] === "</OLQuickDef>") {
                    stop = true;
                }
                else if (count >= max) {
                    stop = true;
                }
                else if (found) {
                    define = lines[count].split("&")[0];
                }

                ++count;
            }

            console.log("==> definition:", define);
        }
    });
}

function wordsFromAPI(salt) {
    var colors = [ "red", "green", "blue", "yellow", "black", "pink", "white" ];
    var seed = random.integer(0, colors.length-1);
    var adjective = colors[seed];
    var limit = 50;

    if (salt) {
        console.log("salting with", salt);
        topics.pop();
        topics.push(salt);
    }

    var categories = topics.join(",");
    //console.log(categories);

    var datamuse = "http://api.datamuse.com/words?";
    var url = datamuse + "rel_jja=" + adjective + "&topics=" + categories + "&max=" + limit;

    request(url, function (error, response, body) {
        if (!error && response.statusCode === 200) {
            var json = JSON.parse(body);
            //console.log(json);

            var pick = random.integer(0, json.length-1);
            xyzzy = json[pick].word;
            console.log("==> magicword:", xyzzy);
            defineFromAPI(xyzzy);
        }
    });
}

function connectDB() {
    redisClient = redis.createClient(redisPort);

    redisClient.on("error", function(err) {
        console.error("Redis server refused connection on port", redisPort);
        console.log(err);
        db = false;
    });

    redisClient.on("end", function() {
        console.log("Connection to Redis Server closed");
        db = false;
    });

    redisClient.on("connect", function() {
        console.log("Connected to Redis Server on port", redisPort);
        db = true;
    });
}

function startServer() {
    var process = io.listen(app.listen(httpPort).on("error", function(err) {
        if (!err) {
            console.log("Starting express server on httpPort", httpPort);
        }
        else if (err.errno === "EADDRINUSE") {
            console.log("Port", httpPort, "busy. Unable to start express server");
            console.log("To debug: $ lsof -i :" + httpPort);
        }
        else {
            console.log(err);
        }
    }));

    return process;

}

function reveal(socket) {
    // echo new word
    socket.emit("displayword", xyzzy, define);
}

function userLogin(socket) {
    usernames.length = 0;
    // when the client emits "adduser", this listens and executes
    socket.on("adduser", function(mode, username, groupname) {
        console.log(mode, username, groupname);
        if(username === null){
            username = "unknown";
        }
        // detect game mode
        if (mode === 1) {
            // we store the username in the socket session for this client
            socket.username = username;
            groupname = "freeforall";
            //we store the room information in the socket session
            socket.room = "freeforall";
            socket.join(socket.room);
            console.log("Free-for-all mode");
             // echo to client they've connected
            socket.emit("updatechat", "SERVER", "you have connected as '" + username + "'");
        }

        else if (mode === 2) {
            //error handling needed....
            console.log(groupname);
            // we store the username in the socket session for this client
            socket.username = username;
            //we store the room information in the socket session
            socket.room = groupname;
            socket.join(groupname);
            console.log("Teams mode");
             // echo to client they've connected
            socket.emit("updatechat", "SERVER", "you have connected as '" + username + "'");
        }

        else {
            console.log("Invalid mode", mode);
        }

        // store username in Redis database
        if (db) {
            redisClient.exists(username, function(err, object) {
                if (object !== 1) {
                    // initialize scores to 0
                    redisClient.hmset(username, {
                        "wins": 0,
                        "groupname": groupname,
                        "socketid": socket.id
                    });
                    var grp = "G"+ groupname;

                    redisClient.sadd(grp, username, function(){

                        redisClient.smembers(grp, function(err, items) {
                            if (err) {
                                console.log("Error in getting elements of user list");
                            }
                            items.forEach(function(item) {
                                console.log(items);
                               usernames.push(item);
                            });
                            // update the list of users in chat, client-side
                            guesswhat.to(socket.room).emit("updateusers", usernames);
                            // echo globally (all clients) that a person has connected
                            socket.broadcast.to(socket.room).emit("updatechat", "SERVER", username + " has connected");
                        });
                    });
                }
            });
        }
            recordDraw(socket.room);

        if (server.engine.clientsCount === 1) {
            reveal(socket);
        }
    });
}

function userLogout(socket) {
    // when the user disconnects.. perform this
    socket.on("disconnect", function() {
        console.log("User:", socket.username, "Disconnected");
        // remove the username from global usernames list
        delete usernames[socket.username];

        // remove username from Redis database
        if (db) {
            var cgrp = "G" + socket.room;
            console.log(cgrp);
            redisClient.srem(cgrp, 1,  socket.username, function(err) {
                if (err) {
                    console.log("User Removed form list");
                }
            });
            //remove the hash set for user
            redisClient.hdel(socket.username, "wins");
            redisClient.hdel(socket.username, "groupname");
            redisClient.hdel(socket.username, "socketid");

            redisClient.exists(cgrp, function(err, object){

                if(object === 0){

                    redisClient.ltrim(socket.room, -1 ,0, function(err){
                        if(!err){
                            console.log(socket.room + " Room deleted !");
                        }
                    });
                }
            });
        }
        // update list of users in chat, client-side
        guesswhat.to(socket.room).emit("updateusers", usernames);
        // echo globally that this client has left
        socket.broadcast.emit("updatechat", "SERVER", socket.username + " has disconnected");

        if (server.engine.clientsCount === 1) {
            reveal(socket);
        }
    });
}

function recordDraw(roomname) {
    var room = roomname;
    line_history.length = 0;
    redisClient.lrange(room, 0, -1, function(err, items){
        if (err) {
                    console.log("Error in getting elements of user list");
                }
                if(items !== null){
                    items.forEach(function(item) {
                   line_history.push(JSON.parse(item));
                });

                    for (var i in line_history) {
                        if (line_history[i] !== null) {

                            guesswhat.to(room).emit("draw_line", line_history[i]);

                            }
                         else {
                            console.log("Drawing null");
                        }
                    }
                }
    });
}

function transmitDraw(socket) {

    socket.on("draw_line", function(data) {
         if(db){
            redisClient.exists(socket.room, function(err, object) {
                if (object !== 1) {
                   redisClient.rpush(socket.room, JSON.stringify(data));
                }
                else{
                     redisClient.rpush(socket.room, JSON.stringify(data));
                }
            });
         }
        guesswhat.to(socket.room).emit("draw_line", data);
    });
}

function winner(socket) {
    var winuser = socket.username;
    console.log("Winner", winuser);

    // echo to client they've won
    socket.emit("updateword", "You win!");
    socket.emit("updateword", "The word was '" + xyzzy + "'");
    // echo globally (all clients) that a person has won
    guesswhat.to(socket.room).emit("updateword", "The word was '" + xyzzy + "'");
    guesswhat.to(socket.room).emit("updateword", "Player '" + winuser + "' was the winner");

    // get new word
    wordsFromAPI(xyzzy);
    reveal(socket);
}

function parseChat(socket, data) {
    var line = Array.prototype.join.call(data, "");
    var words = line.split(" ");

    for (var i = 0; i < words.length; ++i) {
        var guess = words[i].replace(/[^a-zA-Z]/g, "");
        console.log("raw:" + words[i], "alpha:" + guess, "this:" + xyzzy);

        if (guess === xyzzy) {
            winner(socket);
        }
        // fuzzy matching
        else if (guess.replace(/s$/, "") === xyzzy) {
            console.log("trimmed 's'");
            winner(socket);
        }
        else if (guess.replace(/y$/, "ies") === xyzzy) {
            console.log("expanded 's'");
            winner(socket);
        }
        else if (guess === xyzzy + "s") {
            console.log("appended 's'");
            winner(socket);
        }
    }
}

function transmitChat(socket) {
    // when the client emits "sendchat", this listens and executes
    socket.on("sendchat", function(data) {
        // we tell the client to execute "updatechat" with 2 parameters
        //server.sockets.emit("updatechat", socket.username, data);
        guesswhat.to(socket.room).emit("updatechat", socket.username, data);
        // check for magic word
        parseChat(socket, data);
    });
}

function clearCanvas(socket) {
    socket.on("clearcanvas", function() {
        line_history.length = 0;

        guesswhat.to(socket.room).emit("clearcanvas");
    });
}

// Run server
server = startServer();
connectDB();
guesswhat = server.of("/guesswhat");
wordsFromAPI();

// Main
guesswhat.on("connection", function(socket) {
    console.log("Connected: %s", socket.id);
    userLogin(socket);
    //recordDraw(socket);
    transmitDraw(socket);
    transmitChat(socket);
    userLogout(socket);
    clearCanvas(socket);
});
<|endoftext|>


<commit_before>export class CallExpression {
  constructor(observerLocator, targetProperty, sourceExpression, valueConverterLookupFunction){
    this.observerLocator = observerLocator;
    this.targetProperty = targetProperty;
    this.sourceExpression = sourceExpression;
    this.valueConverterLookupFunction = valueConverterLookupFunction;
  }

  createBinding(target){
    return new Call(
      this.observerLocator,
      this.sourceExpression,
      target,
      this.targetProperty,
      this.valueConverterLookupFunction
      );
  }
}

class Call {
  constructor(observerLocator, sourceExpression, target, targetProperty, valueConverterLookupFunction){
    this.sourceExpression = sourceExpression
    this.target = target;
    this.targetProperty = observerLocator.getObserver(target, targetProperty);
    this.valueConverterLookupFunction = valueConverterLookupFunction;
  }

  bind(source){
    if(this.source === source){
      return;
    }

    if(this.source){
      this.unbind();
    }

    this.source = source;
    this.targetProperty.setValue($event => {
      var result, temp = source.$event;
      source.$event = $event;
      result = this.sourceExpression.evaluate(source, this.valueConverterLookupFunction);
      source.$event = temp;
      return result;
    });
  }

  unbind(){
    this.targetProperty.setValue(null);
  }
}
<commit_msg>fix(call-expression): incorrect unbind code<commit_after>export class CallExpression {
  constructor(observerLocator, targetProperty, sourceExpression, valueConverterLookupFunction){
    this.observerLocator = observerLocator;
    this.targetProperty = targetProperty;
    this.sourceExpression = sourceExpression;
    this.valueConverterLookupFunction = valueConverterLookupFunction;
  }

  createBinding(target){
    return new Call(
      this.observerLocator,
      this.sourceExpression,
      target,
      this.targetProperty,
      this.valueConverterLookupFunction
      );
  }
}

class Call {
  constructor(observerLocator, sourceExpression, target, targetProperty, valueConverterLookupFunction){
    this.sourceExpression = sourceExpression
    this.target = target;
    this.targetProperty = observerLocator.getObserver(target, targetProperty);
    this.valueConverterLookupFunction = valueConverterLookupFunction;
  }

  bind(source){
    if(this.source){
      if(this.source === source){
        return;
      }

      this.unbind();
    }

    this.source = source;
    this.targetProperty.setValue($event => {
      var result, temp = source.$event;
      source.$event = $event;
      result = this.sourceExpression.evaluate(source, this.valueConverterLookupFunction);
      source.$event = temp;
      return result;
    });
  }

  unbind(){
    if(this.source){
      this.targetProperty.setValue(null);
      this.source = null;
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');

var CrawlerThread = require('./crawler/CrawlerThread');
var RessourceCrawler = require('./crawler/RessourceCrawler');
var urlStore = require('./url/urlStore');
var urlToPath = require('./url/urlToPath');

var PhantomCrawl = function(config) {
	urlToPath.setBase(config.base || 'extract');

	urlStore.setFilters(config.urlFilters);
	config.urls.forEach(function(url) {
		urlStore.add({
			url: url,
			primary: true,
			level: 0
		});
	});
	if (urlStore.isEmpty()) throw new Error('no urls to crawl');

	if (config.maxDepth) require('./url/filters/level').setMaxLevel(config.maxDepth);

	var userAgent = config.userAgent || 'Mozilla/5.0 (PhantomCrawl/' + require('../package.json').version + '; bot) AppleWebKit/534.34(KHTML, like Gecko) Chrome/13.0.764.0';
	this.threads = [];
	var nbThreads = config.nbThreads || 1;
	while (nbThreads--) {
		var thread = new CrawlerThread({
			nbCrawlers: config.crawlerPerThread,
			userAgent: userAgent
		});
		thread.on('idle', this.checkFinish.bind(this));
		this.threads.push(thread);
	}
	var rc = new RessourceCrawler({
		userAgent: userAgent
	});
	rc.on('idle', this.checkFinish.bind(this));
	this.threads.push(rc);
};

PhantomCrawl.prototype.checkFinish = function() {
	for (var i = 0; i < this.threads.length; i++) {
		if (!this.threads[i].isIdle()) return;
	}
	if (!urlStore.isEmpty()) return;

	for (i = 0; i < this.threads.length; i++) {
		this.threads[i].exit();
	}
};

module.exports = PhantomCrawl;
<commit_msg>WIP #9: restart crashed threads<commit_after>'use strict';

var fs = require('fs');

var CrawlerThread = require('./crawler/CrawlerThread');
var RessourceCrawler = require('./crawler/RessourceCrawler');
var urlStore = require('./url/urlStore');
var urlToPath = require('./url/urlToPath');

var PhantomCrawl = function(config) {
	this.config = config;
	urlToPath.setBase(config.base || 'extract');

	urlStore.setFilters(config.urlFilters);
	config.urls.forEach(function(url) {
		urlStore.add({
			url: url,
			primary: true,
			level: 0
		});
	});
	if (urlStore.isEmpty()) throw new Error('no urls to crawl');

	if (config.maxDepth) require('./url/filters/level').setMaxLevel(config.maxDepth);

	config.userAgent = config.userAgent || 'Mozilla/5.0 (PhantomCrawl/' + require('../package.json').version + '; bot) AppleWebKit/534.34(KHTML, like Gecko) Chrome/13.0.764.0';
	this.threads = [];
	var nbThreads = config.nbThreads || 1;
	while (nbThreads--) {
		this.startThread();
	}
	var rc = new RessourceCrawler({
		userAgent: config.userAgent
	});
	rc.on('idle', this.checkFinish.bind(this));
	this.threads.push(rc);
};

PhantomCrawl.prototype.startThread = function() {
	var thread = new CrawlerThread({
		nbCrawlers: this.config.crawlerPerThread,
		userAgent: this.config.userAgent
	});
	thread.on('idle', this.checkFinish.bind(this));
	thread.on('crash', this.threadCrash.bind(this, thread));
	this.threads.push(thread);

};

PhantomCrawl.prototype.threadCrash = function(thread) {
	this.threads = this.threads.filter(function(t) {
		return t !== thread;
	});
	this.startThread();
};

PhantomCrawl.prototype.checkFinish = function() {
	for (var i = 0; i < this.threads.length; i++) {
		if (!this.threads[i].isIdle()) return;
	}
	if (!urlStore.isEmpty()) return;

	console.log('Crawl done. Exiting');
	for (i = 0; i < this.threads.length; i++) {
		this.threads[i].exit();
	}
};

module.exports = PhantomCrawl;
<|endoftext|>


<commit_before>/*
 *  Effect.js
 *  2014/07/10
 *  @auther minimo
 *  This Program is MIT license.
 */
tds.Effect = [];

(function() {

//汎用パーティクル
tm.define("tds.Effect.Particle", {
    superClass: "tm.display.Shape",
    layer: LAYER_EFFECT_UPPER,

    alpha: 1.0,
    alphaDecayRate: 0.85,
    size: 0,

    image: null,
    isEffect: true,
    isUpper: true,

    init: function(size, initialAlpha, alphaDecayRate, color) {
        size = size || 32;
        color = color || 0;
        this.superInit(size, size);

        if (initialAlpha === undefined) initialAlpha = 1;
        if (alphaDecayRate === undefined) alphaDecayRate = 0.9;

        this.size = size;
        this.alpha = initialAlpha;
        this.alphaDecayRate = alphaDecayRate;
        this.blendMode = "lighter";

        var c = this.canvas;
        c.setFillStyle(
            tm.graphics.RadialGradient(size/2, size/2, 0, size/2, size/2, size/2)
                .addColorStopList([
                    {offset:0.0, color: "hsla({0}, 60%, 50%, 1.0)".format(color)},
                    {offset:0.5, color: "hsla({0}, 60%, 50%, 0.5)".format(color)},
                    {offset:1.0, color: "hsla({0}, 60%, 50%, 0.0)".format(color)},
                ]).toStyle()
            ).fillRect(0, 0, size, size);

        this.on("enterframe", function() {
            this.alpha *= this.alphaDecayRate;
            if (this.alpha < 0.01) {
                this.remove();
                return;
            } else if (1.0 < this.alpha) {
                this.alpha = 1.0;
            }
        }.bind(this));
    },
});

//オーラ用パーティクル
tm.define("tds.Effect.Aura", {
    superClass: "tm.display.Shape",
    layer: LAYER_EFFECT_UPPER,

    init: function(target, size, alphaDecayRate) {
        size = size || 100;
        this.superInit();
        if (alphaDecayRate === undefined) alphaDecayRate = 0.9;

        this.width = this.height = this.size = size;
        this.alpha = 0.02;
        this.alphaDecayRate = alphaDecayRate;
        this.blendMode = "lighter";
        this.tweener.clear().to({alpha:1},200).to({alpha:0},2000);

        this.target = target;
        this.vanish = false;

        this.setScale(size*0.01);

        var c = this.canvas;
        c.setFillStyle(
            tm.graphics.RadialGradient(25, 25, 0, 25, 25, 25)
                .addColorStopList([
                    {offset:0.0, color: "hsla({0}, 60%, 50%, 0.4)".format(200)},
                    {offset:0.5, color: "hsla({0}, 60%, 50%, 0.2)".format(240)},
                    {offset:1.0, color: "hsla({0}, 60%, 50%, 0.0)".format(240)},
                ]).toStyle()
            )
            .fillRect(0, 0, 50, 50);
    },

    update: function() {
        if (this.alpha < 0.01) {
            this.remove();
            return;
        } else if (1.0 < this.alpha) {
            this.alpha = 1.0;
        }
        if (this.target.mouseON && !this.vanish) {
             this.x += this.vx;
             this.y += this.vy;
        } else {
             this.vanish = true;
             this.x -= this.vx*3;
             this.y -= this.vy*3;
        }
        var x = this.target.x;
        var y = this.target.y;
        if (this.x-2 < x && x < this.x+2 && this.y-2 < y && y < this.y+2) {
            this.remove();
            return;
        }
        this.scaleX *= 0.98;
        this.scaleY *= 0.98;
    },
});

//爆発用パーティクル
tm.define("tds.Effect.BurnParticle", {
    superClass: "tm.display.Shape",
    layer: LAYER_EFFECT_UPPER,

    alpha: 1.0,
    alphaDecayRate: 0.85,
    size: 0,

    image: null,
    isEffect: true,
    isUpper: true,

    init: function(size, initialAlpha, alphaDecayRate, color) {
        size = size || 32;
        color = color || 0;
        this.superInit(size, size);

        if (initialAlpha === undefined) initialAlpha = 1;
        if (alphaDecayRate === undefined) alphaDecayRate = 0.9;

        this.size = size;
        this.alpha = initialAlpha;
        this.alphaDecayRate = alphaDecayRate;
        this.blendMode = "lighter";

        var c = this.canvas;
        c.setFillStyle(
            tm.graphics.RadialGradient(size/2, size/2, 0, size/2, size/2, size/2)
                .addColorStopList([
                    {offset:0.0, color: "hsla({0}, 50%, 30%, 1.0)".format(color)},
                    {offset:0.5, color: "hsla({0}, 50%, 30%, 0.5)".format(color)},
                    {offset:1.0, color: "hsla({0}, 60%, 50%, 0.0)".format(color)},
                ]).toStyle()
            )
            .fillRect(0, 0, size, size);

        this.on("enterframe", function() {
            this.alpha *= this.alphaDecayRate;
            if (this.alpha < 0.01) {
                this.remove();
                return;
            } else if (1.0 < this.alpha) {
                this.alpha = 1.0;
            }
        }.bind(this));
    },
});

//敵弾消滅パーティクル
tm.define("tds.Effect.BulletVanish", {
    superClass: "tm.display.Shape",
    layer: LAYER_EFFECT_UPPER,

    alpha: 1.0,
    alphaDecayRate: 0.9,
    size: 0,

    image: null,
    isEffect: true,
    isUpper: true,

    deltaX: 0.0,    //水平方向速度
    deltaY: 0.0,    //垂直方向速度
    deltaA: 1.0,    //速度減衰率

    init: function(bullet) {
        var size = bullet.size || 32;
        var color = bullet.param.color || 0;
        this.superInit(size, size);

        this.size = size;
        this.blendMode = "lighter";
        this.deltaX = bullet.runner.deltaX;
        this.deltaY = bullet.runner.deltaY;
        this.deltaA = 0.5;
        this.setPosition(bullet.x, bullet.y);

        var c = this.canvas;
        c.setFillStyle(
            tm.graphics.RadialGradient(size/2, size/2, 0, size/2, size/2, size/2)
                .addColorStopList([
                    {offset:0.0, color: "hsla({0}, 60%, 50%, 0.0)".format(color)},
                    {offset:0.9, color: "hsla({0}, 60%, 50%, 1.0)".format(color)},
                    {offset:1.0, color: "hsla({0}, 60%, 50%, 0.0)".format(color)},
                ]).toStyle()
            ).fillRect(0, 0, size, size);

        this.on("enterframe", function() {
            this.x += this.deltaX;
            this.y += this.deltaY;
            this.deltaX *= this.deltaA;
            this.deltaY *= this.deltaA;
        }.bind(this));

        this.tweener.clear()
            .to({scaleX: 5, scaleY: 5, alpha: 0.0}, 800, "easeOutQuad")
            .call(function() {
                this.remove();
            }.bind(this));
    },
});

//衝撃波
tm.define("tds.Effect.ShockWave", {
    superClass: "tm.display.Shape",
    layer: LAYER_EFFECT_UPPER,

    init: function(size, alphaDecayRate) {
        size = size || 64;
        this.superInit(size, size);

        if (alphaDecayRate === undefined) alphaDecayRate = 0.9;

        this.width = this.height = this.size = size;
        this.alphaDecayRate = alphaDecayRate;
        this.blendMode = "lighter";

        var c = this.canvas;
        c.setFillStyle(
            tm.graphics.RadialGradient(size/2, size/2, 0, size/2, size/2, size/2)
                .addColorStopList([
                    {offset:0.0, color: "hsla(0, 100%, 100%, 0.0)"},
                    {offset:0.8, color: "hsla(0, 100%, 100%, 1.0)"},
                    {offset:1.0, color: "hsla(0, 100%, 100%, 0.0)"},
                ]).toStyle()
            ).fillRect(0, 0, size, size);
    },

    update: function() {
        if (this.alpha < 0.01) {
            this.remove();
            return;
        } else if (1.0 < this.alpha) {
            this.alpha = 1.0;
        }
    },
});

})();<commit_msg>update bullet vanish<commit_after>/*
 *  Effect.js
 *  2014/07/10
 *  @auther minimo
 *  This Program is MIT license.
 */
tds.Effect = [];

(function() {

//汎用パーティクル
tm.define("tds.Effect.Particle", {
    superClass: "tm.display.Shape",
    layer: LAYER_EFFECT_UPPER,

    alpha: 1.0,
    alphaDecayRate: 0.85,
    size: 0,

    image: null,
    isEffect: true,
    isUpper: true,

    init: function(size, initialAlpha, alphaDecayRate, color) {
        size = size || 32;
        color = color || 0;
        this.superInit(size, size);

        if (initialAlpha === undefined) initialAlpha = 1;
        if (alphaDecayRate === undefined) alphaDecayRate = 0.9;

        this.size = size;
        this.alpha = initialAlpha;
        this.alphaDecayRate = alphaDecayRate;
        this.blendMode = "lighter";

        var c = this.canvas;
        c.setFillStyle(
            tm.graphics.RadialGradient(size/2, size/2, 0, size/2, size/2, size/2)
                .addColorStopList([
                    {offset:0.0, color: "hsla({0}, 60%, 50%, 1.0)".format(color)},
                    {offset:0.5, color: "hsla({0}, 60%, 50%, 0.5)".format(color)},
                    {offset:1.0, color: "hsla({0}, 60%, 50%, 0.0)".format(color)},
                ]).toStyle()
            ).fillRect(0, 0, size, size);

        this.on("enterframe", function() {
            this.alpha *= this.alphaDecayRate;
            if (this.alpha < 0.01) {
                this.remove();
                return;
            } else if (1.0 < this.alpha) {
                this.alpha = 1.0;
            }
        }.bind(this));
    },
});

//オーラ用パーティクル
tm.define("tds.Effect.Aura", {
    superClass: "tm.display.Shape",
    layer: LAYER_EFFECT_UPPER,

    init: function(target, size, alphaDecayRate) {
        size = size || 100;
        this.superInit();
        if (alphaDecayRate === undefined) alphaDecayRate = 0.9;

        this.width = this.height = this.size = size;
        this.alpha = 0.02;
        this.alphaDecayRate = alphaDecayRate;
        this.blendMode = "lighter";
        this.tweener.clear().to({alpha:1},200).to({alpha:0},2000);

        this.target = target;
        this.vanish = false;

        this.setScale(size*0.01);

        var c = this.canvas;
        c.setFillStyle(
            tm.graphics.RadialGradient(25, 25, 0, 25, 25, 25)
                .addColorStopList([
                    {offset:0.0, color: "hsla({0}, 60%, 50%, 0.4)".format(200)},
                    {offset:0.5, color: "hsla({0}, 60%, 50%, 0.2)".format(240)},
                    {offset:1.0, color: "hsla({0}, 60%, 50%, 0.0)".format(240)},
                ]).toStyle()
            )
            .fillRect(0, 0, 50, 50);
    },

    update: function() {
        if (this.alpha < 0.01) {
            this.remove();
            return;
        } else if (1.0 < this.alpha) {
            this.alpha = 1.0;
        }
        if (this.target.mouseON && !this.vanish) {
             this.x += this.vx;
             this.y += this.vy;
        } else {
             this.vanish = true;
             this.x -= this.vx*3;
             this.y -= this.vy*3;
        }
        var x = this.target.x;
        var y = this.target.y;
        if (this.x-2 < x && x < this.x+2 && this.y-2 < y && y < this.y+2) {
            this.remove();
            return;
        }
        this.scaleX *= 0.98;
        this.scaleY *= 0.98;
    },
});

//爆発用パーティクル
tm.define("tds.Effect.BurnParticle", {
    superClass: "tm.display.Shape",
    layer: LAYER_EFFECT_UPPER,

    alpha: 1.0,
    alphaDecayRate: 0.85,
    size: 0,

    image: null,
    isEffect: true,
    isUpper: true,

    init: function(size, initialAlpha, alphaDecayRate, color) {
        size = size || 32;
        color = color || 0;
        this.superInit(size, size);

        if (initialAlpha === undefined) initialAlpha = 1;
        if (alphaDecayRate === undefined) alphaDecayRate = 0.9;

        this.size = size;
        this.alpha = initialAlpha;
        this.alphaDecayRate = alphaDecayRate;
        this.blendMode = "lighter";

        var c = this.canvas;
        c.setFillStyle(
            tm.graphics.RadialGradient(size/2, size/2, 0, size/2, size/2, size/2)
                .addColorStopList([
                    {offset:0.0, color: "hsla({0}, 50%, 30%, 1.0)".format(color)},
                    {offset:0.5, color: "hsla({0}, 50%, 30%, 0.5)".format(color)},
                    {offset:1.0, color: "hsla({0}, 60%, 50%, 0.0)".format(color)},
                ]).toStyle()
            )
            .fillRect(0, 0, size, size);

        this.on("enterframe", function() {
            this.alpha *= this.alphaDecayRate;
            if (this.alpha < 0.01) {
                this.remove();
                return;
            } else if (1.0 < this.alpha) {
                this.alpha = 1.0;
            }
        }.bind(this));
    },
});

//敵弾消滅パーティクル
tm.define("tds.Effect.BulletVanish", {
    superClass: "tm.display.Shape",
    layer: LAYER_EFFECT_UPPER,

    alpha: 1.0,
    alphaDecayRate: 0.9,
    size: 0,

    image: null,
    isEffect: true,
    isUpper: true,

    deltaX: 0.0,    //水平方向速度
    deltaY: 0.0,    //垂直方向速度
    deltaA: 1.0,    //速度減衰率

    init: function(bullet) {
        var size = bullet.size || 32;
        var color = bullet.param.color || 0;
        this.superInit(size, size);

        this.size = size;
        this.blendMode = "lighter";
        this.deltaX = bullet.runner.deltaX;
        this.deltaY = bullet.runner.deltaY;
        this.deltaA = 0.5;
        this.setPosition(bullet.x, bullet.y);

        var c = this.canvas;
        c.setFillStyle(
            tm.graphics.RadialGradient(size/2, size/2, 0, size/2, size/2, size/2)
                .addColorStopList([
                    {offset:0.0, color: "hsla({0}, 60%, 50%, 0.0)".format(color)},
                    {offset:0.9, color: "hsla({0}, 60%, 50%, 1.0)".format(color)},
                    {offset:1.0, color: "hsla({0}, 60%, 50%, 0.0)".format(color)},
                ]).toStyle()
            ).fillRect(0, 0, size, size);

        this.on("enterframe", function() {
            this.x += this.deltaX;
            this.y += this.deltaY;
            this.deltaX *= this.deltaA;
            this.deltaY *= this.deltaA;
        }.bind(this));

        this.tweener.clear()
            .to({scaleX: 3, scaleY: 3, alpha: 0.0}, 800, "easeOutQuad")
            .call(function() {
                this.remove();
            }.bind(this));
    },
});

//衝撃波
tm.define("tds.Effect.ShockWave", {
    superClass: "tm.display.Shape",
    layer: LAYER_EFFECT_UPPER,

    init: function(size, alphaDecayRate) {
        size = size || 64;
        this.superInit(size, size);

        if (alphaDecayRate === undefined) alphaDecayRate = 0.9;

        this.width = this.height = this.size = size;
        this.alphaDecayRate = alphaDecayRate;
        this.blendMode = "lighter";

        var c = this.canvas;
        c.setFillStyle(
            tm.graphics.RadialGradient(size/2, size/2, 0, size/2, size/2, size/2)
                .addColorStopList([
                    {offset:0.0, color: "hsla(0, 100%, 100%, 0.0)"},
                    {offset:0.8, color: "hsla(0, 100%, 100%, 1.0)"},
                    {offset:1.0, color: "hsla(0, 100%, 100%, 0.0)"},
                ]).toStyle()
            ).fillRect(0, 0, size, size);
    },

    update: function() {
        if (this.alpha < 0.01) {
            this.remove();
            return;
        } else if (1.0 < this.alpha) {
            this.alpha = 1.0;
        }
    },
});

})();<|endoftext|>


<commit_before>var DateRange = (function() {
  return function(clock) {
    var startDate, endDate,
      month = (function() {
        return {
          updateRange: function(currentDate) {
            setRange(firstDayOfMonth(currentDate), lastDayOfMonth(currentDate));
          }
        };

        function firstDayOfMonth(date) {
          return moment(date).date(1);
        }

        function lastDayOfMonth(date) {
          var daysInMonth = moment(date).daysInMonth();
          return firstDayOfMonth(date).add(daysInMonth - 1, "days");
        }
      })(),

      week = (function() {
        return {
          updateRange: function(currentDate) {
            setRange(monday(currentDate), sunday(currentDate));
          }
        };

        function monday(date) {
          return moment(date).day("Monday");
        }

        function sunday(date) {
          return monday(date).add(6, "days");
        }
      })(),

      year = (function() {
        return {
          updateRange: function(currentDate) {
            setRange(firstDayOfYear(currentDate), lastDayOfYear(currentDate));
          }
        };

        function firstDayOfYear(date) {
          return moment(date).dayOfYear(1);
        }

        function lastDayOfYear(date) {
          return firstDayOfYear(date).add(1, "years").add(-1, "days");
        }
      })(),

      period = week;

    updateRange();

    return {
      startDate: function() {
        return startDate;
      },
      endDate: function() {
        return endDate;
      },
      useMonth: function() {
        period = month;
        updateRange();
      },
      useYear: function() {
        period = year;
        updateRange();
      }
    };

    function updateRange() {
      period.updateRange(clock.currentDate());
    }

    function setRange(newStartDate, newEndDate) {
      startDate = newStartDate.toDate();
      endDate = newEndDate.toDate();
    }
  };
})();<commit_msg>Gave named to period types constructor functions<commit_after>var DateRange = (function() {
  return function(clock) {
    var startDate, endDate,
      month = Month(),
      week = Week(),
      year = Year(),
      period = week;

    updateRange();

    return {
      startDate: function() {
        return startDate;
      },
      endDate: function() {
        return endDate;
      },
      useMonth: function() {
        period = month;
        updateRange();
      },
      useYear: function() {
        period = year;
        updateRange();
      }
    };

    function updateRange() {
      period.updateRange(clock.currentDate());
    }

    function setRange(newStartDate, newEndDate) {
      startDate = newStartDate.toDate();
      endDate = newEndDate.toDate();
    }

    function Month() {
      return {
        updateRange: function(currentDate) {
          setRange(firstDayOfMonth(currentDate), lastDayOfMonth(currentDate));
        }
      };

      function firstDayOfMonth(date) {
        return moment(date).date(1);
      }

      function lastDayOfMonth(date) {
        var daysInMonth = moment(date).daysInMonth();
        return firstDayOfMonth(date).add(daysInMonth - 1, "days");
      }
    }

    function Week() {
      return {
        updateRange: function(currentDate) {
          setRange(monday(currentDate), sunday(currentDate));
        }
      };

      function monday(date) {
        return moment(date).day("Monday");
      }

      function sunday(date) {
        return monday(date).add(6, "days");
      }
    }

    function Year() {
      return {
        updateRange: function(currentDate) {
          setRange(firstDayOfYear(currentDate), lastDayOfYear(currentDate));
        }
      };

      function firstDayOfYear(date) {
        return moment(date).dayOfYear(1);
      }

      function lastDayOfYear(date) {
        return firstDayOfYear(date).add(1, "years").add(-1, "days");
      }
    }
  };
})();<|endoftext|>


<commit_before>import { scaleIdentity } from 'd3-scale';
import { select } from 'd3-selection';
import { dataJoin } from 'd3fc-data-join';
import { shapeBar } from 'd3fc-shape';
import { range } from './scale';
import constant from './constant';

export default () => {

    let xScale = scaleIdentity();
    let yScale = scaleIdentity();
    let align = 'center';
    let orient = 'horizontal';
    let fromValue = () => {};
    let toValue = () => {};
    let decorate = () => {};

    const join = dataJoin('g', 'annotation-band');

    const pathGenerator = shapeBar()
      .horizontalAlign('right')
      .verticalAlign('top')
      // a null value returned by a value accessor will be replaced by the scale's range
      .x((...args) => orient === 'horizontal' ? range(xScale)[0] : xScale(fromValue(...args)))
      .y((...args) => orient === 'horizontal' ? yScale(fromValue(...args)) : range(yScale)[0])
      .width((...args) => {
          const values = orient === 'horizontal' ? range(xScale) : [xScale(fromValue(...args)), xScale(toValue(...args))];
          return values[1] - values[0];
      })
      .height((...args) => {
          const values = orient === 'horizontal' ? [yScale(fromValue(...args)), yScale(toValue(...args))] : range(yScale);
          return values[1] - values[0];
      });

    var instance = (selection) => {

        if (orient !== 'horizontal' && orient !== 'vertical') {
            throw new Error('Invalid orientation');
        }

        selection.each((data, index, nodes) => {

            var g = join(select(nodes[index]), data);

            g.enter()
                .append('path')
                .classed('band', true);

            g.select('path')
                // the path generator is being used to render a single path, hence
                // an explicit index is provided
                .attr('d', (d, i) => pathGenerator([d], i));

            decorate(g, data, index);
        });
    };

    instance.xScale = (...args) => {
        if (!args.length) {
            return xScale;
        }
        xScale = args[0];
        return instance;
    };
    instance.yScale = (...args) => {
        if (!args.length) {
            return yScale;
        }
        yScale = args[0];
        return instance;
    };
    instance.decorate = (...args) => {
        if (!args.length) {
            return decorate;
        }
        decorate = args[0];
        return instance;
    };
    instance.fromValue = (...args) => {
        if (!args.length) {
            return fromValue;
        }
        fromValue = constant(args[0]);
        return instance;
    };
    instance.toValue = (...args) => {
        if (!args.length) {
            return toValue;
        }
        toValue = constant(args[0]);
        return instance;
    };

    return instance;
};
<commit_msg>feat: add default accessors for from/toValue (.from/.to)<commit_after>import { scaleIdentity } from 'd3-scale';
import { select } from 'd3-selection';
import { dataJoin } from 'd3fc-data-join';
import { shapeBar } from 'd3fc-shape';
import { range } from './scale';
import constant from './constant';

export default () => {

    let xScale = scaleIdentity();
    let yScale = scaleIdentity();
    let align = 'center';
    let orient = 'horizontal';
    let fromValue = d => d.from;
    let toValue = d => d.to;
    let decorate = () => {};

    const join = dataJoin('g', 'annotation-band');

    const pathGenerator = shapeBar()
      .horizontalAlign('right')
      .verticalAlign('top')
      // a null value returned by a value accessor will be replaced by the scale's range
      .x((...args) => orient === 'horizontal' ? range(xScale)[0] : xScale(fromValue(...args)))
      .y((...args) => orient === 'horizontal' ? yScale(fromValue(...args)) : range(yScale)[0])
      .width((...args) => {
          const values = orient === 'horizontal' ? range(xScale) : [xScale(fromValue(...args)), xScale(toValue(...args))];
          return values[1] - values[0];
      })
      .height((...args) => {
          const values = orient === 'horizontal' ? [yScale(fromValue(...args)), yScale(toValue(...args))] : range(yScale);
          return values[1] - values[0];
      });

    var instance = (selection) => {

        if (orient !== 'horizontal' && orient !== 'vertical') {
            throw new Error('Invalid orientation');
        }

        selection.each((data, index, nodes) => {

            var g = join(select(nodes[index]), data);

            g.enter()
                .append('path')
                .classed('band', true);

            g.select('path')
                // the path generator is being used to render a single path, hence
                // an explicit index is provided
                .attr('d', (d, i) => pathGenerator([d], i));

            decorate(g, data, index);
        });
    };

    instance.xScale = (...args) => {
        if (!args.length) {
            return xScale;
        }
        xScale = args[0];
        return instance;
    };
    instance.yScale = (...args) => {
        if (!args.length) {
            return yScale;
        }
        yScale = args[0];
        return instance;
    };
    instance.decorate = (...args) => {
        if (!args.length) {
            return decorate;
        }
        decorate = args[0];
        return instance;
    };
    instance.fromValue = (...args) => {
        if (!args.length) {
            return fromValue;
        }
        fromValue = constant(args[0]);
        return instance;
    };
    instance.toValue = (...args) => {
        if (!args.length) {
            return toValue;
        }
        toValue = constant(args[0]);
        return instance;
    };

    return instance;
};
<|endoftext|>


<commit_before>function NotesApplication(author) {
	// Take in a parameter author  of the note and saves this as an instance variable
	this.author = author;
	// Create a notes list,then store all the notes as an instance property.
	this.notes = [];

	"use strict"

	//  function create(note_content) takes the note content as the parameter and adds it to the notes list of  object.
	this.create = function(noteContent) {
		this.notes.push(noteContent);
	};

	/* listNotes() function lists out each of the notes in the notes list in the following format.
	The note_id parameter below represents the respective index of each of the items in the list,
	the NOTE_CONTENT represent the note content and the author represents the note author.*/
	this.listNotes = function() {
		for (var i = 0; i < this.notes.length; i++) {
			console.log(
				"Note ID: " + i + "\n" +
				this.notes[i] + "\n" +
				"By Author: " + this.author + "\n\n"
			);

		}
	};

	/* get(noteId) function takes a noteId which refers to the index of the note in the notes
	list and returns the content of that note as a string.*/
	this.get = function(noteId) {
		return this.notes[noteId];
	};

	/* search(search_text)function take a search string, search_text and returns all the
	notes with that text within it in the following format*/
	this.search = function(searchText) {
		result = [];
		var j = 0;

		this.notes.forEach(function(el, i) {
			if (el.indexOf(searchText) > -1)
				result.push({
					id: i,
					note: el
				});
		});
		var heading = "\nShowing result for search text " + searchText + "\n";
		var content = "";
		var that = this;
		result.map(function(el) {
			content += "\nNote ID: " + el.id + "\n" +
				el.note + "\n" +
				"By Author: " + that.author + "\n";
		});
		return heading + content;

	};
	/* edit(edit_text)function take two input(note_id and new_content)*/
	this.edit = function(noteId, newContent) {
		this.notes[noteId] = newContent;
	};
	/* delete(delete_text)function take a input(note_id )*/
	this.delete = function(noteId) {
		this.notes.splice(noteId, 1);

	};
}<commit_msg>Final adjustment<commit_after>
"use strict"

function NotesApplication(author) {
	// Take in a parameter author  of the note and saves this as an instance variable
	this.author = author;
	// Create a notes list,then store all the notes as an instance property.
	this.notes = [];

	//  function create(note_content) takes the note content as the parameter and adds it to the notes list of  object.
	this.create = function(noteContent) {
		this.notes.push(noteContent);
	};

	/* listNotes() function lists out each of the notes in the notes list in the following format.
	The note_id parameter below represents the respective index of each of the items in the list,
	the NOTE_CONTENT represent the note content and the author represents the note author.*/
	this.listNotes = function() {
		for (var i = 0; i < this.notes.length; i++) {
			console.log(
				"Note ID: " + i + "\n" +
				this.notes[i] + "\n" +
				"By Author: " + this.author + "\n\n"
			);

		}
	};

	/* get(noteId) function takes a noteId which refers to the index of the note in the notes
	list and returns the content of that note as a string.*/
	this.get = function(noteId) {
		return this.notes[noteId];
	};

	/* search(search_text)function take a search string, search_text and returns all the
	notes with that text within it in the following format*/
	this.search = function(searchText) {
		result = [];
		var j = 0;

		this.notes.forEach(function(el, i) {
			if (el.indexOf(searchText) > -1)
				result.push({
					id: i,
					note: el
				});
		});
		var heading = "\nShowing result for search text " + searchText + "\n";
		var content = "";
		var that = this;
		result.map(function(el) {
			content += "\nNote ID: " + el.id + "\n" +
				el.note + "\n" +
				"By Author: " + that.author + "\n";
		});
		return heading + content;

	};
	/* edit(edit_text)function take two input(note_id and new_content)*/
	this.edit = function(noteId, newContent) {
		this.notes[noteId] = newContent;
	};
	/* delete(delete_text)function take a input(note_id )*/
	this.delete = function(noteId) {
		this.notes.splice(noteId, 1);

	};
}<|endoftext|>


<commit_before>(function(global) {
  'use strict';

  var Promise = global.Promise || require('es6-promise').Promise;

  var chai, promisePool;
  if (typeof module !== 'undefined') {
    chai = require('chai');
    chai.use(require('chai-as-promised'));
    promisePool = require('../');
  } else {
    chai = global.chai;
    promisePool = global.promisePool;
  }

  var expect = chai.expect;

  var supportsGenerators = (function() {
    try {
      eval('(function*(){})()');
      return true;
    } catch (e) {
      return false;
    }
  })();

  describe('promisePool', function() {
    it('should take a non-function', function() {
      var poolPromise = promisePool('test', 1);
      return expect(poolPromise).to.be.fulfilled;
    });

    it('should take a single promise', function() {
      var poolPromise = promisePool(Promise.resolve(), 1);
      return expect(poolPromise).to.be.fulfilled;
    });

    if (supportsGenerators) {
      var gen = eval('(function* g() {' +
        'yield new Promise(function(resolve, reject) {' +
        'resolve();' +
        '});' +
        '})');
      it('should take a generator', function() {
        var poolPromise = promisePool(gen, 1);
        return expect(poolPromise).to.be.fulfilled;
      });
    }

    it('should resolve an empty pool', function() {
      var poolPromise = promisePool(function() {
        return null;
      }, 1);
      return expect(poolPromise).to.be.fulfilled;
    });

    it('should forward a rejection', function() {
      var poolPromise = promisePool(function() {
        return new Promise(function(resolve, reject) {
          reject(new Error('test'));
        });
      }, 1);
      return expect(poolPromise).to.be.rejectedWith(Error, 'test');
    });

    it('should handle delayed promises', function() {
      var called = false;
      var poolPromise = promisePool(function() {
        if (called) {
          return null;
        }
        called = true;
        return new Promise(function(resolve, reject) {
          setTimeout(resolve, 10);
        });
      }, 1);
      return expect(poolPromise).to.be.fulfilled;
    });

    it('should have a pool property', function() {
      var poolPromise = promisePool(function() {
        return null;
      }, 1);
      return expect(poolPromise.pool).to.be.an('object');
    });

    it('should report the pool size', function() {
      var cnt = 0;
      var poolPromise = promisePool(function() {
        if (cnt++ < 5) {
          return new Promise(function(resolve, reject) {
            setTimeout(resolve, 100);
          });
        } else {
          return null;
        }
      }, 3);
      var sizePromise = new Promise(function(resolve, reject) {
        setTimeout(function() {
          resolve(poolPromise.pool.size());
        }, 0);
      });
      return expect(sizePromise).to.eventually.equal(3);
    });

    it('should report the concurrency', function() {
      var poolPromise = promisePool(function() {
        return null;
      }, 5);
      return expect(poolPromise.pool.concurrency()).to.equal(5);
    });

    it('should update the concurrency', function() {
      var poolPromise = promisePool(function() {
        return null;
      }, 1);
      poolPromise.pool.concurrency(5);
      return expect(poolPromise.pool.concurrency()).to.equal(5);
    });

    it('should throttle', function() {
      var maxPoolSize = 0;
      var cnt = 0;
      var poolPromise = promisePool(function() {
        if (cnt++ < 10) {
          return new Promise(function(resolve, reject) {
            setTimeout(function() {
              maxPoolSize = Math.max(maxPoolSize, poolPromise.pool.size());
              resolve();
            }, 0);
          });
        } else {
          return null;
        }
      }, 3);
      var sizePromise = poolPromise.then(function() {
        return maxPoolSize;
      });
      return expect(sizePromise).to.eventually.be.at.most(3);
    });

    it('should not call the producer after terminating it', function() {
      var maxCnt = 0;
      var cnt = 0;
      var poolPromise = promisePool(function() {
        if (cnt++ === 3) {
          return null;
        } else {
          maxCnt = Math.max(maxCnt, cnt);
          return new Promise(function(resolve, reject) {
            setTimeout(resolve, 10);
          });
        }
      }, 1);
      var cntPromise = poolPromise.then(function() {
        return maxCnt;
      });
      return expect(cntPromise).to.eventually.equal(3);
    });

    it('should call onresolve', function() {
      var arg = null;
      var res = 'test';
      var prom = new Promise(function(resolve, reject) {
        setTimeout(function() {
          resolve(res);
        }, 0);
      });
      var called = false;
      var poolPromise = promisePool(function() {
        if (called) {
          return null;
        }
        called = true;
        return prom;
      }, 1, {
        onresolve: function() {
          arg = Array.prototype.slice.call(arguments);
        }
      });
      var argPromise = poolPromise.then(function() {
        return arg;
      });
      return expect(argPromise).to.eventually.deep.equal([poolPromise, prom, res]);
    });

    it('should call onreject', function() {
      var arg = null;
      var err = new Error('test');
      var prom = new Promise(function(resolve, reject) {
        setTimeout(function() {
          reject(err);
        }, 0);
      });
      var called = false;
      var poolPromise = promisePool(function() {
        if (called) {
          return null;
        }
        called = true;
        return prom;
      }, 1, {
        onreject: function() {
          arg = Array.prototype.slice.call(arguments);
        }
      });
      var argPromise = poolPromise.then(function() {
        throw new Error('Should not happen');
      }, function() {
        return arg;
      });
      return expect(argPromise).to.eventually.deep.equal([poolPromise, prom, err]);
    });
  });
})(this);
<commit_msg>Tests for unwanted resolve/reject<commit_after>(function(global) {
  'use strict';

  var Promise = global.Promise || require('es6-promise').Promise;

  var chai, promisePool;
  if (typeof module !== 'undefined') {
    chai = require('chai');
    chai.use(require('chai-as-promised'));
    promisePool = require('../');
  } else {
    chai = global.chai;
    promisePool = global.promisePool;
  }

  var expect = chai.expect;

  var supportsGenerators = (function() {
    try {
      eval('(function*(){})()');
      return true;
    } catch (e) {
      return false;
    }
  })();

  describe('promisePool', function() {
    it('should take a non-function', function() {
      var poolPromise = promisePool('test', 1);
      return expect(poolPromise).to.be.fulfilled;
    });

    it('should take a single promise', function() {
      var poolPromise = promisePool(Promise.resolve(), 1);
      return expect(poolPromise).to.be.fulfilled;
    });

    if (supportsGenerators) {
      var gen = eval('(function* g() {' +
        'yield new Promise(function(resolve, reject) {' +
        'resolve();' +
        '});' +
        '})');
      it('should take a generator', function() {
        var poolPromise = promisePool(gen, 1);
        return expect(poolPromise).to.be.fulfilled;
      });
    }

    it('should resolve an empty pool', function() {
      var poolPromise = promisePool(function() {
        return null;
      }, 1);
      return expect(poolPromise).to.be.fulfilled;
    });

    it('should forward a rejection', function() {
      var poolPromise = promisePool(function() {
        return new Promise(function(resolve, reject) {
          reject(new Error('test'));
        });
      }, 1);
      return expect(poolPromise).to.be.rejectedWith(Error, 'test');
    });

    it('should not resolve after a rejection', function() {
      var reached = false;
      var cnt = 0;
      var poolPromise = promisePool(function() {
        switch (cnt++) {
          case 0:
            return new Promise(function(resolve, reject) {
              reject(new Error('test'));
            });
          case 1:
            return new Promise(function(resolve, reject) {
              setTimeout(function() {
                resolve();
              }, 10);
            });
          default:
            return null;
        }
      }, 3, {
        onresolve: function() {
          reached = true;
        }
      });
      var valuePromise = poolPromise['catch'](function() {
        return reached;
      });
      return expect(valuePromise).to.eventually.equal(false);
    });

    it('should not reject again after a rejection', function() {
      var rejections = 0;
      var cnt = 0;
      var poolPromise = promisePool(function() {
        switch (cnt++) {
          case 0:
            return new Promise(function(resolve, reject) {
              reject(new Error('test'));
            });
          case 1:
            return new Promise(function(resolve, reject) {
              setTimeout(function() {
                reject();
              }, 10);
            });
          default:
            return null;
        }
      }, 3, {
        onreject: function() {
          rejections++;
        }
      });
      var valuePromise = poolPromise['catch'](function() {
        return rejections;
      });
      return expect(valuePromise).to.eventually.equal(1);
    });

    it('should handle delayed promises', function() {
      var called = false;
      var poolPromise = promisePool(function() {
        if (called) {
          return null;
        }
        called = true;
        return new Promise(function(resolve, reject) {
          setTimeout(resolve, 10);
        });
      }, 1);
      return expect(poolPromise).to.be.fulfilled;
    });

    it('should have a pool property', function() {
      var poolPromise = promisePool(function() {
        return null;
      }, 1);
      return expect(poolPromise.pool).to.be.an('object');
    });

    it('should report the pool size', function() {
      var cnt = 0;
      var poolPromise = promisePool(function() {
        if (cnt++ < 5) {
          return new Promise(function(resolve, reject) {
            setTimeout(resolve, 100);
          });
        } else {
          return null;
        }
      }, 3);
      var sizePromise = new Promise(function(resolve, reject) {
        setTimeout(function() {
          resolve(poolPromise.pool.size());
        }, 0);
      });
      return expect(sizePromise).to.eventually.equal(3);
    });

    it('should report the concurrency', function() {
      var poolPromise = promisePool(function() {
        return null;
      }, 5);
      return expect(poolPromise.pool.concurrency()).to.equal(5);
    });

    it('should update the concurrency', function() {
      var poolPromise = promisePool(function() {
        return null;
      }, 1);
      poolPromise.pool.concurrency(5);
      return expect(poolPromise.pool.concurrency()).to.equal(5);
    });

    it('should throttle', function() {
      var maxPoolSize = 0;
      var cnt = 0;
      var poolPromise = promisePool(function() {
        if (cnt++ < 10) {
          return new Promise(function(resolve, reject) {
            setTimeout(function() {
              maxPoolSize = Math.max(maxPoolSize, poolPromise.pool.size());
              resolve();
            }, 0);
          });
        } else {
          return null;
        }
      }, 3);
      var sizePromise = poolPromise.then(function() {
        return maxPoolSize;
      });
      return expect(sizePromise).to.eventually.be.at.most(3);
    });

    it('should not call the producer after terminating it', function() {
      var maxCnt = 0;
      var cnt = 0;
      var poolPromise = promisePool(function() {
        if (cnt++ === 3) {
          return null;
        } else {
          maxCnt = Math.max(maxCnt, cnt);
          return new Promise(function(resolve, reject) {
            setTimeout(resolve, 10);
          });
        }
      }, 1);
      var cntPromise = poolPromise.then(function() {
        return maxCnt;
      });
      return expect(cntPromise).to.eventually.equal(3);
    });

    it('should call onresolve', function() {
      var arg = null;
      var res = 'test';
      var prom = new Promise(function(resolve, reject) {
        setTimeout(function() {
          resolve(res);
        }, 0);
      });
      var called = false;
      var poolPromise = promisePool(function() {
        if (called) {
          return null;
        }
        called = true;
        return prom;
      }, 1, {
        onresolve: function() {
          arg = Array.prototype.slice.call(arguments);
        }
      });
      var argPromise = poolPromise.then(function() {
        return arg;
      });
      return expect(argPromise).to.eventually.deep.equal([poolPromise, prom, res]);
    });

    it('should call onreject', function() {
      var arg = null;
      var err = new Error('test');
      var prom = new Promise(function(resolve, reject) {
        setTimeout(function() {
          reject(err);
        }, 0);
      });
      var called = false;
      var poolPromise = promisePool(function() {
        if (called) {
          return null;
        }
        called = true;
        return prom;
      }, 1, {
        onreject: function() {
          arg = Array.prototype.slice.call(arguments);
        }
      });
      var argPromise = poolPromise.then(function() {
        throw new Error('Should not happen');
      }, function() {
        return arg;
      });
      return expect(argPromise).to.eventually.deep.equal([poolPromise, prom, err]);
    });
  });
})(this);
<|endoftext|>


<commit_before>import CustomError from 'customerror';
import Collection from './Collection';
import Database from './Database';

class QueryBuilder {

  /**
   * Constructs a new QueryBuilder instance for the designated collection.
   * @param {String} collectionName the name of the collection.
   * @constructor
   */
  constructor(collectionName: String) {
    this.collectionName = collectionName;
  }

  /**
   * Builds and returns a new "find" query, based on the supplied AST.
   * @param {Array} ast an abstract syntax tree, as provided by the QueryParser.
   * @return {Object}
   * @throws {NotImplementedException} if method has not been implemented or does not apply to the current database engine.
   */
  buildFind(ast: Array) {
    throw new CustomError('Method not implemented', 'NotImplementedException');
  }

  /**
   * Builds and returns a new "find one" query, based on the supplied AST.
   * @param {Array} ast an abstract syntax tree, as provided by the QueryParser.
   * @return {Object}
   * @throws {NotImplementedException} if method has not been implemented or does not apply to the current database engine.
   */
  buildFindOne(ast: Array) {
    throw new CustomError('Method not implemented', 'NotImplementedException');
  }

  /**
   * Builds and returns a new "count" query, based on the supplied AST.
   * @param {Array} ast an abstract syntax tree, as provided by the QueryParser.
   * @return {Object}
   * @throws {NotImplementedException} if method has not been implemented or does not apply to the current database engine.
   */
  buildCount(ast: Array) {
    throw new CustomError('Method not implemented', 'NotImplementedException');
  }

  /**
   * Builds and returns a new "remove" query, based on the supplied AST.
   * @param {Array} ast an abstract syntax tree, as provided by the QueryParser.
   * @return {Object}
   * @throws {NotImplementedException} if method has not been implemented or does not apply to the current database engine.
   */
  buildRemove(ast: Array) {
    throw new CustomError('Method not implemented', 'NotImplementedException');
  }

  /**
   * Builds and returns a new "insert" query, based on the supplied AST.
   * @param {Array} ast an abstract syntax tree, as provided by the QueryParser.
   * @return {Object}
   * @throws {NotImplementedException} if method has not been implemented or does not apply to the current database engine.
   */
  buildInsert(ast: Array) {
    throw new CustomError('Method not implemented', 'NotImplementedException');
  }

  /**
   * Builds and returns a new "update" query, based on the supplied AST.
   * @param {Array} ast an abstract syntax tree, as provided by the QueryParser.
   * @return {Object}
   * @throws {NotImplementedException} if method has not been implemented or does not apply to the current database engine.
   */
  buildUpdate(ast: Array) {
    throw new CustomError('Method not implemented', 'NotImplementedException');
  }

}

export default QueryBuilder;
<commit_msg>Bugfix: should be using "string" instead of "String"<commit_after>import CustomError from 'customerror';
import Collection from './Collection';
import Database from './Database';

class QueryBuilder {

  /**
   * Constructs a new QueryBuilder instance for the designated collection.
   * @param {string} collectionName the name of the collection.
   * @constructor
   */
  constructor(collectionName: string) {
    this.collectionName = collectionName;
  }

  /**
   * Builds and returns a new "find" query, based on the supplied AST.
   * @param {Array} ast an abstract syntax tree, as provided by the QueryParser.
   * @return {Object}
   * @throws {NotImplementedException} if method has not been implemented or does not apply to the current database engine.
   */
  buildFind(ast: Array) {
    throw new CustomError('Method not implemented', 'NotImplementedException');
  }

  /**
   * Builds and returns a new "find one" query, based on the supplied AST.
   * @param {Array} ast an abstract syntax tree, as provided by the QueryParser.
   * @return {Object}
   * @throws {NotImplementedException} if method has not been implemented or does not apply to the current database engine.
   */
  buildFindOne(ast: Array) {
    throw new CustomError('Method not implemented', 'NotImplementedException');
  }

  /**
   * Builds and returns a new "count" query, based on the supplied AST.
   * @param {Array} ast an abstract syntax tree, as provided by the QueryParser.
   * @return {Object}
   * @throws {NotImplementedException} if method has not been implemented or does not apply to the current database engine.
   */
  buildCount(ast: Array) {
    throw new CustomError('Method not implemented', 'NotImplementedException');
  }

  /**
   * Builds and returns a new "remove" query, based on the supplied AST.
   * @param {Array} ast an abstract syntax tree, as provided by the QueryParser.
   * @return {Object}
   * @throws {NotImplementedException} if method has not been implemented or does not apply to the current database engine.
   */
  buildRemove(ast: Array) {
    throw new CustomError('Method not implemented', 'NotImplementedException');
  }

  /**
   * Builds and returns a new "insert" query, based on the supplied AST.
   * @param {Array} ast an abstract syntax tree, as provided by the QueryParser.
   * @return {Object}
   * @throws {NotImplementedException} if method has not been implemented or does not apply to the current database engine.
   */
  buildInsert(ast: Array) {
    throw new CustomError('Method not implemented', 'NotImplementedException');
  }

  /**
   * Builds and returns a new "update" query, based on the supplied AST.
   * @param {Array} ast an abstract syntax tree, as provided by the QueryParser.
   * @return {Object}
   * @throws {NotImplementedException} if method has not been implemented or does not apply to the current database engine.
   */
  buildUpdate(ast: Array) {
    throw new CustomError('Method not implemented', 'NotImplementedException');
  }

}

export default QueryBuilder;
<|endoftext|>


<commit_before>// @flow weak
/* eslint-env mocha */

import React from 'react';
import { assert } from 'chai';
import { spy } from 'sinon';
import { createShallowWithContext } from 'test/utils';
import Tab, { styleSheet } from './Tab';

describe('<Tab />', () => {
  let shallow;
  let classes;
  const icon = restore;

  before(() => {
    shallow = createShallowWithContext();
    classes = shallow.context.styleManager.render(styleSheet);
  });

  it('should render with the root class', () => {
    const wrapper = shallow(
      <Tab />,
    );
    assert.strictEqual(wrapper.is('ButtonBase'), true, 'should be a ButtonBase');
    assert.strictEqual(wrapper.hasClass(classes.root), true, 'should have the root class');
  });

  describe('prop: className', () => {
    it('should render with the user and root classes', () => {
      const wrapper = shallow(<Tab className="woof" />);
      assert.strictEqual(wrapper.hasClass('woof'), true, 'should have the "woof" class');
      assert.strictEqual(wrapper.hasClass(classes.root), true, 'should have the root class');
    });
  });

  describe('prop: selected', () => {
    it('should render with the selected and root classes', () => {
      const wrapper = shallow(
        <Tab selected textColor="accent" />,
      );
      assert.strictEqual(wrapper.hasClass(classes.rootAccentSelected), true);
      assert.strictEqual(wrapper.hasClass(classes.rootAccent), true);
      assert.strictEqual(wrapper.hasClass(classes.root), true);
      assert.strictEqual(wrapper.props()['aria-selected'], true);
    });
  });

  describe('prop: onClick', () => {
    it('should be called when a click is triggered', () => {
      const handleClick = spy();
      const wrapper = shallow(
        <Tab onClick={handleClick} onChange={() => {}} />,
      );
      wrapper.simulate('click');
      assert.strictEqual(handleClick.callCount, 1, 'it should forward the onClick');
    });
  });

  describe('prop: label', () => {
    it('should render label with the label class', () => {
      const wrapper = shallow(<Tab label="foo" />);
      const label = wrapper.childAt(0);
      assert.strictEqual(label.hasClass(classes.label), true);
    });
  });

  describe('prop: icon', () => {
    it('should render icon with the icon class', () => {
      const wrapper = shallow(<Tab icon={icon} />);
      const iconWrapper = wrapper.childAt(0);
      assert.strictEqual(iconWrapper.hasClass('material-icons'), true);
    });

    it('should render a font icon if a icon string is passed', () => {
      const wrapper = shallow(<Tab icon="book" />);
      assert.strictEqual(wrapper.find('.material-icons').length, 1, 'should have the material icons class');
    });
  });

  describe('prop: textColor', () => {
    it('should support the inherit value', () => {
      const wrapper = shallow(
        <Tab selected textColor="inherit" />,
      );
      assert.strictEqual(wrapper.hasClass(classes.rootInheritSelected), true);
      assert.strictEqual(wrapper.hasClass(classes.rootInherit), true);
      assert.strictEqual(wrapper.hasClass(classes.root), true);
    });

    it('should support an arbitrary value', () => {
      const textColor = '#eee';
      const wrapper = shallow(
        <Tab selected textColor={textColor} />,
      );
      assert.strictEqual(wrapper.props().style.color, textColor);
    });
  });

  describe('prop: fullWidth', () => {
    it('should apply a specific width', () => {
      const wrapper = shallow(<Tab fullWidth />);
      assert.strictEqual(wrapper.props().style.width, '100%');
    });
  });

  describe('prop: style', () => {
    it('should be able to override everything', () => {
      const style = {
        width: '80%',
        color: 'red',
        alignText: 'center',
      };
      const wrapper = shallow(<Tab fullWidth textColor="#eee" style={style} />);
      assert.deepEqual(wrapper.props().style, style);
    });
  });
});
<commit_msg>[Tab] Tweak icon test wording<commit_after>// @flow weak
/* eslint-env mocha */

import React from 'react';
import { assert } from 'chai';
import { spy } from 'sinon';
import { createShallowWithContext } from 'test/utils';
import Tab, { styleSheet } from './Tab';

describe('<Tab />', () => {
  let shallow;
  let classes;
  const icon = restore;

  before(() => {
    shallow = createShallowWithContext();
    classes = shallow.context.styleManager.render(styleSheet);
  });

  it('should render with the root class', () => {
    const wrapper = shallow(
      <Tab />,
    );
    assert.strictEqual(wrapper.is('ButtonBase'), true, 'should be a ButtonBase');
    assert.strictEqual(wrapper.hasClass(classes.root), true, 'should have the root class');
  });

  describe('prop: className', () => {
    it('should render with the user and root classes', () => {
      const wrapper = shallow(<Tab className="woof" />);
      assert.strictEqual(wrapper.hasClass('woof'), true, 'should have the "woof" class');
      assert.strictEqual(wrapper.hasClass(classes.root), true, 'should have the root class');
    });
  });

  describe('prop: selected', () => {
    it('should render with the selected and root classes', () => {
      const wrapper = shallow(
        <Tab selected textColor="accent" />,
      );
      assert.strictEqual(wrapper.hasClass(classes.rootAccentSelected), true);
      assert.strictEqual(wrapper.hasClass(classes.rootAccent), true);
      assert.strictEqual(wrapper.hasClass(classes.root), true);
      assert.strictEqual(wrapper.props()['aria-selected'], true);
    });
  });

  describe('prop: onClick', () => {
    it('should be called when a click is triggered', () => {
      const handleClick = spy();
      const wrapper = shallow(
        <Tab onClick={handleClick} onChange={() => {}} />,
      );
      wrapper.simulate('click');
      assert.strictEqual(handleClick.callCount, 1, 'it should forward the onClick');
    });
  });

  describe('prop: label', () => {
    it('should render label with the label class', () => {
      const wrapper = shallow(<Tab label="foo" />);
      const label = wrapper.childAt(0);
      assert.strictEqual(label.hasClass(classes.label), true);
    });
  });

  describe('prop: icon', () => {
    it('should render icon element', () => {
      const wrapper = shallow(<Tab icon={icon} />);
      const iconWrapper = wrapper.childAt(0);
      assert.strictEqual(iconWrapper.hasClass('material-icons'), true);
    });

    it('should render a font icon if a icon string is passed', () => {
      const wrapper = shallow(<Tab icon="book" />);
      assert.strictEqual(wrapper.find('.material-icons').length, 1, 'should have the material icons class');
    });
  });

  describe('prop: textColor', () => {
    it('should support the inherit value', () => {
      const wrapper = shallow(
        <Tab selected textColor="inherit" />,
      );
      assert.strictEqual(wrapper.hasClass(classes.rootInheritSelected), true);
      assert.strictEqual(wrapper.hasClass(classes.rootInherit), true);
      assert.strictEqual(wrapper.hasClass(classes.root), true);
    });

    it('should support an arbitrary value', () => {
      const textColor = '#eee';
      const wrapper = shallow(
        <Tab selected textColor={textColor} />,
      );
      assert.strictEqual(wrapper.props().style.color, textColor);
    });
  });

  describe('prop: fullWidth', () => {
    it('should apply a specific width', () => {
      const wrapper = shallow(<Tab fullWidth />);
      assert.strictEqual(wrapper.props().style.width, '100%');
    });
  });

  describe('prop: style', () => {
    it('should be able to override everything', () => {
      const style = {
        width: '80%',
        color: 'red',
        alignText: 'center',
      };
      const wrapper = shallow(<Tab fullWidth textColor="#eee" style={style} />);
      assert.deepEqual(wrapper.props().style, style);
    });
  });
});
<|endoftext|>


<commit_before>const server = require('kth-node-server')
// Load .env file in development mode
const nodeEnv = process.env.NODE_ENV && process.env.NODE_ENV.toLowerCase()
if (nodeEnv === 'development' || nodeEnv === 'dev' || !nodeEnv) {
  require('dotenv').config()
}
// Now read the server config
const config = require('./init/configuration').server

/**
 * *** TEMPLATING ***
 */
const path = require('path')
server.set('views', path.join(__dirname, '/views'))
server.set('layouts', path.join(__dirname, '/views/layouts'))
server.set('partials', path.join(__dirname, '/views/partials'))
server.engine('handlebars', exphbs({
  defaultLayout: 'publicLayout',
  layoutsDir: server.settings.layouts,
  partialsDir: server.settings.partials,
}))
server.set('view engine', 'handlebars')
// Register handlebar helpers
require('./views/helpers')

/* ***********************
 * ******* LOGGING *******
 * ***********************
 */
const log = require('kth-node-log')
const packageFile = require('../package.json')

// What is this used for?
server.locals.secret = new Map()

server.start({
  useSsl: config.useSsl,
  pfx: config.ssl.pfx,
  passphrase: config.ssl.passphrase,
  key: config.ssl.key,
  ca: config.ssl.ca,
  cert: config.ssl.cert,
  port: config.port,
  logger: log
})

module.exports = server
let logConfiguration = {
  name: packageFile.name,
  app: packageFile.name,
  env: process.env.NODE_ENV,
  level: config.logging.log.level,
  console: config.logging.console,
  stdout: config.logging.stdout,
  src: config.logging.src
}
log.init(logConfiguration)
<commit_msg>Starat server prior to init (like it was before), not sure if this is such a good idea though so might revisit<commit_after>const server = require('kth-node-server')
// Load .env file in development mode
const nodeEnv = process.env.NODE_ENV && process.env.NODE_ENV.toLowerCase()
if (nodeEnv === 'development' || nodeEnv === 'dev' || !nodeEnv) {
  require('dotenv').config()
}
// Now read the server config
const config = require('./init/configuration').server

// What is this used for?
server.locals.secret = new Map()

server.start({
  useSsl: config.useSsl,
  pfx: config.ssl.pfx,
  passphrase: config.ssl.passphrase,
  key: config.ssl.key,
  ca: config.ssl.ca,
  cert: config.ssl.cert,
  port: config.port,
  logger: log
})

module.exports = server

/* **************************
 * ******* TEMPLATING *******
 * **************************
 */
const path = require('path')
server.set('views', path.join(__dirname, '/views'))
server.set('layouts', path.join(__dirname, '/views/layouts'))
server.set('partials', path.join(__dirname, '/views/partials'))
server.engine('handlebars', exphbs({
  defaultLayout: 'publicLayout',
  layoutsDir: server.settings.layouts,
  partialsDir: server.settings.partials,
}))
server.set('view engine', 'handlebars')
// Register handlebar helpers
require('./views/helpers')

/* ***********************
 * ******* LOGGING *******
 * ***********************
 */
const log = require('kth-node-log')
const packageFile = require('../package.json')

let logConfiguration = {
  name: packageFile.name,
  app: packageFile.name,
  env: process.env.NODE_ENV,
  level: config.logging.log.level,
  console: config.logging.console,
  stdout: config.logging.stdout,
  src: config.logging.src
}
log.init(logConfiguration)
<|endoftext|>


<commit_before>/**
 * Broadcaster factory.
 * This class provides access to the broadcaster as a service.
 */
define([
    'spoon/core/broadcaster/Broadcaster'
], function (Broadcaster) {

    'use strict';

    return new Broadcaster();
});<commit_msg>Fix namespace<commit_after>/**
 * Broadcaster factory.
 * This class provides access to the broadcaster as a service.
 */
define([
    'spoon/core/Broadcaster/Broadcaster'
], function (Broadcaster) {

    'use strict';

    return new Broadcaster();
});<|endoftext|>


<commit_before>(function () {
  "use strict";

  // map auto_home          0         0         0   100%    /home
  var exec = require('child_process').exec
    , os = require('os')
    , reCaptureCells = /^([^\s]+\s?[^\s]+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)%\s+(.*?)\s*$/
    , cmdMap = {
          "Darwin": "df -b"
        , "Linux": "df -B 512"
      }
    , reMap = {
          "Darwin": reCaptureCells
        , "Linux": reCaptureCells
      }
    , cmdDf = cmdMap[os.type()]
    , reDf = reMap[os.type()]
    ;

  function init() {
    // TODO test default block size
  }

  function df(cb) {
    function formatDf(err, stdout, stderr) {
      var table
        , infos = []
        ;

      function parseRow(row) {
        var cells = row.match(reDf)
          ;

        if (!cells) {
          return;
        }

        // FYI
        // It seems that RegExp Match isn't a true array
        // popping it deos weird things
        infos.push({
            filesystem: cells[1]
          , blocks: parseInt(cells[2], 10)
          , used: parseInt(cells[3], 10)
          , available: parseInt(cells[4], 10)
          , percent: parseInt(cells[5], 10)
          , mountpoint: cells[6]
        });
      }

      if (err) {
        cb(err);
        return;
      }

      if (stderr) {
        cb(new Error(stderr));
        return;
      }

      table = stdout.split(/\n/g);
      // get rid of header

      table.pop();
      table.forEach(parseRow);

      cb(null, infos);
    }

    exec('df', formatDf);
  }

  function main () {
    df(function (err, table) {
      if (err) {
        console.error(err.stack);
        return;
      }

      console.log(JSON.stringify(table, null, '  '));
    })
  }

  if (require.main === module) {
      main();
  }

  module.exports = df;
}());
<commit_msg>forgot to add #!/usr/bin/env node<commit_after>#!/usr/bin/env node
(function () {
  "use strict";

  // map auto_home          0         0         0   100%    /home
  var exec = require('child_process').exec
    , os = require('os')
    , reCaptureCells = /^([^\s]+\s?[^\s]+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)%\s+(.*?)\s*$/
    , cmdMap = {
          "Darwin": "df -b"
        , "Linux": "df -B 512"
      }
    , reMap = {
          "Darwin": reCaptureCells
        , "Linux": reCaptureCells
      }
    , cmdDf = cmdMap[os.type()]
    , reDf = reMap[os.type()]
    ;

  function init() {
    // TODO test default block size
  }

  function df(cb) {
    function formatDf(err, stdout, stderr) {
      var table
        , infos = []
        ;

      function parseRow(row) {
        var cells = row.match(reDf)
          ;

        if (!cells) {
          return;
        }

        // FYI
        // It seems that RegExp Match isn't a true array
        // popping it deos weird things
        infos.push({
            filesystem: cells[1]
          , blocks: parseInt(cells[2], 10)
          , used: parseInt(cells[3], 10)
          , available: parseInt(cells[4], 10)
          , percent: parseInt(cells[5], 10)
          , mountpoint: cells[6]
        });
      }

      if (err) {
        cb(err);
        return;
      }

      if (stderr) {
        cb(new Error(stderr));
        return;
      }

      table = stdout.split(/\n/g);
      // get rid of header

      table.pop();
      table.forEach(parseRow);

      cb(null, infos);
    }

    exec('df', formatDf);
  }

  function main () {
    df(function (err, table) {
      if (err) {
        console.error(err.stack);
        return;
      }

      console.log(JSON.stringify(table, null, '  '));
    })
  }

  if (require.main === module) {
      main();
  }

  module.exports = df;
}());
<|endoftext|>


<commit_before>(function() {

    var Engine = Game.Engine = Class({
        loop: null,
        state_machine: null,
        is_running: false,

        init: function(state_machine) {
            this.state_machine = state_machine;
        },

        tick_factory: function() {
            var a = Game.Time.update,
                b = this.state_machine.run;

            return function() { a(); b(); };
        },

        start: function(fps) {
            if(this.is_running) return;

            var fps = fps || 30;

            Game.Time.update();
            this.is_running = true;
            this.loop = setInterval(this.tick_factory(), 1000 / fps);
        },

        stop: function() {
            clearInterval(this.loop);
            this.is_running = false;
        }
    });

})();
<commit_msg>Actually switch states.<commit_after>(function() {

    var Engine = Game.Engine = Class({
        loop: null,
        state_machine: null,
        is_running: false,

        init: function(state_machine) {
            this.state_machine = state_machine;
        },

        tick_factory: function() {
            var a = Game.Time.update,
                b = this.state_machine;

            return function() { a(); b.run(); };
        },

        start: function(fps) {
            if(this.is_running) return;

            var fps = fps || 30;

            Game.Time.update();
            this.is_running = true;
            this.loop = setInterval(this.tick_factory(), 1000 / fps);
        },

        stop: function() {
            clearInterval(this.loop);
            this.is_running = false;
        }
    });

})();
<|endoftext|>