<commit_before>var contentLib = require('/lib/xp/content');
var portalLib = require('/lib/xp/portal');

/*******************************************************
 * URL functions
 *******************************************************/

exports.getFoosSiteUrl = function () {
    return portalLib.pageUrl({
        path: portalLib.getSite()._path
    });
};

/*******************************************************
 * Retrieval functions
 *******************************************************/

exports.getContentByKey = function (id) {
    return contentLib.get({
        key: id
    });
};

exports.getChildrenByParentKey = function (key) {
    return contentLib.getChildren({
        key: key,
        count: -1
    }).hits;
};

exports.getPlayers = function () {
    return contentLib.query({
        start: 0,
        count: -1,
        contentTypes: [app.name + ":player"],
        sort: "displayName ASC"
    }).hits;
};

exports.getTeams = function () {
    return contentLib.query({
        start: 0,
        count: -1,
        contentTypes: [app.name + ":team"],
        sort: "displayName ASC"
    }).hits;
};

exports.getTeamByPlayerIds = function (playerIds) {
    var teams = exports.getTeams().filter(function (team) {
        return (team.data.playerIds.indexOf(playerIds[0]) != -1) && (team.data.playerIds.indexOf(playerIds[1]) != -1);
    });
    return teams[0];
};

exports.getLatestModificationTime = function () {
    return contentLib.query({
        start: 0,
        count: 1,
        sort: "modifiedTime DESC"
    }).hits[0].modifiedTime;
}

exports.getLatestWeek = function () {
    return contentLib.query({
        start: 0,
        count: 1,
        contentTypes: [app.name + ":week"],
        sort: "data.start DESC"
    }).hits[0];
};

exports.getWeeks = function () {
    return contentLib.query({
        start: 0,
        count: -1,
        contentTypes: [app.name + ":week"]
    }).hits;
};

exports.getWeekCount = function () {
    return contentLib.query({
        start: 0,
        count: 0,
        contentTypes: [app.name + ":week"]
    }).total;
};

exports.getGames = function () {
    return contentLib.query({
        start: 0,
        count: -1,
        contentTypes: [app.name + ":game"],
        sort: "data.date DESC, displayName DESC"
    }).hits;
};

exports.getGamesByWeekPath = function (weekPath) {
    return contentLib.getChildren({
        key: weekPath,
        count: -1,
        sort: "displayName DESC"
    }).hits;
};

exports.getGamesByPlayerId = function (playerId) {
    return exports.getGames().filter(function (game) {
        var gamePlayer = false;
        game.data.playerResults.forEach(function (playerResult) {
            if (playerResult.playerId == playerId) {
                gamePlayer = true;
            }
        });
        return gamePlayer;
    });
};

exports.getGamesByTeam = function (team, won) {
    return exports.getGames().filter(function (game) {
        var nbWinnerTeamPlayers = 0;
        var nbLoserTeamPlayers = 0;
        game.data.playerResults.forEach(function (playerResult) {
            if (playerResult.playerId == team.data.playerIds[0] || playerResult.playerId == team.data.playerIds[1]) {
                if (playerResult.winner) {
                    nbWinnerTeamPlayers++;
                } else {
                    nbLoserTeamPlayers++;
                }
            }
        });

        if (won == undefined) {
            return nbWinnerTeamPlayers == 2 || nbLoserTeamPlayers == 2;
        } else {
            if (won) {
                return nbWinnerTeamPlayers == 2;
            } else {
                return nbLoserTeamPlayers == 2;
            }
        }
    });
};

exports.getTeamGames = function () {
    return exports.getGames().filter(function (game) {
        return game.data.playerResults.length == 4;
    });
};

exports.getTeamGamesBetween = function (start, end) {
    return exports.getTeamGames().filter(function (game) {
        return game.data.date.localeCompare(start) >= 0 && game.data.date.localeCompare(end) <= 0;
    });
};

/*******************************************************
 * Generation functions
 *******************************************************/

exports.generatePageUrl = function (contents) {
    var contentArray = exports.toArray(contents);
    contentArray.forEach(function (content) {
        content.gen = content.gen || {};
        content.gen.pageUrl = portalLib.pageUrl({
            path: content._path
        });
    });
}

exports.generatePictureUrl = function (content, size) {
    size = size || 60;
    if (content.data.picture) {
        content.gen = content.gen || {};
        content.gen.pictureUrl = portalLib.imageUrl({
            id: content.data.picture,
            scale: 'square(' + size + ')',
            filter: 'rounded(' + (size / 2).toFixed(0) + ');sharpen()'
        });
    }
};

exports.generatePlayerStats = function (player) {
    var games = exports.getGames();

    player.gen = player.gen || {};
    player.gen.nbGames = 0;
    player.gen.nbGamesWon = 0;
    player.gen.nbGoalsScored = 0;
    player.gen.nbGoalsScoredSolo = 0;
    player.gen.nbGoalsScoredTeam = 0;
    player.gen.nbGoalsAgainst = 0;
    player.gen.nbGamesSolo = 0;
    player.gen.nbGamesWonSolo = 0;
    player.gen.nbGamesTeam = 0;
    player.gen.nbGamesWonTeam = 0;
    player.gen.nbAllGoalsSolo = 0;
    player.gen.nbAllGoalsTeam = 0;

    games.forEach(function (game) {
        var nbAllGoalsForCurrentGame = 0;
        var currentGamePlayed = false
        var playerResults = exports.toArray(game.data.playerResults);
        playerResults.forEach(function (playerResult) {
            if (playerResult.playerId == player._id) {
                player.gen.nbGames++;
                currentGamePlayed = true;
                player.gen.nbGoalsScored += playerResult.score;
                player.gen.nbGoalsAgainst += playerResult.against || 0;

                if (playerResult.winner) {
                    player.gen.nbGamesWon++;
                }

                if (playerResults.length == 2) {
                    player.gen.nbGamesSolo++;
                    player.gen.nbGoalsScoredSolo += playerResult.score;
                    if (playerResult.winner) {
                        player.gen.nbGamesWonSolo++;
                    }
                } else if (playerResults.length == 4) {
                    player.gen.nbGamesTeam++;
                    player.gen.nbGoalsScoredTeam += playerResult.score;
                    if (playerResult.winner) {
                        player.gen.nbGamesWonTeam++;
                    }
                }
            }
            nbAllGoalsForCurrentGame += playerResult.score;
        });

        if (currentGamePlayed) {
            if (playerResults.length == 2) {
                player.gen.nbAllGoalsSolo += nbAllGoalsForCurrentGame;
            } else if (playerResults.length == 4) {
                player.gen.nbAllGoalsTeam += nbAllGoalsForCurrentGame;
            }
        }
    });

    player.gen.anySolo = player.gen.nbGamesSolo > 0;
    player.gen.anyTeam = player.gen.nbGamesTeam > 0;

    player.gen.ratioGamesWon = exports.toPercentageRatio(player.gen.nbGamesWon, player.gen.nbGames);
    player.gen.ratioGamesWonSolo = exports.toPercentageRatio(player.gen.nbGamesWonSolo, player.gen.nbGamesSolo);
    player.gen.ratioGamesWonTeam = exports.toPercentageRatio(player.gen.nbGamesWonTeam, player.gen.nbGamesTeam);
    player.gen.ratioGamesSolo = exports.toPercentageRatio(player.gen.nbGamesSolo, player.gen.nbGames);
    player.gen.ratioGoalsAgainst = exports.toPercentageRatio(player.gen.nbGoalsAgainst, player.gen.nbGoalsScored);
    player.gen.ratioGoalsScoredSolo = exports.toPercentageRatio(player.gen.nbGoalsScoredSolo, player.gen.nbAllGoalsSolo);
    player.gen.ratioGoalsScoredTeam = exports.toPercentageRatio(player.gen.nbGoalsScoredTeam, player.gen.nbAllGoalsTeam);
}

exports.generateTeamStats = function (team) {
    var nbGamesWon = exports.getGamesByTeam(team, true).length;
    var nbGamesLost = exports.getGamesByTeam(team, false).length;
    var nbGames = nbGamesWon + nbGamesLost;
    team.gen = team.gen || {};
    team.gen.nbGamesWon = nbGamesWon;
    team.gen.nbGames = nbGames;
    team.gen.ratioGamesWon = exports.toPercentageRatio(nbGamesWon, nbGames);
}

exports.generateGameBasicStats = function (game) {
    game.gen = game.gen || {};
    game.gen.score = {
        winners: 0,
        losers: 0
    };

    var playerResults = exports.toArray(game.data.playerResults);
    playerResults.forEach(function (playerResult) {
        if (playerResult.winner) {
            game.gen.score.winners += playerResult.score;
            if (playerResult.against) {
                game.gen.score.losers += playerResult.against;
            }
        } else {
            game.gen.score.losers += playerResult.score;
            if (playerResult.against) {
                game.gen.score.winners += playerResult.against;
            }
        }
    });
}

exports.generateGameStats = function (game) {
    exports.generateGameBasicStats(game);

    var playerResults = exports.toArray(game.data.playerResults);
    playerResults.forEach(function (playerResult) {
        var playerContent = contentLib.get({
            key: playerResult.playerId
        });

        playerResult.gen = {};
        playerResult.gen.name = playerContent.displayName;
        exports.generatePictureUrl(playerContent);
        exports.generatePageUrl(playerContent);
        playerResult.gen.pictureUrl = playerContent.gen.pictureUrl;
        playerResult.gen.pageUrl = playerContent.gen.pageUrl;
    });
}

exports.generateGameComments = function (game) {
    game.gen = game.gen || {};

    game.gen.comments = exports.getChildrenByParentKey(game._id);
    game.gen.comments.forEach(function (comment) {
        var player = exports.getContentByKey(comment.data.authorId);
        comment.gen = {
            authorName: player.displayName
        };
    });
}

/*******************************************************
 * Generic functions
 *******************************************************/

exports.toArray = function (object) {
    if (!object) {
        return [];
    }
    if (object.constructor === Array) {
        return object;
    }
    return [object];
}

exports.toPercentageRatio = function (numerator, denominator) {
    return Math.floor(numerator * 100 / (denominator > 0 ? denominator : 1))
}

/*******************************************************
 * Perf functions
 *******************************************************/
var chrono = {};

exports.startChrono = function (topic) {
    chrono[topic] = new Date().getTime();
}
exports.stopChrono = function (topic) {
    var time = new Date().getTime() - chrono[topic];
    log.info(topic + ": " + time + "ms");
}

exports.log = function (message, object) {
    log.info(message + ": " + JSON.stringify(object, null, 2));
}

<commit_msg>Foos lib refactoring<commit_after>var contentLib = require('/lib/xp/content');
var portalLib = require('/lib/xp/portal');

/*******************************************************
 * URL functions
 *******************************************************/

exports.getFoosSiteUrl = function () {
    return portalLib.pageUrl({
        path: portalLib.getSite()._path
    });
};

/*******************************************************
 * Retrieval functions
 *******************************************************/

exports.getContentByKey = function (id) {
    return contentLib.get({
        key: id
    });
};

exports.getChildrenByParentKey = function (key) {
    return contentLib.getChildren({
        key: key,
        count: -1
    }).hits;
};

exports.getPlayers = function () {
    return contentLib.query({
        start: 0,
        count: -1,
        contentTypes: [app.name + ":player"],
        sort: "displayName ASC"
    }).hits;
};

exports.getTeams = function () {
    return contentLib.query({
        start: 0,
        count: -1,
        contentTypes: [app.name + ":team"],
        sort: "displayName ASC"
    }).hits;
};

exports.getTeamByPlayerIds = function (playerIds) {
    var teams = exports.getTeams().filter(function (team) {
        return (team.data.playerIds.indexOf(playerIds[0]) != -1) && (team.data.playerIds.indexOf(playerIds[1]) != -1);
    });
    return teams[0];
};

exports.getLatestModificationTime = function () {
    return contentLib.query({
        start: 0,
        count: 1,
        sort: "modifiedTime DESC"
    }).hits[0].modifiedTime;
}

exports.getLatestWeek = function () {
    return contentLib.query({
        start: 0,
        count: 1,
        contentTypes: [app.name + ":week"],
        sort: "data.start DESC"
    }).hits[0];
};

exports.getWeeks = function () {
    return contentLib.query({
        start: 0,
        count: -1,
        contentTypes: [app.name + ":week"]
    }).hits;
};

exports.getWeekCount = function () {
    return contentLib.query({
        start: 0,
        count: 0,
        contentTypes: [app.name + ":week"]
    }).total;
};

exports.getGames = function () {
    return contentLib.query({
        start: 0,
        count: -1,
        contentTypes: [app.name + ":game"],
        sort: "data.date DESC, displayName DESC"
    }).hits;
};

exports.getGamesByWeekPath = function (weekPath) {
    return contentLib.getChildren({
        key: weekPath,
        count: -1,
        sort: "displayName DESC"
    }).hits;
};

exports.getGamesByPlayerId = function (playerId) {
    return contentLib.query({
        start: 0,
        count: -1,
        query: "data.playerResults.playerID = '" + playerId + "'",
        contentTypes: [app.name + ":game"],
        sort: "data.date DESC, displayName DESC"
    }).hits;
};

exports.getGamesByTeam = function (team, won) {
    return exports.getGames().filter(function (game) {
        var nbWinnerTeamPlayers = 0;
        var nbLoserTeamPlayers = 0;
        game.data.playerResults.forEach(function (playerResult) {
            if (playerResult.playerId == team.data.playerIds[0] || playerResult.playerId == team.data.playerIds[1]) {
                if (playerResult.winner) {
                    nbWinnerTeamPlayers++;
                } else {
                    nbLoserTeamPlayers++;
                }
            }
        });

        if (won == undefined) {
            return nbWinnerTeamPlayers == 2 || nbLoserTeamPlayers == 2;
        } else {
            if (won) {
                return nbWinnerTeamPlayers == 2;
            } else {
                return nbLoserTeamPlayers == 2;
            }
        }
    });
};

exports.getTeamGames = function () {
    return exports.getGames().filter(function (game) {
        return game.data.playerResults.length == 4;
    });
};

exports.getTeamGamesBetween = function (start, end) {
    return exports.getTeamGames().filter(function (game) {
        return game.data.date.localeCompare(start) >= 0 && game.data.date.localeCompare(end) <= 0;
    });
};

/*******************************************************
 * Generation functions
 *******************************************************/

exports.generatePageUrl = function (contents) {
    var contentArray = exports.toArray(contents);
    contentArray.forEach(function (content) {
        content.gen = content.gen || {};
        content.gen.pageUrl = portalLib.pageUrl({
            path: content._path
        });
    });
}

exports.generatePictureUrl = function (content, size) {
    size = size || 60;
    if (content.data.picture) {
        content.gen = content.gen || {};
        content.gen.pictureUrl = portalLib.imageUrl({
            id: content.data.picture,
            scale: 'square(' + size + ')',
            filter: 'rounded(' + (size / 2).toFixed(0) + ');sharpen()'
        });
    }
};

exports.generatePlayerStats = function (player) {
    var games = exports.getGames();

    player.gen = player.gen || {};
    player.gen.nbGames = 0;
    player.gen.nbGamesWon = 0;
    player.gen.nbGoalsScored = 0;
    player.gen.nbGoalsScoredSolo = 0;
    player.gen.nbGoalsScoredTeam = 0;
    player.gen.nbGoalsAgainst = 0;
    player.gen.nbGamesSolo = 0;
    player.gen.nbGamesWonSolo = 0;
    player.gen.nbGamesTeam = 0;
    player.gen.nbGamesWonTeam = 0;
    player.gen.nbAllGoalsSolo = 0;
    player.gen.nbAllGoalsTeam = 0;

    games.forEach(function (game) {
        var nbAllGoalsForCurrentGame = 0;
        var currentGamePlayed = false
        var playerResults = exports.toArray(game.data.playerResults);
        playerResults.forEach(function (playerResult) {
            if (playerResult.playerId == player._id) {
                player.gen.nbGames++;
                currentGamePlayed = true;
                player.gen.nbGoalsScored += playerResult.score;
                player.gen.nbGoalsAgainst += playerResult.against || 0;

                if (playerResult.winner) {
                    player.gen.nbGamesWon++;
                }

                if (playerResults.length == 2) {
                    player.gen.nbGamesSolo++;
                    player.gen.nbGoalsScoredSolo += playerResult.score;
                    if (playerResult.winner) {
                        player.gen.nbGamesWonSolo++;
                    }
                } else if (playerResults.length == 4) {
                    player.gen.nbGamesTeam++;
                    player.gen.nbGoalsScoredTeam += playerResult.score;
                    if (playerResult.winner) {
                        player.gen.nbGamesWonTeam++;
                    }
                }
            }
            nbAllGoalsForCurrentGame += playerResult.score;
        });

        if (currentGamePlayed) {
            if (playerResults.length == 2) {
                player.gen.nbAllGoalsSolo += nbAllGoalsForCurrentGame;
            } else if (playerResults.length == 4) {
                player.gen.nbAllGoalsTeam += nbAllGoalsForCurrentGame;
            }
        }
    });

    player.gen.anySolo = player.gen.nbGamesSolo > 0;
    player.gen.anyTeam = player.gen.nbGamesTeam > 0;

    player.gen.ratioGamesWon = exports.toPercentageRatio(player.gen.nbGamesWon, player.gen.nbGames);
    player.gen.ratioGamesWonSolo = exports.toPercentageRatio(player.gen.nbGamesWonSolo, player.gen.nbGamesSolo);
    player.gen.ratioGamesWonTeam = exports.toPercentageRatio(player.gen.nbGamesWonTeam, player.gen.nbGamesTeam);
    player.gen.ratioGamesSolo = exports.toPercentageRatio(player.gen.nbGamesSolo, player.gen.nbGames);
    player.gen.ratioGoalsAgainst = exports.toPercentageRatio(player.gen.nbGoalsAgainst, player.gen.nbGoalsScored);
    player.gen.ratioGoalsScoredSolo = exports.toPercentageRatio(player.gen.nbGoalsScoredSolo, player.gen.nbAllGoalsSolo);
    player.gen.ratioGoalsScoredTeam = exports.toPercentageRatio(player.gen.nbGoalsScoredTeam, player.gen.nbAllGoalsTeam);
}

exports.generateTeamStats = function (team) {
    var nbGamesWon = exports.getGamesByTeam(team, true).length;
    var nbGamesLost = exports.getGamesByTeam(team, false).length;
    var nbGames = nbGamesWon + nbGamesLost;
    team.gen = team.gen || {};
    team.gen.nbGamesWon = nbGamesWon;
    team.gen.nbGames = nbGames;
    team.gen.ratioGamesWon = exports.toPercentageRatio(nbGamesWon, nbGames);
}

exports.generateGameBasicStats = function (game) {
    game.gen = game.gen || {};
    game.gen.score = {
        winners: 0,
        losers: 0
    };

    var playerResults = exports.toArray(game.data.playerResults);
    playerResults.forEach(function (playerResult) {
        if (playerResult.winner) {
            game.gen.score.winners += playerResult.score;
            if (playerResult.against) {
                game.gen.score.losers += playerResult.against;
            }
        } else {
            game.gen.score.losers += playerResult.score;
            if (playerResult.against) {
                game.gen.score.winners += playerResult.against;
            }
        }
    });
}

exports.generateGameStats = function (game) {
    exports.generateGameBasicStats(game);

    var playerResults = exports.toArray(game.data.playerResults);
    playerResults.forEach(function (playerResult) {
        var playerContent = contentLib.get({
            key: playerResult.playerId
        });

        playerResult.gen = {};
        playerResult.gen.name = playerContent.displayName;
        exports.generatePictureUrl(playerContent);
        exports.generatePageUrl(playerContent);
        playerResult.gen.pictureUrl = playerContent.gen.pictureUrl;
        playerResult.gen.pageUrl = playerContent.gen.pageUrl;
    });
}

exports.generateGameComments = function (game) {
    game.gen = game.gen || {};

    game.gen.comments = exports.getChildrenByParentKey(game._id);
    game.gen.comments.forEach(function (comment) {
        var player = exports.getContentByKey(comment.data.authorId);
        comment.gen = {
            authorName: player.displayName
        };
    });
}

/*******************************************************
 * Generic functions
 *******************************************************/

exports.toArray = function (object) {
    if (!object) {
        return [];
    }
    if (object.constructor === Array) {
        return object;
    }
    return [object];
}

exports.toPercentageRatio = function (numerator, denominator) {
    return Math.floor(numerator * 100 / (denominator > 0 ? denominator : 1))
}

/*******************************************************
 * Perf functions
 *******************************************************/
var chrono = {};

exports.startChrono = function (topic) {
    chrono[topic] = new Date().getTime();
}
exports.stopChrono = function (topic) {
    var time = new Date().getTime() - chrono[topic];
    log.info(topic + ": " + time + "ms");
}

exports.log = function (message, object) {
    log.info(message + ": " + JSON.stringify(object, null, 2));
}

<|endoftext|>


<commit_before>var forOwn = require('./forOwn')
var makeIterator = require('../function/makeIterator_')

// creates a new object with all the properties where the
// callback returns true.

function filterValues (obj, fn, thisObj) {
  fn = makeIterator(fn, thisObj)
  var output = {}
  forOwn(obj, function (value, key, obj) {
    if (fn(value, key, obj)) output[key] = value
  })
  return output
}

module.exports = filterValues
<commit_msg>refactor: object/filter.js<commit_after>function filter (obj, fn) {
  var result = {}
  var key

  for (key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (fn(obj[key], key, obj)) result[key] = obj[key]
    }
  }
  return result
}

module.exports = filter
<|endoftext|>


<commit_before>go.app = function() {
    var vumigo = require('vumigo_v02');
    var App = vumigo.App;
    var Choice = vumigo.states.Choice;
    var ChoiceState = vumigo.states.ChoiceState;
    var EndState = vumigo.states.EndState;

    var GoNDOH = App.extend(function(self) {
        App.call(self, 'states:start');
        var $ = self.$;

        self.init = function() {
            return self.im.contacts
                .for_user()
                .then(function(user_contact) {
                   self.contact = user_contact;
                });
        };

        self.states.add('states:start', function(name) {
            return new ChoiceState(name, {
                question: $('Welcome to MomConnect. Why do you want to ' +
                            'stop receiving our messages?'),

                choices: [
                    new Choice('miscarriage', $('Miscarriage')),
                    new Choice('not_pregnant', $('Not pregnant')),
                    new Choice('not_useful', $('Messages not useful')),
                    new Choice('had_baby', $('Had my baby')),
                    new Choice('other', $('Other'))
                ],

                events: {
                    'state:enter': function() {
                        return self.im.api_request('optout.optout', {
                            address_type: "msisdn",
                            address_value: self.im.user_addr
                        });
                    }
                },

                next: function(choice) {
                    self.contact.extra.opt_out_reason = choice.value;

                    return self.im.contacts.save(self.contact)
                    .then(function() {
                        return 'states:end';
                    });
                }

            });
        });

        self.states.add('states:end', function(name) {
            return new EndState(name, {
                text: $('Thank you. You will no longer receive ' +
                        'messages from us. If you have any medical ' +
                        'concerns please visit your nearest clinic.'),

                next: 'states:start'
            });
        });

    });

    return {
        GoNDOH: GoNDOH
    };
}();

<commit_msg>Fix save indentation<commit_after>go.app = function() {
    var vumigo = require('vumigo_v02');
    var App = vumigo.App;
    var Choice = vumigo.states.Choice;
    var ChoiceState = vumigo.states.ChoiceState;
    var EndState = vumigo.states.EndState;

    var GoNDOH = App.extend(function(self) {
        App.call(self, 'states:start');
        var $ = self.$;

        self.init = function() {
            return self.im.contacts
                .for_user()
                .then(function(user_contact) {
                   self.contact = user_contact;
                });
        };

        self.states.add('states:start', function(name) {
            return new ChoiceState(name, {
                question: $('Welcome to MomConnect. Why do you want to ' +
                            'stop receiving our messages?'),

                choices: [
                    new Choice('miscarriage', $('Miscarriage')),
                    new Choice('not_pregnant', $('Not pregnant')),
                    new Choice('not_useful', $('Messages not useful')),
                    new Choice('had_baby', $('Had my baby')),
                    new Choice('other', $('Other'))
                ],

                events: {
                    'state:enter': function() {
                        return self.im.api_request('optout.optout', {
                            address_type: "msisdn",
                            address_value: self.im.user_addr
                        });
                    }
                },

                next: function(choice) {
                    self.contact.extra.opt_out_reason = choice.value;

                    return self.im.contacts
                        .save(self.contact)
                        .then(function() {
                            return 'states:end';
                        });
                }

            });
        });

        self.states.add('states:end', function(name) {
            return new EndState(name, {
                text: $('Thank you. You will no longer receive ' +
                        'messages from us. If you have any medical ' +
                        'concerns please visit your nearest clinic.'),

                next: 'states:start'
            });
        });

    });

    return {
        GoNDOH: GoNDOH
    };
}();

<|endoftext|>


<commit_before>const OPTIONS = [
  // Static - Reference Info
  {
    id: 'lastRun',
    static: true,
    value: null,
  },

  // Section - General
  {
    id: 'enabled',
    section: 'general',
    type: 'boolean',
    defaultValue: true,
    title: 'Enable Play Midnight',
    description: `This will temporarily disable/enable Play Midnight if you don't want it on all the time`,
  },
  {
    id: 'accentsOnly',
    section: 'general',
    type: 'boolean',
    defaultValue: false,
    title: 'Enable Light-Mode Accents',
    description: 'This enables custom accents when Play Midnight is disabled',
  },

  // Section - Colorize
  {
    id: 'background',
    plural: 'backgrounds',
    section: 'colorize',
    type: 'array',
    title: 'Background Colors',
    description: `Not a fan of midnight? Well then let us change that!`,
    defaultValue: 'default',
    defaultValues: [
      { id: 'default', name: 'Midnight (Default)', value: '#141517' },
      { id: 'dusk', name: 'Dusk', value: '#171C2A' },
      { id: 'plum-berries', name: 'Plum Berries', value: '#1D1723' },
    ],
  },
  {
    id: 'accent',
    plural: 'accents',
    section: 'colorize',
    type: 'array',
    title: 'Accent Colors',
    description: `Customize the accent color to your heart's content`,
    defaultValue: 'default',
    defaultValues: [
      { id: 'default', name: 'Play Music (Default)', value: '#ec4e28' },
      { id: 'blue-abyss', name: 'Blue Abyss', value: '#007AA5' },
      { id: 'midnight-oil', name: 'Midnight Oil', value: '#6B2F79' },
      { id: 'prince-purple', name: 'Prince Purple', value: '#673ab7' },
      { id: 'redrum', name: 'Redrum', value: '#8E3055' },
      { id: 'rusty-spoon', name: 'Rusty Spoon', value: '#4c9014' },
    ],
  },

  // Section - Customize
  {
    id: 'favicon',
    section: 'customize',
    type: 'boolean',
    defaultValue: true,
    title: 'Show Play Midnight Favicon',
    description: `This is the icon that shows on your Google Play tab in the browser`,
  },
  {
    id: 'faviconAccent',
    section: 'customize',
    reliesOn: 'favicon',
    type: 'boolean',
    defaultValue: true,
    title: 'Show Accent Favicon',
    description: `Makes the favicon match your selected accent color instead of dark`,
  },
  {
    id: 'queue',
    section: 'customize',
    type: 'boolean',
    defaultValue: true,
    title: 'Enable Larger Queue',
    description: `Makes the now playing queue span across your screen further to prevent cutting off song titles`,
  },
  // {
  //   id: 'staticSidebar',
  //   section: 'customize',
  //   type: 'boolean',
  //   defaultValue: false,
  //   title: 'Enable Static Sidebar',
  //   description: `Show main sidebar on page load and keep it open permanently`,
  // },
  // {
  //   id: 'staticPlaylists',
  //   section: 'customize',
  //   type: 'boolean',
  //   defaultValue: false,
  //   title: 'Enable Static Playlists',
  //   description: `Show playlists sidebar on page load and keep it open permanently`,
  // },

  // Section - Visible Menus
  {
    id: 'myLibrary',
    section: 'visibleMenus',
    type: 'boolean',
    defaultValue: true,
    title: 'My Library',
    description: `The home of your wonderful music collection`,
  },
  {
    id: 'recent',
    section: 'visibleMenus',
    type: 'boolean',
    defaultValue: true,
    title: 'Recent Activity',
    description: `Access to your most recently played and added music`,
  },
  {
    id: 'topCharts',
    section: 'visibleMenus',
    type: 'boolean',
    defaultValue: true,
    title: 'Top Charts',
    description: `Top songs and albums currently trending in Play Music`,
  },
  {
    id: 'newReleases',
    section: 'visibleMenus',
    type: 'boolean',
    defaultValue: true,
    title: 'New Releases',
    description: `Newest albums and singles added to Play Music`,
  },
  {
    id: 'browseStations',
    section: 'visibleMenus',
    type: 'boolean',
    defaultValue: true,
    title: 'Browse Stations',
    description: `Radio stations brought directly to you from Google`,
  },
  {
    id: 'podcasts',
    section: 'visibleMenus',
    type: 'boolean',
    defaultValue: true,
    title: 'Podcasts',
    description: `Podcasts brought directly to you from Google`,
  },
  {
    id: 'shop',
    section: 'visibleMenus',
    type: 'boolean',
    defaultValue: true,
    title: 'Shop (Free Users Only)',
    description: `Shop menu for purchasing music if you're not an 'All Access' subscriber`,
  },
  {
    id: 'subscribe',
    section: 'visibleMenus',
    type: 'boolean',
    defaultValue: true,
    title: 'Subscribe Now (Free Users Only)',
    description: `Subscribe button for converting you to an 'All Access' subscriber`,
  },

  // Section - Visible Playlists
  {
    id: 'thumbsUp',
    section: 'visiblePlaylists',
    type: 'boolean',
    defaultValue: true,
    title: `Thumbs Up`,
    description: `All your favorite songs`,
  },
  {
    id: 'soundSearch',
    section: 'visiblePlaylists',
    type: 'boolean',
    defaultValue: false,
    title: `Sound search`,
    description: `The music you've found over time via Google Sound Search`,
  },
  {
    id: 'lastAdded',
    section: 'visiblePlaylists',
    type: 'boolean',
    defaultValue: true,
    title: `Last Added`,
    description: `All of your most recently added music`,
  },
  {
    id: 'freePurchased',
    section: 'visiblePlaylists',
    type: 'boolean',
    defaultValue: true,
    title: `Free and Purchased`,
    description: `The music you've paid for or collected over time`,
  },

  // Section - Default
  {
    id: 'devNote',
    type: 'string',
    title: 'Thanks!',
    description: `Here's a big old thanks for all you do!`,
  },
];

export const SECTIONS = [
  { id: 'general', title: 'General' },
  { id: 'colorize', title: 'Colorize' },
  { id: 'customize', title: 'Customize' },
  { id: 'visibleMenus', title: 'Visible Menus' },
  { id: 'visiblePlaylists', title: 'Visible Auto-Playlists' },
  { id: 'tidbits', title: 'Tidbits' },
  { id: 'default' },
];

export default OPTIONS;
<commit_msg>Tweaked default color options<commit_after>const OPTIONS = [
  // Static - Reference Info
  {
    id: 'lastRun',
    static: true,
    value: null,
  },

  // Section - General
  {
    id: 'enabled',
    section: 'general',
    type: 'boolean',
    defaultValue: true,
    title: 'Enable Play Midnight',
    description: `This will temporarily disable/enable Play Midnight if you don't want it on all the time`,
  },
  {
    id: 'accentsOnly',
    section: 'general',
    type: 'boolean',
    defaultValue: false,
    title: 'Enable Light-Mode Accents',
    description: 'This enables custom accents when Play Midnight is disabled',
  },

  // Section - Colorize
  {
    id: 'background',
    plural: 'backgrounds',
    section: 'colorize',
    type: 'array',
    title: 'Background Colors',
    description: `Not a fan of midnight? Well then let us change that!`,
    defaultValue: 'default',
    defaultValues: [
      { id: 'default', name: 'Midnight', value: '#141517' },
      { id: 'dusk', name: 'Dusk', value: '#171C2A' },
      { id: 'plum-berries', name: 'Plum Berries', value: '#1D1723' },
    ],
  },
  {
    id: 'accent',
    plural: 'accents',
    section: 'colorize',
    type: 'array',
    title: 'Accent Colors',
    description: `Customize the accent color to your heart's content`,
    defaultValue: 'default',
    defaultValues: [
      { id: 'default', name: 'Play Music', value: '#ec4e28' },
      { id: 'blue-abyss', name: 'Blue Abyss', value: '#007AA5' },
      { id: 'midnight-oil', name: 'Midnight Oil', value: '#6B2F79' },
      { id: 'prince-purple', name: 'Prince Purple', value: '#673ab7' },
      { id: 'redrum', name: 'Redrum', value: '#8E3055' },
      { id: 'rusty-spoon', name: 'Rusty Spoon', value: '#496438' },
    ],
  },

  // Section - Customize
  {
    id: 'favicon',
    section: 'customize',
    type: 'boolean',
    defaultValue: true,
    title: 'Show Play Midnight Favicon',
    description: `This is the icon that shows on your Google Play tab in the browser`,
  },
  {
    id: 'faviconAccent',
    section: 'customize',
    reliesOn: 'favicon',
    type: 'boolean',
    defaultValue: true,
    title: 'Show Accent Favicon',
    description: `Makes the favicon match your selected accent color instead of dark`,
  },
  {
    id: 'queue',
    section: 'customize',
    type: 'boolean',
    defaultValue: true,
    title: 'Enable Larger Queue',
    description: `Makes the now playing queue span across your screen further to prevent cutting off song titles`,
  },
  // {
  //   id: 'staticSidebar',
  //   section: 'customize',
  //   type: 'boolean',
  //   defaultValue: false,
  //   title: 'Enable Static Sidebar',
  //   description: `Show main sidebar on page load and keep it open permanently`,
  // },
  // {
  //   id: 'staticPlaylists',
  //   section: 'customize',
  //   type: 'boolean',
  //   defaultValue: false,
  //   title: 'Enable Static Playlists',
  //   description: `Show playlists sidebar on page load and keep it open permanently`,
  // },

  // Section - Visible Menus
  {
    id: 'myLibrary',
    section: 'visibleMenus',
    type: 'boolean',
    defaultValue: true,
    title: 'My Library',
    description: `The home of your wonderful music collection`,
  },
  {
    id: 'recent',
    section: 'visibleMenus',
    type: 'boolean',
    defaultValue: true,
    title: 'Recent Activity',
    description: `Access to your most recently played and added music`,
  },
  {
    id: 'topCharts',
    section: 'visibleMenus',
    type: 'boolean',
    defaultValue: true,
    title: 'Top Charts',
    description: `Top songs and albums currently trending in Play Music`,
  },
  {
    id: 'newReleases',
    section: 'visibleMenus',
    type: 'boolean',
    defaultValue: true,
    title: 'New Releases',
    description: `Newest albums and singles added to Play Music`,
  },
  {
    id: 'browseStations',
    section: 'visibleMenus',
    type: 'boolean',
    defaultValue: true,
    title: 'Browse Stations',
    description: `Radio stations brought directly to you from Google`,
  },
  {
    id: 'podcasts',
    section: 'visibleMenus',
    type: 'boolean',
    defaultValue: true,
    title: 'Podcasts',
    description: `Podcasts brought directly to you from Google`,
  },
  {
    id: 'shop',
    section: 'visibleMenus',
    type: 'boolean',
    defaultValue: true,
    title: 'Shop (Free Users Only)',
    description: `Shop menu for purchasing music if you're not an 'All Access' subscriber`,
  },
  {
    id: 'subscribe',
    section: 'visibleMenus',
    type: 'boolean',
    defaultValue: true,
    title: 'Subscribe Now (Free Users Only)',
    description: `Subscribe button for converting you to an 'All Access' subscriber`,
  },

  // Section - Visible Playlists
  {
    id: 'thumbsUp',
    section: 'visiblePlaylists',
    type: 'boolean',
    defaultValue: true,
    title: `Thumbs Up`,
    description: `All your favorite songs`,
  },
  {
    id: 'soundSearch',
    section: 'visiblePlaylists',
    type: 'boolean',
    defaultValue: false,
    title: `Sound search`,
    description: `The music you've found over time via Google Sound Search`,
  },
  {
    id: 'lastAdded',
    section: 'visiblePlaylists',
    type: 'boolean',
    defaultValue: true,
    title: `Last Added`,
    description: `All of your most recently added music`,
  },
  {
    id: 'freePurchased',
    section: 'visiblePlaylists',
    type: 'boolean',
    defaultValue: true,
    title: `Free and Purchased`,
    description: `The music you've paid for or collected over time`,
  },

  // Section - Default
  {
    id: 'devNote',
    type: 'string',
    title: 'Thanks!',
    description: `Here's a big old thanks for all you do!`,
  },
];

export const SECTIONS = [
  { id: 'general', title: 'General' },
  { id: 'colorize', title: 'Colorize' },
  { id: 'customize', title: 'Customize' },
  { id: 'visibleMenus', title: 'Visible Menus' },
  { id: 'visiblePlaylists', title: 'Visible Auto-Playlists' },
  { id: 'tidbits', title: 'Tidbits' },
  { id: 'default' },
];

export default OPTIONS;
<|endoftext|>


<commit_before>import _ from "underscore"
import toString from "./untracedToString"
import debuggerStatementFunction from "./debuggerStatementFunction"

export default function Origin(opts){
    var error = opts.error;
    if (!error) {
        Error.stackTraceLimit = 500;
        error = new Error();
    }

    this.action = opts.action;
    this.value = toString(opts.value)
    this.error = error;

    if (opts.inputValues.length > 0) {
        this.inputValues = opts.inputValues.map(function(iv){
            return getUsableInputValue(iv, error)
        })
    }

    if (opts.extraCharsAdded) {
        this.extraCharsAdded = opts.extraCharsAdded
    }

    if (opts.inputValuesCharacterIndex) {
        this.inputValuesCharacterIndex = opts.inputValuesCharacterIndex
    }
    if (opts.offsetAtCharIndex){
        this.offsetAtCharIndex = opts.offsetAtCharIndex
        if (this.offsetAtCharIndex.length == 0){
            debuggerStatementFunction()
        }
    }

    if (opts.isHTMLFileContent) {
        this.isHTMLFileContent = opts.isHTMLFileContent
    }
    if (opts.valueItems) {
        this.valueItems = opts.valueItems
    }
}

function getUsableInputValue(inputValue, error){
    if (typeof inputValue === "undefined") {
       return new Origin({
           action: "Undefined",
           inputValues: [],
           value: "undefined",
           error: error
       })
    }
    if (inputValue === null) {
       return new Origin({
           action: "Null",
           inputValues: [],
           value: "null",
           error: error
       })
    }
    if (inputValue.isFromJSOriginObject){
        return inputValue
    }
    if (inputValue.isFromJSFrozenElement) {
        return inputValue
    }
    if (inputValue.origin && inputValue.origin.isFromJSOriginObject){
        return inputValue.origin
    }
    if (inputValue instanceof Element){
        return inputValue
    }
    if (typeof inputValue === "number") {
        return new Origin({
            action: "Number",
            inputValues: [],
            value: inputValue,
            error: error
        })
    }
    if (typeof inputValue === "string") {
        return new Origin({
            action: "Untracked String",
            inputValues: [],
            value: inputValue,
            error: error
        })
    }
    if (typeof inputValue === "boolean") {
        return new Origin({
            action: "Boolean",
            inputValues: [],
            value: inputValue,
            error: error
        })
    }
    if (typeof inputValue === "object") {
        if (inputValue.toString !== Object.prototype.toString) {
            inputValue = inputValue.toString();
            return getUsableInputValue(inputValue, error)
        }
        return new Origin({
            action: "Object",
            inputValues: [],
            value: toString(inputValue), // would rather not store a whole obj reference
            error: error
        })
    }
    if (typeof inputValue === "function") {
       return new Origin({
           action: "Function",
           inputValues: [],
           value: toString(inputValue), // would rather not store a whole function reference
           error: error
       })
   }

    debuggerStatementFunction();
    return new Origin({
        action: "Unknown Thing",
        inputValues: [],
        value: toString(inputValue),
        error: error
    })
}

// easier for tests to handle / simulate than instanceof check
Object.defineProperty(Origin.prototype, "isFromJSOriginObject", {
    value: true
})

Origin.prototype.getId = function(){
    if (this._id === undefined) {
        this._id = _.uniqueId()
    }
    return this._id;
}

Object.defineProperty(Origin.prototype, "extraCharsAdded", {
    value: 0,
    writable: true
})

Object.defineProperty(Origin.prototype, "inputValues", {
    value: [],
    writable: true
})

Origin.prototype.getStackFrames = function(){
    return this.error.stack.split("\n").filter(function(frame){
        if (frame.indexOf("fromjs-internals/from.js") !== -1) {
            return false;
        }
        if (frame.indexOf("chrome-extension://") !== -1 &&
            (frame.indexOf("from.js") !== -1) || frame.indexOf("injected.js") !== -1) {
            return false;
        }
        if (frame.indexOf("/dist/from.js") !== -1) {
            return false
        }
        if (frame.indexOf("/base/src/test-setup.spec.js") !== -1) {
            return false
        }
        if (frame.indexOf("chrome-extension-from-string/from.js") !== -1) {
            return false;
        }
        if (frame.indexOf("playground/fromjs/") !== -1) {
            return false
        }
        if (frame.indexOf("http://localhost:8080/dist/from.js") !== -1) {
            return false;
        }
        if (frame.indexOf("webpack://") !== -1) {
            // loading from webpack-dev-server
            return false;
        }
        if (frame.indexOf("(native)") !== -1) {
            return false;
        }
        if (frame === "Error"){
            return false;
        }
        return true
    });
}

Origin.prototype.serialize = function(){
    return this._serialize();
}

Origin.prototype._serialize = function(shallow){
    var serialized = {...this}
    if (!serialized.inputValues) {
        serialized.inputValues = [];
    }

    if (shallow) {
        // prevent tree from sprawling arbitrarily deep
        serialized.inputValues = [];
        // Some input values can be elements, (which is wrong and should change at some point)
        // but for now avoid passing elements on to iframe.
        // ===> this could very well be fixed  now
        serialized.__elOrigin = null;

    } else {
        serialized.inputValues = serialized.inputValues.filter(function(iv){
            return iv instanceof Origin;
        })
        serialized.inputValues = serialized.inputValues.map(function(inputValue){
            return inputValue._serialize(true)
        })
        serialized.stack = this.getStackFrames();
    }
    serialized.id = this.getId();
    delete serialized.error
    delete serialized.valueItems

    return serialized;
}

window.Origin = Origin
<commit_msg>Remove unneeded values when serializing Origin.<commit_after>import _ from "underscore"
import toString from "./untracedToString"
import debuggerStatementFunction from "./debuggerStatementFunction"

export default function Origin(opts){
    var error = opts.error;
    if (!error) {
        Error.stackTraceLimit = 500;
        error = new Error();
    }

    this.action = opts.action;
    this.value = toString(opts.value)
    this.error = error;

    if (opts.inputValues.length > 0) {
        this.inputValues = opts.inputValues.map(function(iv){
            return getUsableInputValue(iv, error)
        })
    }

    if (opts.extraCharsAdded) {
        this.extraCharsAdded = opts.extraCharsAdded
    }

    if (opts.inputValuesCharacterIndex) {
        this.inputValuesCharacterIndex = opts.inputValuesCharacterIndex
    }
    if (opts.offsetAtCharIndex){
        this.offsetAtCharIndex = opts.offsetAtCharIndex
        if (this.offsetAtCharIndex.length == 0){
            debuggerStatementFunction()
        }
    }

    if (opts.isHTMLFileContent) {
        this.isHTMLFileContent = opts.isHTMLFileContent
    }
    if (opts.valueItems) {
        this.valueItems = opts.valueItems
    }
}

function getUsableInputValue(inputValue, error){
    if (typeof inputValue === "undefined") {
       return new Origin({
           action: "Undefined",
           inputValues: [],
           value: "undefined",
           error: error
       })
    }
    if (inputValue === null) {
       return new Origin({
           action: "Null",
           inputValues: [],
           value: "null",
           error: error
       })
    }
    if (inputValue.isFromJSOriginObject){
        return inputValue
    }
    if (inputValue.isFromJSFrozenElement) {
        return inputValue
    }
    if (inputValue.origin && inputValue.origin.isFromJSOriginObject){
        return inputValue.origin
    }
    if (inputValue instanceof Element){
        return inputValue
    }
    if (typeof inputValue === "number") {
        return new Origin({
            action: "Number",
            inputValues: [],
            value: inputValue,
            error: error
        })
    }
    if (typeof inputValue === "string") {
        return new Origin({
            action: "Untracked String",
            inputValues: [],
            value: inputValue,
            error: error
        })
    }
    if (typeof inputValue === "boolean") {
        return new Origin({
            action: "Boolean",
            inputValues: [],
            value: inputValue,
            error: error
        })
    }
    if (typeof inputValue === "object") {
        if (inputValue.toString !== Object.prototype.toString) {
            inputValue = inputValue.toString();
            return getUsableInputValue(inputValue, error)
        }
        return new Origin({
            action: "Object",
            inputValues: [],
            value: toString(inputValue), // would rather not store a whole obj reference
            error: error
        })
    }
    if (typeof inputValue === "function") {
       return new Origin({
           action: "Function",
           inputValues: [],
           value: toString(inputValue), // would rather not store a whole function reference
           error: error
       })
   }

    debuggerStatementFunction();
    return new Origin({
        action: "Unknown Thing",
        inputValues: [],
        value: toString(inputValue),
        error: error
    })
}

// easier for tests to handle / simulate than instanceof check
Object.defineProperty(Origin.prototype, "isFromJSOriginObject", {
    value: true
})

Origin.prototype.getId = function(){
    if (this._id === undefined) {
        this._id = _.uniqueId()
    }
    return this._id;
}

Object.defineProperty(Origin.prototype, "extraCharsAdded", {
    value: 0,
    writable: true
})

Object.defineProperty(Origin.prototype, "inputValues", {
    value: [],
    writable: true
})

Origin.prototype.getStackFrames = function(){
    return this.error.stack.split("\n").filter(function(frame){
        if (frame.indexOf("fromjs-internals/from.js") !== -1) {
            return false;
        }
        if (frame.indexOf("chrome-extension://") !== -1 &&
            (frame.indexOf("from.js") !== -1) || frame.indexOf("injected.js") !== -1) {
            return false;
        }
        if (frame.indexOf("/dist/from.js") !== -1) {
            return false
        }
        if (frame.indexOf("/base/src/test-setup.spec.js") !== -1) {
            return false
        }
        if (frame.indexOf("chrome-extension-from-string/from.js") !== -1) {
            return false;
        }
        if (frame.indexOf("playground/fromjs/") !== -1) {
            return false
        }
        if (frame.indexOf("http://localhost:8080/dist/from.js") !== -1) {
            return false;
        }
        if (frame.indexOf("webpack://") !== -1) {
            // loading from webpack-dev-server
            return false;
        }
        if (frame.indexOf("(native)") !== -1) {
            return false;
        }
        if (frame === "Error"){
            return false;
        }
        return true
    });
}

Origin.prototype.serialize = function(){
    return this._serialize();
}

Origin.prototype._serialize = function(shallow){
    var serialized = {...this}
    if (!serialized.inputValues) {
        serialized.inputValues = [];
    }

    if (shallow) {
        // prevent tree from sprawling arbitrarily deep
        serialized.inputValues = [];
        // Some input values can be elements, (which is wrong and should change at some point)
        // but for now avoid passing elements on to iframe.
        // ===> this could very well be fixed  now
        serialized.__elOrigin = null;

    } else {
        serialized.inputValues = serialized.inputValues.filter(function(iv){
            return iv instanceof Origin;
        })
        serialized.inputValues = serialized.inputValues.map(function(inputValue){
            return inputValue._serialize(true)
        })
        serialized.stack = this.getStackFrames();
    }
    serialized.id = this.getId();
    delete serialized.error
    delete serialized.valueItems
    delete serialized.offsetAtCharIndex
    delete serialized.inputValuesCharacterIndex
    delete serialized._id

    return serialized;
}

window.Origin = Origin
<|endoftext|>


<commit_before>var d3 = require('d3'),
    util = require('datalib/src/util'),
    changeset = require('vega-dataflow/src/ChangeSet'),
    Node = require('vega-dataflow/src/Node'), // jshint ignore:line
    Deps = require('vega-dataflow/src/Dependencies'),
    parseSignals = require('./signals'),
    selector = require('./events'),
    expr = require('./expr');

var GATEKEEPER = '_vgGATEKEEPER';

var vgEvent = {
  getGroup: function(name) { return name ? this.name[name] : this.group; },
  getXY: function(item) {
      var p = {x: this.x, y: this.y};
      if (typeof item === 'string') {
        item = this.name[item];
      }
      for (; item; item = item.mark && item.mark.group) {
        p.x -= item.x || 0;
        p.y -= item.y || 0;
      }
      return p;
    },
  getX: function(item) { return this.getXY(item).x; },
  getY: function(item) { return this.getXY(item).y; }
};

function parseStreams(view) {
  var model = view.model(),
      spec  = model.defs().signals,
      registry = {handlers: {}, nodes: {}},
      internal = util.duplicate(registry),  // Internal event processing
      external = util.duplicate(registry);  // External event processing

  (spec || []).forEach(function(sig) {
    var signal = model.signal(sig.name);
    if (sig.expr) return;  // Cannot have an expr and stream definition.

    (sig.streams || []).forEach(function(stream) {
      var sel = selector.parse(stream.type),
          exp = expr(stream.expr);
      mergedStream(signal, sel, exp, stream);
    });
  });

  // We register the event listeners all together so that if multiple
  // signals are registered on the same event, they will receive the
  // new value on the same pulse.
  util.keys(internal.handlers).forEach(function(type) {
    view.on(type, function(evt, item) {
      evt.preventDefault(); // stop text selection
      extendEvent(evt, item);
      fire(internal, type, (item && item.datum) || {}, evt);
    });
  });

  // add external event listeners
  util.keys(external.handlers).forEach(function(type) {
    if (typeof window === 'undefined') return; // No external support

    var h = external.handlers[type],
        t = type.split(':'), // --> no element pseudo-selectors
        elt = (t[0] === 'window') ? [window] :
              window.document.querySelectorAll(t[0]);

    function handler(evt) {
      extendEvent(evt);
      fire(external, type, d3.select(this).datum(), evt);
    }

    for (var i=0; i<elt.length; ++i) {
      elt[i].addEventListener(t[1], handler);
    }

    h.elements = elt;
    h.listener = handler;
  });

  // remove external event listeners
  external.detach = function() {
    util.keys(external.handlers).forEach(function(type) {
      var h = external.handlers[type],
          t = type.split(':'),
          elt = h.elements || [];

      for (var i=0; i<elt.length; ++i) {
        elt[i].removeEventListener(t[1], h.listener);
      }
    });
  };

  // export detach method
  return external.detach;

  // -- helper functions -----

  function extendEvent(evt, item) {
    var mouse = d3.mouse((d3.event=evt, view._el)),
        pad = view.padding(),
        names = {}, mark, group, i;

    if (item) {
      mark = item.mark;
      group = mark.marktype === 'group' ? item : mark.group;
      for (i=item; i!=null; i=i.mark.group) {
        if (i.mark.def.name) {
          names[i.mark.def.name] = i;
        }
      }
    }
    names.root = view.model().scene().items[0];

    evt.vg = Object.create(vgEvent);
    evt.vg.group = group;
    evt.vg.item = item || {};
    evt.vg.name = names;
    evt.vg.x = mouse[0] - pad.left;
    evt.vg.y = mouse[1] - pad.top;
  }

  function fire(registry, type, datum, evt) {
    var handlers = registry.handlers[type],
        node = registry.nodes[type],
        cs = changeset.create(null, true),
        filtered = false,
        val, i, n, h;

    function invoke(f) {
      return !f.fn(datum, evt, model.signalValues(f.globals));
    }

    for (i=0, n=handlers.length; i<n; ++i) {
      h = handlers[i];
      filtered = h.filters.some(invoke);
      if (filtered) continue;

      val = h.exp.fn(datum, evt, model.signalValues(h.exp.globals));
      if (h.spec.scale) {
        val = parseSignals.scale(model, h.spec, val, datum, evt);
      }

      if (val !== h.signal.value() || h.signal.verbose()) {
        h.signal.value(val);
        cs.signals[h.signal.name()] = 1;
      }
    }

    model.propagate(cs, node);
  }

  function mergedStream(sig, selector, exp, spec) {
    selector.forEach(function(s) {
      if (s.event)       event(sig, s, exp, spec);
      else if (s.signal) signal(sig, s, exp, spec);
      else if (s.start)  orderedStream(sig, s, exp, spec);
      else if (s.stream) mergedStream(sig, s.stream, exp, spec);
    });
  }

  function event(sig, selector, exp, spec) {
    var evt = selector.event,
        name = selector.name,
        mark = selector.mark,
        target   = selector.target,
        filters  = selector.filters || [],
        registry = target ? external : internal,
        type = target ? target+':'+evt : evt,
        node = registry.nodes[type] || (registry.nodes[type] = new Node(model)),
        handlers = registry.handlers[type] || (registry.handlers[type] = []);

    if (name) {
      filters.push('!!event.vg.name["' + name + '"]'); // Mimic event bubbling
    } else if (mark) {
      filters.push('event.vg.item.mark && event.vg.item.mark.marktype==='+util.str(mark));
    }

    handlers.push({
      signal: sig,
      exp: exp,
      spec: spec,
      filters: filters.map(function(f) { return expr(f); })
    });

    node.addListener(sig);
  }

  function signal(sig, selector, exp, spec) {
    var n = new Node(model);
    n.evaluate = function(input) {
      if (!input.signals[selector.signal]) return model.doNotPropagate;
      var val = exp.fn(null, null, model.signalValues(exp.globals));
      if (spec.scale) {
        val = parseSignals.scale(model, spec, val);
      }

      if (val !== sig.value() || sig.verbose()) {
        sig.value(val);
        input.signals[sig.name()] = 1;
        input.reflow = true;
      }

      return input;
    };
    n.dependency(Deps.SIGNALS, selector.signal);
    n.addListener(sig);
    model.signal(selector.signal).addListener(n);
  }

  function orderedStream(sig, selector, exp, spec) {
    var name = sig.name(),
        trueFn = expr('true'),
        falseFn = expr('false'),
        middle = selector.middle,
        filters = middle.filters || (middle.filters = []),
        gatekeeper = model.signal(name + GATEKEEPER, false);

    // Register an anonymous signal to act as a gatekeeper. It's value is
    // true or false depending on whether the start or end streams occur.
    // The middle signal then simply filters for the gatekeeper's value.
    mergedStream(gatekeeper, [selector.start], trueFn, {});
    mergedStream(gatekeeper, [selector.end], falseFn, {});

    filters.push(gatekeeper.name());
    mergedStream(sig, [selector.middle], exp, spec);
  }
}

module.exports = parseStreams;
parseStreams.schema = {
  "defs": {
    "streams": {
      "type": "array",
      "items": {
        "type": "object",

        "properties": {
          "type": {"type": "string"},
          "expr": {"type": "string"},
          "scale": {"$ref": "#/refs/scopedScale"}
        },

        "additionalProperties": false,
        "required": ["type", "expr"]
      }
    }
  }
};<commit_msg>Typos<commit_after>var d3 = require('d3'),
    util = require('datalib/src/util'),
    changeset = require('vega-dataflow/src/ChangeSet'),
    Node = require('vega-dataflow/src/Node'), // jshint ignore:line
    Deps = require('vega-dataflow/src/Dependencies'),
    parseSignals = require('./signals'),
    selector = require('./events'),
    expr = require('./expr');

var GATEKEEPER = '_vgGATEKEEPER';

var vgEvent = {
  getGroup: function(name) { return name ? this.name[name] : this.group; },
  getXY: function(item) {
      var p = {x: this.x, y: this.y};
      if (typeof item === 'string') {
        item = this.name[item];
      }
      for (; item; item = item.mark && item.mark.group) {
        p.x -= item.x || 0;
        p.y -= item.y || 0;
      }
      return p;
    },
  getX: function(item) { return this.getXY(item).x; },
  getY: function(item) { return this.getXY(item).y; }
};

function parseStreams(view) {
  var model = view.model(),
      spec  = model.defs().signals,
      registry = {handlers: {}, nodes: {}},
      internal = util.duplicate(registry),  // Internal event processing
      external = util.duplicate(registry);  // External event processing

  (spec || []).forEach(function(sig) {
    var signal = model.signal(sig.name);
    if (sig.expr) return;  // Cannot have an expr and stream definition.

    (sig.streams || []).forEach(function(stream) {
      var sel = selector.parse(stream.type),
          exp = expr(stream.expr);
      mergedStream(signal, sel, exp, stream);
    });
  });

  // We register the event listeners all together so that if multiple
  // signals are registered on the same event, they will receive the
  // new value on the same pulse.
  util.keys(internal.handlers).forEach(function(type) {
    view.on(type, function(evt, item) {
      evt.preventDefault(); // stop text selection
      extendEvent(evt, item);
      fire(internal, type, (item && item.datum) || {}, evt);
    });
  });

  // add external event listeners
  util.keys(external.handlers).forEach(function(type) {
    if (typeof window === 'undefined') return; // No external support

    var h = external.handlers[type],
        t = type.split(':'), // --> no element pseudo-selectors
        elt = (t[0] === 'window') ? [window] :
              window.document.querySelectorAll(t[0]);

    function handler(evt) {
      extendEvent(evt);
      fire(external, type, d3.select(this).datum(), evt);
    }

    for (var i=0; i<elt.length; ++i) {
      elt[i].addEventListener(t[1], handler);
    }

    h.elements = elt;
    h.listener = handler;
  });

  // remove external event listeners
  external.detach = function() {
    util.keys(external.handlers).forEach(function(type) {
      var h = external.handlers[type],
          t = type.split(':'),
          elt = h.elements || [];

      for (var i=0; i<elt.length; ++i) {
        elt[i].removeEventListener(t[1], h.listener);
      }
    });
  };

  // export detach method
  return external.detach;

  // -- helper functions -----

  function extendEvent(evt, item) {
    var mouse = d3.mouse((d3.event=evt, view._el)),
        pad = view.padding(),
        names = {}, mark, group, i;

    if (item) {
      mark = item.mark;
      group = mark.marktype === 'group' ? item : mark.group;
      for (i=item; i!=null; i=i.mark.group) {
        if (i.mark.def.name) {
          names[i.mark.def.name] = i;
        }
      }
    }
    names.root = view.model().scene().items[0];

    evt.vg = Object.create(vgEvent);
    evt.vg.group = group;
    evt.vg.item = item || {};
    evt.vg.name = names;
    evt.vg.x = mouse[0] - pad.left;
    evt.vg.y = mouse[1] - pad.top;
  }

  function fire(registry, type, datum, evt) {
    var handlers = registry.handlers[type],
        node = registry.nodes[type],
        cs = changeset.create(null, true),
        filtered = false,
        val, i, n, h;

    function invoke(f) {
      return !f.fn(datum, evt, model.signalValues(f.globals));
    }

    for (i=0, n=handlers.length; i<n; ++i) {
      h = handlers[i];
      filtered = h.filters.some(invoke);
      if (filtered) continue;

      val = h.exp.fn(datum, evt, model.signalValues(h.exp.globals));
      if (h.spec.scale) {
        val = parseSignals.scale(model, h.spec, val, datum, evt);
      }

      if (val !== h.signal.value() || h.signal.verbose()) {
        h.signal.value(val);
        cs.signals[h.signal.name()] = 1;
      }
    }

    model.propagate(cs, node);
  }

  function mergedStream(sig, selector, exp, spec) {
    selector.forEach(function(s) {
      if (s.event)       event(sig, s, exp, spec);
      else if (s.signal) signal(sig, s, exp, spec);
      else if (s.start)  orderedStream(sig, s, exp, spec);
      else if (s.stream) mergedStream(sig, s.stream, exp, spec);
    });
  }

  function event(sig, selector, exp, spec) {
    var evt = selector.event,
        name = selector.name,
        mark = selector.mark,
        target   = selector.target,
        filters  = selector.filters || [],
        registry = target ? external : internal,
        type = target ? target+':'+evt : evt,
        node = registry.nodes[type] || (registry.nodes[type] = new Node(model)),
        handlers = registry.handlers[type] || (registry.handlers[type] = []);

    if (name) {
      filters.push('!!event.vg.name["' + name + '"]'); // Mimic event bubbling
    } else if (mark) {
      filters.push('event.vg.item.mark && event.vg.item.mark.marktype==='+util.str(mark));
    }

    handlers.push({
      signal: sig,
      exp: exp,
      spec: spec,
      filters: filters.map(function(f) { return expr(f); })
    });

    node.addListener(sig);
  }

  function signal(sig, selector, exp, spec) {
    var n = new Node(model);
    n.evaluate = function(input) {
      if (!input.signals[selector.signal]) return model.doNotPropagate;
      var val = exp.fn(null, null, model.signalValues(exp.globals));
      if (spec.scale) {
        val = parseSignals.scale(model, spec, val);
      }

      if (val !== sig.value() || sig.verbose()) {
        sig.value(val);
        input.signals[sig.name()] = 1;
        input.reflow = true;
      }

      return input;
    };
    n.dependency(Deps.SIGNALS, selector.signal);
    n.addListener(sig);
    model.signal(selector.signal).addListener(n);
  }

  function orderedStream(sig, selector, exp, spec) {
    var name = sig.name(),
        trueFn  = expr('true'),
        falseFn = expr('false'),
        middle  = selector.middle,
        filters = middle.filters || (middle.filters = []),
        gatekeeper = model.signal(name + GATEKEEPER, false);

    // Register an anonymous signal to act as a gatekeeper. Its value is
    // true or false depending on whether the start or end streams occur.
    // The middle signal then simply filters for the gatekeeper's value.
    mergedStream(gatekeeper, [selector.start], trueFn, {});
    mergedStream(gatekeeper, [selector.end], falseFn, {});

    filters.push(gatekeeper.name());
    mergedStream(sig, [selector.middle], exp, spec);
  }
}

module.exports = parseStreams;
parseStreams.schema = {
  "defs": {
    "streams": {
      "type": "array",
      "items": {
        "type": "object",

        "properties": {
          "type": {"type": "string"},
          "expr": {"type": "string"},
          "scale": {"$ref": "#/refs/scopedScale"}
        },

        "additionalProperties": false,
        "required": ["type", "expr"]
      }
    }
  }
};<|endoftext|>


<commit_before>/**
 * @description Logs all actions and states after they are dispatched.
 */

import 'babel-polyfill';
import { find }         from 'lodash';
import * as ActionNames from '../actions/action-types';
import AudioPlayer      from '../utils/audio';

const audio = new AudioPlayer;

const musicPlayer = store => next => async action => {
  if (action.type === ActionNames.CLICK_MUSIC_ITEM) {
    const targetId   = action.id;
    const targetPath = find(store.getState().musics, { id: targetId }).filePath;

    audio.play(targetPath);
  }

  return next(action);
};

export default musicPlayer;
<commit_msg>modify: stop playing the music when starting playing music<commit_after>/**
 * @description Logs all actions and states after they are dispatched.
 */

import 'babel-polyfill';
import { find }         from 'lodash';
import * as ActionNames from '../actions/action-types';
import AudioPlayer      from '../utils/audio';

const audio = new AudioPlayer;

const musicPlayer = store => next => async action => {
  if (action.type === ActionNames.CLICK_MUSIC_ITEM) {
    const targetId   = action.id;
    const targetPath = find(store.getState().musics, { id: targetId }).filePath;

    audio.stop();
    audio.play(targetPath);
  }

  return next(action);
};

export default musicPlayer;
<|endoftext|>


<commit_before>import cloud from 'google-cloud';
import path from 'path';
import download from 'download';

const gcloud = cloud({
    projectId: process.env.GCLOUD_PROJECT, //eslint-disable-line
    keyFilename: path.join(__dirname, '../../keyfile.json')
});

const gcs = gcloud.storage();

const photoUpload = (ctx, next) => {
    const { telegram } = ctx;
    const fileId = ctx.state.fileId;
    if (fileId) {
        return telegram.getFileLink(fileId).then(fileLink => {
            download(fileLink, '.').then(() => {
                const bucket = gcs.bucket(process.env.STORAGE_BUCKET);
                const fileName = fileLink.slice(fileLink.lastIndexOf('/') + 1);
                const options = {
                    destination: fileId,
                    public: global.activeUsers.has(ctx.state.userId)

                };
                bucket.upload(fileName, options, err => {
                    if (err) {
                        console.log('ERROR::::::', err);
                    }
                });
            });
            return next();
        });
    }
    return next();
};

export default photoUpload;
<commit_msg>removes photos after uploading to bucket<commit_after>import cloud from 'google-cloud';
import path from 'path';
import download from 'download';
import fs from 'fs';

const gcloud = cloud({
    projectId: process.env.GCLOUD_PROJECT, //eslint-disable-line
    keyFilename: path.join(__dirname, '../../keyfile.json')
});

const gcs = gcloud.storage();

const photoUpload = (ctx, next) => {
    const { telegram } = ctx;
    const fileId = ctx.state.fileId;
    if (fileId) {
        return telegram.getFileLink(fileId).then(fileLink => {
            download(fileLink, '.').then(() => {
                const bucket = gcs.bucket(process.env.STORAGE_BUCKET);
                const fileName = fileLink.slice(fileLink.lastIndexOf('/') + 1);
                const options = {
                    destination: fileId,
                    public: global.activeUsers.has(ctx.state.userId)

                };
                bucket.upload(fileName, options, err => {
                    if (err) {
                        console.log('ERROR::::::', err);
                    }
                    const photoPath = path.join(__dirname, `../../${fileName}`);
                    fs.unlink((photoPath, fileName), e => {
                        if (e) {
                            console.log('Error when deleting file', e);
                        }
                    });
                });
            });
            return next();
        });
    }
    return next();
};

export default photoUpload;
<|endoftext|>


<commit_before>const scanArtist = require('./artists.js')
// import readRoot from './read-root.js'

const roots = [
  '/Users/ogd/Music/flac',
  '/Users/ogd/Music/mp3'
]

function reverseSize (a, b) {
  return b.getSize() - a.getSize()
}

scanArtist(roots).then(sorted => {
  console.log('ARTISTS\n=======\n')
  for (let a of sorted) {
    console.log('%s [%s]', a.name, a.getSize(1024 * 1024))
  }

  console.log('\n\nALBUMS\n======\n')
  const albums = sorted.reduce((l, r) => l.concat(r.albums), [])
                       .sort(reverseSize)
  for (let a of albums) {
    console.log(
      '%s - %s [%s]%s',
      a.artist,
      a.name,
      a.getSize(1024 * 1024),
      a.cuesheet ? ' [c]' : ''
    )
  }
}).catch(error => console.error('HURF DURF', error.stack))
<commit_msg>src: don't need packer anymore<commit_after><|endoftext|>


<commit_before>'use strict';

/**
 * Determines the response for a stub based on the user-provided response configuration
 * @module
 */

var helpers = require('../util/helpers'),
    errors = require('../util/errors'),
    behaviors = require('./behaviors'),
    Q = require('q'),
    stringify = require('json-stable-stringify');

/**
 * Creates the resolver
 * @param {Object} proxy - The protocol-specific proxy implementation
 * @param {Function} postProcess - The protocol-specific post-processor to add default response values
 * @returns {Object}
 */
function create (proxy, postProcess) {
    var injectState = {};

    function inject (request, fn, logger) {
        var deferred = Q.defer(),
            scope = helpers.clone(request),
            injected = '(' + fn + ')(scope, injectState, logger, deferred.resolve);';

        if (request.isDryRun === true) {
            Q.delay(1).then(function () {
                deferred.resolve({});
            });
        }
        else {
            try {
                var response = eval(injected);
                if (typeof response !== 'undefined') {
                    deferred.resolve(response);
                }
            }
            catch (error) {
                logger.error('injection X=> ' + error);
                logger.error('    full source: ' + JSON.stringify(injected));
                logger.error('    scope: ' + JSON.stringify(scope));
                logger.error('    injectState: ' + JSON.stringify(injectState));
                deferred.reject(errors.InjectionError('invalid response injection', {
                    source: injected,
                    data: error.message
                }));
            }
        }
        return deferred.promise;
    }

    function buildEquals (request, matchers) {
        var result = {};
        Object.keys(matchers).forEach(function (key) {
            if (typeof request[key] === 'object') {
                result[key] = buildEquals(request[key], matchers[key]);
            }
            else {
                result[key] = request[key];
            }
        });
        return result;
    }

    function predicatesFor (request, matchers) {
        var predicates = [];

        matchers.forEach(function (matcher) {
            var basePredicate = {};

            // Add parameters
            Object.keys(matcher).forEach(function (key) {
                if (key !== 'matches') {
                    basePredicate[key] = matcher[key];
                }
            });

            Object.keys(matcher.matches).forEach(function (fieldName) {
                var value = matcher.matches[fieldName],
                    predicate = helpers.clone(basePredicate);

                if (value === true) {
                    predicate.deepEquals = {};
                    predicate.deepEquals[fieldName] = request[fieldName];
                }
                else {
                    predicate.equals = {};
                    predicate.equals[fieldName] = buildEquals(request[fieldName], value);
                }

                predicates.push(predicate);
            });
        });

        return predicates;
    }

    function stubIndexFor (responseConfig, stubs) {
        for (var i = 0; i < stubs.length; i += 1) {
            var stub = stubs[i];
            if (stub.responses.indexOf(responseConfig) >= 0) {
                break;
            }
        }
        return i;
    }

    function proxyAndRecord (responseConfig, request, stubs) {
        return proxy.to(responseConfig.proxy.to, request, responseConfig.proxy)
        .then(function (response){
            if ( request.isDryRun ){
                return Q(response);
            }
            return Q(behaviors.execute(request, response, responseConfig.proxy._behaviors, logger))
        }).then(function (response) {
            var predicates = predicatesFor(request, responseConfig.proxy.predicateGenerators || []),
                stubResponse = { is: response },
                newStub = { predicates: predicates, responses: [stubResponse] },
                index = stubIndexFor(responseConfig, stubs);

            if (['proxyOnce', 'proxyAlways'].indexOf(responseConfig.proxy.mode) < 0) {
                responseConfig.proxy.mode = 'proxyOnce';
            }

            if (responseConfig.proxy.mode === 'proxyAlways') {
                for (index += 1; index < stubs.length; index += 1) {
                    if (stringify(predicates) === stringify(stubs[index].predicates)) {
                        stubs[index].responses.push(stubResponse);
                        return Q(response);
                    }
                }
            }

            stubs.splice(index, 0, newStub);
            return Q(response);
        });
    }

    function process (responseConfig, request, logger, stubs) {
        if (responseConfig.is) {
            return Q(responseConfig.is);
        }
        else if (responseConfig.proxy) {
            return proxyAndRecord(responseConfig, request, stubs);
        }
        else if (responseConfig.inject) {
            return inject(request, responseConfig.inject, logger).then(Q);
        }
        else {
            return Q.reject(errors.ValidationError('unrecognized response type', { source: responseConfig }));
        }
    }

    function hasMultipleTypes (responseConfig) {
        return (responseConfig.is && responseConfig.proxy) ||
               (responseConfig.is && responseConfig.inject) ||
               (responseConfig.proxy && responseConfig.inject);
    }

    /**
     * Resolves a single response
     * @memberOf module:models/responseResolver#
     * @param {Object} responseConfig - The API-provided response configuration
     * @param {Object} request - The protocol-specific request object
     * @param {Object} logger - The logger
     * @param {Object} stubs - The stubs for the imposter
     * @returns {Object} - Promise resolving to the response
     */
    function resolve (responseConfig, request, logger, stubs) {
        if (hasMultipleTypes(responseConfig)) {
            return Q.reject(errors.ValidationError('each response object must have only one response type', { source: responseConfig }));
        }

        return process(responseConfig, request, logger, stubs).then(function (response) {
            return Q(postProcess(response, request));
        }).then(function (response) {
            return Q(behaviors.execute(request, response, responseConfig._behaviors, logger));
        });
    }

    return {
        resolve: resolve
    };
}

module.exports = {
    create: create
};
<commit_msg>Fixing break<commit_after>'use strict';

/**
 * Determines the response for a stub based on the user-provided response configuration
 * @module
 */

var helpers = require('../util/helpers'),
    errors = require('../util/errors'),
    behaviors = require('./behaviors'),
    Q = require('q'),
    stringify = require('json-stable-stringify');

/**
 * Creates the resolver
 * @param {Object} proxy - The protocol-specific proxy implementation
 * @param {Function} postProcess - The protocol-specific post-processor to add default response values
 * @returns {Object}
 */
function create (proxy, postProcess) {
    var injectState = {};

    function inject (request, fn, logger) {
        var deferred = Q.defer(),
            scope = helpers.clone(request),
            injected = '(' + fn + ')(scope, injectState, logger, deferred.resolve);';

        if (request.isDryRun === true) {
            Q.delay(1).then(function () {
                deferred.resolve({});
            });
        }
        else {
            try {
                var response = eval(injected);
                if (typeof response !== 'undefined') {
                    deferred.resolve(response);
                }
            }
            catch (error) {
                logger.error('injection X=> ' + error);
                logger.error('    full source: ' + JSON.stringify(injected));
                logger.error('    scope: ' + JSON.stringify(scope));
                logger.error('    injectState: ' + JSON.stringify(injectState));
                deferred.reject(errors.InjectionError('invalid response injection', {
                    source: injected,
                    data: error.message
                }));
            }
        }
        return deferred.promise;
    }

    function buildEquals (request, matchers) {
        var result = {};
        Object.keys(matchers).forEach(function (key) {
            if (typeof request[key] === 'object') {
                result[key] = buildEquals(request[key], matchers[key]);
            }
            else {
                result[key] = request[key];
            }
        });
        return result;
    }

    function predicatesFor (request, matchers) {
        var predicates = [];

        matchers.forEach(function (matcher) {
            var basePredicate = {};

            // Add parameters
            Object.keys(matcher).forEach(function (key) {
                if (key !== 'matches') {
                    basePredicate[key] = matcher[key];
                }
            });

            Object.keys(matcher.matches).forEach(function (fieldName) {
                var value = matcher.matches[fieldName],
                    predicate = helpers.clone(basePredicate);

                if (value === true) {
                    predicate.deepEquals = {};
                    predicate.deepEquals[fieldName] = request[fieldName];
                }
                else {
                    predicate.equals = {};
                    predicate.equals[fieldName] = buildEquals(request[fieldName], value);
                }

                predicates.push(predicate);
            });
        });

        return predicates;
    }

    function stubIndexFor (responseConfig, stubs) {
        for (var i = 0; i < stubs.length; i += 1) {
            var stub = stubs[i];
            if (stub.responses.indexOf(responseConfig) >= 0) {
                break;
            }
        }
        return i;
    }

    function proxyAndRecord (responseConfig, request, logger, stubs) {
        return proxy.to(responseConfig.proxy.to, request, responseConfig.proxy)
        .then(function (response){
            if ( request.isDryRun ){
                return Q(response);
            }
            return Q(behaviors.execute(request, response, responseConfig.proxy._behaviors, logger))
        }).then(function (response) {
            var predicates = predicatesFor(request, responseConfig.proxy.predicateGenerators || []),
                stubResponse = { is: response },
                newStub = { predicates: predicates, responses: [stubResponse] },
                index = stubIndexFor(responseConfig, stubs);

            if (['proxyOnce', 'proxyAlways'].indexOf(responseConfig.proxy.mode) < 0) {
                responseConfig.proxy.mode = 'proxyOnce';
            }

            if (responseConfig.proxy.mode === 'proxyAlways') {
                for (index += 1; index < stubs.length; index += 1) {
                    if (stringify(predicates) === stringify(stubs[index].predicates)) {
                        stubs[index].responses.push(stubResponse);
                        return Q(response);
                    }
                }
            }

            stubs.splice(index, 0, newStub);
            return Q(response);
        });
    }

    function process (responseConfig, request, logger, stubs) {
        if (responseConfig.is) {
            return Q(responseConfig.is);
        }
        else if (responseConfig.proxy) {
            return proxyAndRecord(responseConfig, request, logger, stubs);
        }
        else if (responseConfig.inject) {
            return inject(request, responseConfig.inject, logger).then(Q);
        }
        else {
            return Q.reject(errors.ValidationError('unrecognized response type', { source: responseConfig }));
        }
    }

    function hasMultipleTypes (responseConfig) {
        return (responseConfig.is && responseConfig.proxy) ||
               (responseConfig.is && responseConfig.inject) ||
               (responseConfig.proxy && responseConfig.inject);
    }

    /**
     * Resolves a single response
     * @memberOf module:models/responseResolver#
     * @param {Object} responseConfig - The API-provided response configuration
     * @param {Object} request - The protocol-specific request object
     * @param {Object} logger - The logger
     * @param {Object} stubs - The stubs for the imposter
     * @returns {Object} - Promise resolving to the response
     */
    function resolve (responseConfig, request, logger, stubs) {
        if (hasMultipleTypes(responseConfig)) {
            return Q.reject(errors.ValidationError('each response object must have only one response type', { source: responseConfig }));
        }

        return process(responseConfig, request, logger, stubs).then(function (response) {
            return Q(postProcess(response, request));
        }).then(function (response) {
            return Q(behaviors.execute(request, response, responseConfig._behaviors, logger));
        });
    }

    return {
        resolve: resolve
    };
}

module.exports = {
    create: create
};
<|endoftext|>


<commit_before>var style = {
	textInput: {
		padding: '8px',
		paddingLeft: '16px',
		paddingRight: '16px',
		borderRadius: '50px', // 4px
		border: '1px solid rgb(210, 210, 210)',
		boxSizing: 'border-box',
		fooBar: 'none',
		outline: 'none',
		color: '#4E4E4E',
		fontSize: '14px',
		width: '100%',
		':focus': {
			border: '1px solid #20C753', // F96331 6E00FF
			color: '#000000'
		}
	}
};
export default style;
<commit_msg>Style fix for InputText. Closes #3<commit_after>var style = {
	textInput: {
		padding: '8px',
		paddingLeft: '16px',
		paddingRight: '16px',
		borderRadius: '50px', // 4px
		border: '1px solid rgb(210, 210, 210)',
		boxSizing: 'border-box',
      backgroundColor: 'transparent',
		fooBar: 'none',
		outline: 'none',
		color: '#4E4E4E',
		fontSize: '14px',
		width: '100%',
		':focus': {
			border: '1px solid #20C753', // F96331 6E00FF
			color: '#000000'
		}
	}
};
export default style;
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react';
import {
  Text,
  View,
  StyleSheet,
  Image,
  TouchableOpacity
} from 'react-native';

import * as NavigationState from '../../modules/navigation/NavigationState';

const Welcome = React.createClass({
  propTypes: {
    dispatch: PropTypes.func.isRequired
  },

  getInitialState() {
    return {
      username: '',
      password: '',
      background: 'rgba(255,0,54,1)'
    };
  },

  login() {
    this.props.dispatch(NavigationState.pushRoute({
      key: 'LoginView',
      title: 'Login'
    }));
  },

  render() {
    return (
      <View style={[styles.container, {backgroundColor: this.state.background}]}>
        <View style={styles.header}>
          <Text style={styles.titleText}>
              Tervetuloa!
          </Text>
          <Image style={styles.mark} source={require('../../../images/tervetuloa.png')}/>
        </View>
        <View style={styles.textContainer}>
          <View style={styles.textField}>
            <Text style={styles.textstyle}>
              Kahdeksan rastia odottavat sinua!
              Jokaisella rastilla suoritetaan tehtävä.
              Rasteja pitävät yritykset ja oppilaitokset
              kirjaavat rastisuoritukset puolestanne
            </Text>
          </View>
          <View style={styles.textField}>
            <Text style={styles.textstyle}>
              Kannattaa pelata läpi myös Super-Ada Quiz.
              Tasapistetilanteessa hyvin suoritettu Quiz ratkaisee voiton.
            </Text>
          </View>
          <View style={styles.textField}>
             <Text style={styles.boldText}>ONNEA MATKAAN!</Text>
          </View>
        </View>
        <TouchableOpacity onPress={this.login}>
          <View style={styles.button}>
              <Text style={styles.whiteFont}>MUOKKAA TIIMIÄ</Text>
          </View>
        </TouchableOpacity>
      </View>
    );
  }
});

const styles = StyleSheet.create({
  container: {
    flexDirection: 'column',
    flex: 1,
    backgroundColor: 'transparent'
  },
  header: {
    justifyContent: 'flex-start',
    alignItems: 'center',
    flex: 0,
    backgroundColor: 'transparent',
    marginTop: 20
  },
  titleText: {
    fontSize: 30,
    fontWeight: 'bold',
    color: '#FFF'
  },
  mark: {
    width: 200,
    height: 150
  },
  button: {
    backgroundColor: '#FF8A8C',
    padding: 20,
    marginLeft: 30,
    marginRight: 30,
    marginBottom: 20,
    alignItems: 'center'
  },
  textContainer: {
    marginTop: 2,
    marginBottom: 2,
    flex: .25
  },
  textField: {
  },
  whiteFont: {
    color: '#FFF',
    fontSize: 18,
    fontWeight: 'bold'
  },
  textstyle: {
    color: '#FFF',
    fontSize: 18,
    fontWeight: 'bold',
    marginLeft: 20,
    marginRight: 20,
    marginBottom: 20
  },
  boldText: {
    color: '#FFF',
    fontSize: 18,
    marginBottom: 15,
    fontWeight: 'bold',
    textAlign: 'center'
  }
});
export default Welcome;
<commit_msg>typo fix<commit_after>import React, {PropTypes} from 'react';
import {
  Text,
  View,
  StyleSheet,
  Image,
  TouchableOpacity
} from 'react-native';

import * as NavigationState from '../../modules/navigation/NavigationState';

const Welcome = React.createClass({
  propTypes: {
    dispatch: PropTypes.func.isRequired
  },

  getInitialState() {
    return {
      username: '',
      password: '',
      background: 'rgba(255,0,54,1)'
    };
  },

  login() {
    this.props.dispatch(NavigationState.pushRoute({
      key: 'LoginView',
      title: 'Login'
    }));
  },

  render() {
    return (
      <View style={[styles.container, {backgroundColor: this.state.background}]}>
        <View style={styles.header}>
          <Text style={styles.titleText}>
              Tervetuloa!
          </Text>
          <Image style={styles.mark} source={require('../../../images/tervetuloa.png')}/>
        </View>
        <View style={styles.textContainer}>
          <View style={styles.textField}>
            <Text style={styles.textstyle}>
              Kahdeksan rastia odottavat sinua!
              Jokaisella rastilla suoritetaan tehtävä.
              Rasteja pitävät yritykset ja oppilaitokset
              kirjaavat rastisuoritukset puolestanne
            </Text>
          </View>
          <View style={styles.textField}>
            <Text style={styles.textstyle}>
              Kannattaa pelata läpi myös Super-Ada Quiz.
              Tasapistetilanteessa hyvin suoritettu Quiz ratkaisee voiton.
            </Text>
          </View>
          <View style={styles.textField}>
             <Text style={styles.boldText}>ONNEA MATKAAN!</Text>
          </View>
        </View>
        <TouchableOpacity onPress={this.login}>
          <View style={styles.button}>
              <Text style={styles.whiteFont}>KIRJAUDU</Text>
          </View>
        </TouchableOpacity>
      </View>
    );
  }
});

const styles = StyleSheet.create({
  container: {
    flexDirection: 'column',
    flex: 1,
    backgroundColor: 'transparent'
  },
  header: {
    justifyContent: 'flex-start',
    alignItems: 'center',
    flex: 0,
    backgroundColor: 'transparent',
    marginTop: 20
  },
  titleText: {
    fontSize: 30,
    fontWeight: 'bold',
    color: '#FFF'
  },
  mark: {
    width: 200,
    height: 150
  },
  button: {
    backgroundColor: '#FF8A8C',
    padding: 20,
    marginLeft: 30,
    marginRight: 30,
    marginBottom: 20,
    alignItems: 'center'
  },
  textContainer: {
    marginTop: 2,
    marginBottom: 2,
    flex: .25
  },
  textField: {
  },
  whiteFont: {
    color: '#FFF',
    fontSize: 18,
    fontWeight: 'bold'
  },
  textstyle: {
    color: '#FFF',
    fontSize: 18,
    fontWeight: 'bold',
    marginLeft: 20,
    marginRight: 20,
    marginBottom: 20
  },
  boldText: {
    color: '#FFF',
    fontSize: 18,
    marginBottom: 15,
    fontWeight: 'bold',
    textAlign: 'center'
  }
});
export default Welcome;
<|endoftext|>


<commit_before>/* eslint-disable */
export const PERSON = {
  name: {
    first: 'John',
    middle: '',
    last: 'Doe',
  },
  about: 'Hi, my name is John Doe. I\'m just about the most boring type of person you could possibly imagine. I like collecting leaves from the tree in my back yard and documenting each time I eat a peanut that is non-uniform. I am not a robot. Please hire me.',
  position: 'Software Developer',
  birth: {
    year: 1990,
    location: 'New York'
  },
  experience: [{
      company: 'Company A',
      position: 'Developer',
      timeperiod: 'since January 2016',
      description: 'Programming and watching cute cat videos.'
    },
    {
      company: 'Company B',
      position: 'Frontend Developer',
      timeperiod: 'January 2015 - December 2015',
      description: 'Fulfillment of extremely important tasks.'
    },
    {
      company: 'Company C',
      position: 'Trainee',
      timeperiod: 'March 2014 - December 2014',
      description: 'Making coffee and baking cookies.'
    }
  ],
  education: [{
      degree: 'Master of Arts',
      timeperiod: 'March 2012 - December 2013',
      description: 'Major in Hacking and Computer Penetration, University A, New York, USA.'
    },
    {
      degree: 'Bachelor of Science',
      timeperiod: 'March 2009 - December 2011',
      description: 'Major in Engineering, University B, Los Angeles, USA.'
    }
  ],
  // skill level goes 0 to 100
  skills: [{
      name: 'HTML5',
      level: '99'
    },
    {
      name: 'CSS3',
      level: '95'
    },
    {
      name: 'JavaScript',
      level: '97'
    },
    {
      name: 'Node.js',
      level: '93'
    },
    {
      name: 'Angular 2',
      level: '60'
    },
    {
      name: 'TypeScript',
      level: '80'
    },
    {
      name: 'ES.Next',
      level: '70'
    },
    {
      name: 'Docker',
      level: '99'
    }
  ],
  skillDescription: 'Also proficient in Adobe Photoshop and Illustrator, grew up bilingual (English and Klingon).',
  contact: {
    email: 'john.doe@email.com',
    phone: '0123 456789',
    street: '1234 Broadway',
    city: 'New York',
    website: 'johndoe.com',
    github: 'johnyD'
  },
  lang: 'en' // en, de, fr, pt, cn, it, es, th, pt-br, ru, sv, id, hu, pl
};
<commit_msg>added nl to lang comment<commit_after>/* eslint-disable */
export const PERSON = {
  name: {
    first: 'John',
    middle: '',
    last: 'Doe',
  },
  about: 'Hi, my name is John Doe. I\'m just about the most boring type of person you could possibly imagine. I like collecting leaves from the tree in my back yard and documenting each time I eat a peanut that is non-uniform. I am not a robot. Please hire me.',
  position: 'Software Developer',
  birth: {
    year: 1990,
    location: 'New York'
  },
  experience: [{
      company: 'Company A',
      position: 'Developer',
      timeperiod: 'since January 2016',
      description: 'Programming and watching cute cat videos.'
    },
    {
      company: 'Company B',
      position: 'Frontend Developer',
      timeperiod: 'January 2015 - December 2015',
      description: 'Fulfillment of extremely important tasks.'
    },
    {
      company: 'Company C',
      position: 'Trainee',
      timeperiod: 'March 2014 - December 2014',
      description: 'Making coffee and baking cookies.'
    }
  ],
  education: [{
      degree: 'Master of Arts',
      timeperiod: 'March 2012 - December 2013',
      description: 'Major in Hacking and Computer Penetration, University A, New York, USA.'
    },
    {
      degree: 'Bachelor of Science',
      timeperiod: 'March 2009 - December 2011',
      description: 'Major in Engineering, University B, Los Angeles, USA.'
    }
  ],
  // skill level goes 0 to 100
  skills: [{
      name: 'HTML5',
      level: '99'
    },
    {
      name: 'CSS3',
      level: '95'
    },
    {
      name: 'JavaScript',
      level: '97'
    },
    {
      name: 'Node.js',
      level: '93'
    },
    {
      name: 'Angular 2',
      level: '60'
    },
    {
      name: 'TypeScript',
      level: '80'
    },
    {
      name: 'ES.Next',
      level: '70'
    },
    {
      name: 'Docker',
      level: '99'
    }
  ],
  skillDescription: 'Also proficient in Adobe Photoshop and Illustrator, grew up bilingual (English and Klingon).',
  contact: {
    email: 'john.doe@email.com',
    phone: '0123 456789',
    street: '1234 Broadway',
    city: 'New York',
    website: 'johndoe.com',
    github: 'johnyD'
  },
  lang: 'en' // en, de, fr, pt, cn, it, es, th, pt-br, ru, sv, id, hu, pl, nl
};
<|endoftext|>