<commit_before>require('../../support/test_helper');

var assert = require('../../support/assert');
var TestClient = require('../../support/test-client');
var dot = require('dot');

describe('analysis-layers use cases', function() {

    var multitypeStyleTemplate = dot.template([
        "#points['mapnik::geometry_type'=1] {",
        "  marker-fill-opacity: {{=it._opacity}};",
        "  marker-line-color: #FFF;",
        "  marker-line-width: 0.5;",
        "  marker-line-opacity: {{=it._opacity}};",
        "  marker-placement: point;",
        "  marker-type: ellipse;",
        "  marker-width: 8;",
        "  marker-fill: {{=it._color}};",
        "  marker-allow-overlap: true;",
        "}",
        "#lines['mapnik::geometry_type'=2] {",
        "  line-color: {{=it._color}};",
        "  line-width: 2;",
        "  line-opacity: {{=it._opacity}};",
        "}",
        "#polygons['mapnik::geometry_type'=3] {",
        "  polygon-fill: {{=it._color}};",
        "  polygon-opacity: {{=it._opacity}};",
        "  line-color: #FFF;",
        "  line-width: 0.5;",
        "  line-opacity: {{=it._opacity}};",
        "}"
    ].join('\n'));

    function cartocss(color, opacity) {
        return multitypeStyleTemplate({
            _color: color || '#F11810',
            _opacity: Number.isFinite(opacity) ? opacity : 1
        });
    }

    function mapConfig(layers, analysis) {
        return {
            version: '1.5.0',
            layers: layers,
            analysis: analysis || []
        };
    }

    function analysisDef(analysis) {
        return JSON.stringify(analysis);
    }

    var DEFAULT_MULTITYPE_STYLE = cartocss();

    var TILE_ANALYSIS_TABLES = { z: 14, x: 8023, y: 6177 };

    var useCases = [
        {
            desc: '1 mapnik layer',
            mapConfig: {
                version: '1.5.0',
                layers: [
                    {
                        type: 'cartodb',
                        options: {
                            sql: "select * from analysis_rent_listings",
                            cartocss: DEFAULT_MULTITYPE_STYLE,
                            cartocss_version: '2.3.0'
                        }
                    }
                ]
            }
        },

        {
            desc: '2 mapnik layers',
            mapConfig: mapConfig([
                {
                    type: 'cartodb',
                    options: {
                        sql: "select * from analysis_banks",
                        cartocss: cartocss('#2167AB'),
                        cartocss_version: '2.3.0'
                    }
                },
                {
                    type: 'cartodb',
                    options: {
                        sql: "select * from analysis_rent_listings",
                        cartocss: DEFAULT_MULTITYPE_STYLE,
                        cartocss_version: '2.3.0'
                    }
                }
            ])
        },

        {
            desc: 'rent listings + buffer over atm-machines',
            mapConfig: mapConfig([
                {
                    type: 'cartodb',
                    options: {
                        sql: "select * from analysis_rent_listings",
                        cartocss: DEFAULT_MULTITYPE_STYLE,
                        cartocss_version: '2.3.0'
                    }
                },
                {
                    type: 'analysis',
                    options: {
                        def: analysisDef({
                            "type": "buffer",
                            "params": {
                                "source": {
                                    "type": "source",
                                    "params": {
                                        "query": "select * from analysis_banks"
                                    }
                                },
                                "radio": 250
                            }
                        }),
                        cartocss: cartocss('black', 0.5)
                    }
                }
            ])
        },

        {
            desc: 'rent listings + point-in-polygon from buffer atm-machines and rent listings',
            mapConfig: mapConfig([
                {
                    type: 'cartodb',
                    options: {
                        sql: "select * from analysis_rent_listings",
                        cartocss: DEFAULT_MULTITYPE_STYLE,
                        cartocss_version: '2.3.0'
                    }
                },
                {
                    type: 'analysis',
                    options: {
                        def: analysisDef({
                            "type": "point-in-polygon",
                            "params": {
                                "pointsSource": {
                                    "type": "source",
                                    "params": {
                                        "query": "select * from analysis_rent_listings"
                                    }
                                },
                                "polygonsSource": {
                                    "type": "buffer",
                                    "params": {
                                        "source": {
                                            "type": "source",
                                            "params": {
                                                "query": "select * from analysis_banks"
                                            }
                                        },
                                        "radio": 250
                                    }
                                }
                            }
                        }),
                        cartocss: cartocss('green', 1.0)
                    }
                }
            ])
        },

        {
            desc: 'point-in-polygon from buffer atm-machines and rent listings + rent listings',
            mapConfig: mapConfig([
                {
                    type: 'analysis',
                    options: {
                        def: analysisDef({
                            "type": "point-in-polygon",
                            "params": {
                                "pointsSource": {
                                    "type": "source",
                                    "params": {
                                        "query": "select * from analysis_rent_listings"
                                    }
                                },
                                "polygonsSource": {
                                    "type": "buffer",
                                    "params": {
                                        "source": {
                                            "type": "source",
                                            "params": {
                                                "query": "select * from analysis_banks"
                                            }
                                        },
                                        "radio": 250
                                    }
                                }
                            }
                        }),
                        cartocss: cartocss('green', 1.0)
                    }
                },
                {
                    type: 'cartodb',
                    options: {
                        sql: "select * from analysis_rent_listings",
                        cartocss: DEFAULT_MULTITYPE_STYLE,
                        cartocss_version: '2.3.0'
                    }
                }
            ])
        },

        {
            desc: 'buffer + point-in-polygon from buffer atm-machines and rent listings + rent listings',
            mapConfig: mapConfig([
                {
                    type: 'cartodb',
                    options: {
                        sql: "select * from analysis_rent_listings",
                        cartocss: DEFAULT_MULTITYPE_STYLE,
                        cartocss_version: '2.3.0'
                    }
                },
                {
                    type: 'analysis',
                    options: {
                        def: analysisDef({
                            "type": "buffer",
                            "params": {
                                "source": {
                                    "type": "source",
                                    "params": {
                                        "query": "select * from analysis_banks"
                                    }
                                },
                                "radio": 300
                            }
                        }),
                        cartocss: cartocss('magenta', 0.5)
                    }
                },
                {
                    type: 'analysis',
                    options: {
                        def: analysisDef({
                            "type": "point-in-polygon",
                            "params": {
                                "pointsSource": {
                                    "type": "source",
                                    "params": {
                                        "query": "select * from analysis_rent_listings"
                                    }
                                },
                                "polygonsSource": {
                                    "type": "buffer",
                                    "params": {
                                        "source": {
                                            "type": "source",
                                            "params": {
                                                "query": "select * from analysis_banks"
                                            }
                                        },
                                        "radio": 300
                                    }
                                }
                            }
                        }),
                        cartocss: cartocss('green', 1.0)
                    }
                }
            ])
        },

        {
            skip: true,
            desc: 'buffer + point-in-polygon from buffer atm-machines and rent listings + rent listings',
            mapConfig: mapConfig([
                {
                    type: 'cartodb',
                    options: {
                        "source": { id: "a" },
                        "cartocss": DEFAULT_MULTITYPE_STYLE,
                        "cartocss_version": "2.3.0"
                    }
                },
                {
                    type: 'cartodb',
                    options: {
                        "source": { id: "b1" },
                        "cartocss": cartocss('green', 1.0),
                        "cartocss_version": "2.3.0"
                    }
                },
                {
                    type: 'cartodb',
                    options: {
                        "source": { id: "b2" },
                        "cartocss": cartocss('magenta', 0.5),
                        "cartocss_version": "2.3.0"
                    }
                }
            ],
            [
                {
                    id: "b2",
                    options: {
                        def: analysisDef({
                            "type": "count-in-polygon",
                            "id": "a0",
                            "params": {
                                "columnName": 'count_airbnb',
                                "pointsSource": {
                                    "type": "source",
                                    "params": {
                                        query: "select * from analysis_rent_listings"
                                    },
                                    dataviews: {
                                        price_histogram: {
                                            type: 'histogram',
                                            options: {
                                                column: 'price'
                                            }
                                        }
                                    }
                                },
                                "polygonsSource": {
                                    "id": "b1",
                                    "type": "buffer",
                                    "params": {
                                        "source": {
                                            "id": "b0",
                                            "type": "source",
                                            "params": {
                                                query: "select * from analysis_banks"
                                            }
                                        },
                                        "radio": 250
                                    },
                                    dataviews: {
                                        bank_category: {
                                            type: 'aggregation',
                                            options: {
                                                column: 'bank'
                                            }
                                        }
                                    }
                                }
                            },
                            dataviews: {
                                count_histogram: {
                                    type: 'histogram',
                                    options: {
                                        column: 'count_airbnb'
                                    }
                                }
                            }
                        }),
                        cartocss: cartocss('green', 1.0)
                    }
                }
            ])
        },

        {
            skip: true,
            desc: 'I. Distribution centers',
            mapConfig: mapConfig(
                [
                    {
                        type: 'cartodb',
                        options: {
                            "source": { id: "b0" },
                            "cartocss": [
                                "#distribution_centers {",
                                "  marker-fill-opacity: 1.0;",
                                "  marker-line-color: #FFF;",
                                "  marker-line-width: 0.5;",
                                "  marker-line-opacity: 0.7;",
                                "  marker-placement: point;",
                                "  marker-type: ellipse;",
                                "  marker-width: 8;",
                                "  marker-fill: blue;",
                                "  marker-allow-overlap: true;",
                                "}"
                            ].join('\n'),
                            "cartocss_version": "2.3.0"
                        }
                    },
                    {
                        type: 'cartodb',
                        options: {
                            "source": { id: "a0" },
                            "cartocss": [
                                "#shops {",
                                "  marker-fill-opacity: 1.0;",
                                "  marker-line-color: #FFF;",
                                "  marker-line-width: 0.5;",
                                "  marker-line-opacity: 0.7;",
                                "  marker-placement: point;",
                                "  marker-type: ellipse;",
                                "  marker-width: 8;",
                                "  marker-fill: red;",
                                "  marker-allow-overlap: true;",
                                "}"
                            ].join('\n'),
                            "cartocss_version": "2.3.0"
                        }
                    },
                    {
                        type: 'cartodb',
                        options: {
                            "source": { id: "a1" },
                            "cartocss": [
                                "#routing {",
                                "  line-color: ramp([routing_time], colorbrewer(Reds));",
                                "  line-width: ramp([routing_time], 2, 8);",
                                "  line-opacity: 1.0;",
                                "}"
                            ].join('\n'),
                            "cartocss_version": "2.3.0"
                        }
                    }
                ],
                [
                    {
                        id: 'a1',
                        type: 'routing-n-to-n',
                        params: {
                            // distanceColumn: 'routing_distance',
                            // timeColumn: 'routing_time',
                            originSource: {
                                id: 'b0',
                                type: 'source',
                                params: {
                                    query: 'select * from distribution_centers'
                                },
                                dataviews: {
                                    distribution_center_name_category: {
                                        type: 'aggregation',
                                        options: {
                                            column: 'name'
                                        }
                                    }
                                }
                            },
                            destinationSource: {
                                id: 'a0',
                                type: 'source',
                                params: {
                                    query: 'select * from shops'
                                }
                            }
                        },
                        dataviews: {
                            time_histogram: {
                                type: 'histogram',
                                options: {
                                    column: 'routing_time'
                                }
                            },
                            distance_histogram: {
                                type: 'histogram',
                                options: {
                                    column: 'routing_distance'
                                }
                            }
                        }
                    }
                ]
            )
        },

        {
            skip: true,
            desc: 'II. Population analysis',
            mapConfig: mapConfig([
                {
                    type: 'cartodb',
                    options: {
                        "source": { id: "a2" },
                        "cartocss": [
                            "#count_in_polygon {",
                            "  polygon-opacity: 1.0",
                            "  line-color: #FFF;",
                            "  line-width: 0.5;",
                            "  line-opacity: 0.7",
                            "  polygon-fill: ramp([estimated_people], colorbrewer(Reds));",
                            "}"
                        ].join('\n'),
                        "cartocss_version": "2.3.0"
                    }
                },
                {
                    type: 'cartodb',
                    options: {
                        "source": { id: "a0" },
                        "cartocss": DEFAULT_MULTITYPE_STYLE,
                        "cartocss_version": "2.3.0"
                    }
                }
            ],
            [
                {
                    id: 'a3',
                    type: 'total-population',
                    params: {
                        source: {
                            id: 'a2',
                            type: 'estimated-population',
                            params: {
                                columnName: 'estimated_people',
                                source: {
                                    id: 'a1',
                                    type: 'trade-area',
                                    params: {
                                        source: {
                                            "id": "a0",
                                            "type": "source",
                                            "params": {
                                                query: "select * from subway_stops"
                                            }
                                        },
                                        kind: 'walk',
                                        time: 300
                                    },
                                    dataviews: {
                                        subway_line_category: {
                                            type: 'aggregation',
                                            options: {
                                                column: 'subway_line'
                                            }
                                        }
                                    }
                                }
                            },
                            dataviews: {
                                people_histogram: {
                                    type: 'histogram',
                                    options: {
                                        column: 'estimated_people'
                                    }
                                }
                            }
                        }
                    },
                    dataviews: {
                        total_population_formula: {
                            type: 'formula',
                            options: {
                                column: 'estimated_people',
                                operation: 'sum'
                            }
                        }
                    }
                }
            ])
        },

        {
            skip: true,
            desc: 'III. Point in polygon',
            mapConfig: mapConfig(
                [
                    {
                        type: 'cartodb',
                        options: {
                            "source": { id: "a1" },
                            "cartocss": [
                                "#count_in_polygon {",
                                "  polygon-opacity: 1.0",
                                "  line-color: #FFF;",
                                "  line-width: 0.5;",
                                "  line-opacity: 0.7",
                                "  polygon-fill: ramp([count_people], colorbrewer(Reds));",
                                "}"
                            ].join('\n'),
                            "cartocss_version": "2.3.0"
                        }
                    }
                ],
                [
                    {
                        "id": "a1",
                        "type": "count-in-polygon",
                        "params": {
                            "columnName": 'count_people',
                            "pointsSource": {
                                "id": 'a0',
                                "type": "source",
                                "params": {
                                    query: "select the_geom, age, gender, income from people"
                                },
                                dataviews: {
                                    age_histogram: {
                                        type: 'histogram',
                                        options: {
                                            column: 'age'
                                        }
                                    },
                                    income_histogram: {
                                        type: 'histogram',
                                        options: {
                                            column: 'income'
                                        }
                                    },
                                    gender_category: {
                                        type: 'aggregation',
                                        options: {
                                            column: 'gender'
                                        }
                                    }
                                }
                            },
                            "polygonsSource": {
                                "id": "b0",
                                "type": "source",
                                "params": {
                                    query: "select * from postal_codes"
                                }
                            }
                        }
                    }
                ]
            )
        }

    ];

    useCases.forEach(function(useCase, imageIdx) {
        if (!!useCase.skip) {
            console.log(JSON.stringify(useCase.mapConfig, null, 4));
        }
        it.skip('should implement use case: "' + useCase.desc + '"', function(done) {

            var testClient = new TestClient(useCase.mapConfig, 1234);

            var tile = useCase.tile || TILE_ANALYSIS_TABLES;

            testClient.getTile(tile.z, tile.x, tile.y, function(err, res, image) {
                assert.ok(!err, err);

                image.save('/tmp/tests/' + imageIdx + '---' + useCase.desc.replace(/\s/g, '-') + '.png');

                assert.equal(image.width(), 256);

                testClient.drain(done);
            });
        });
    });
});
<commit_msg>Notes to make clear the total-population analysis<commit_after>require('../../support/test_helper');

var assert = require('../../support/assert');
var TestClient = require('../../support/test-client');
var dot = require('dot');

describe('analysis-layers use cases', function() {

    var multitypeStyleTemplate = dot.template([
        "#points['mapnik::geometry_type'=1] {",
        "  marker-fill-opacity: {{=it._opacity}};",
        "  marker-line-color: #FFF;",
        "  marker-line-width: 0.5;",
        "  marker-line-opacity: {{=it._opacity}};",
        "  marker-placement: point;",
        "  marker-type: ellipse;",
        "  marker-width: 8;",
        "  marker-fill: {{=it._color}};",
        "  marker-allow-overlap: true;",
        "}",
        "#lines['mapnik::geometry_type'=2] {",
        "  line-color: {{=it._color}};",
        "  line-width: 2;",
        "  line-opacity: {{=it._opacity}};",
        "}",
        "#polygons['mapnik::geometry_type'=3] {",
        "  polygon-fill: {{=it._color}};",
        "  polygon-opacity: {{=it._opacity}};",
        "  line-color: #FFF;",
        "  line-width: 0.5;",
        "  line-opacity: {{=it._opacity}};",
        "}"
    ].join('\n'));

    function cartocss(color, opacity) {
        return multitypeStyleTemplate({
            _color: color || '#F11810',
            _opacity: Number.isFinite(opacity) ? opacity : 1
        });
    }

    function mapConfig(layers, analysis) {
        return {
            version: '1.5.0',
            layers: layers,
            analysis: analysis || []
        };
    }

    function analysisDef(analysis) {
        return JSON.stringify(analysis);
    }

    var DEFAULT_MULTITYPE_STYLE = cartocss();

    var TILE_ANALYSIS_TABLES = { z: 14, x: 8023, y: 6177 };

    var useCases = [
        {
            desc: '1 mapnik layer',
            mapConfig: {
                version: '1.5.0',
                layers: [
                    {
                        type: 'cartodb',
                        options: {
                            sql: "select * from analysis_rent_listings",
                            cartocss: DEFAULT_MULTITYPE_STYLE,
                            cartocss_version: '2.3.0'
                        }
                    }
                ]
            }
        },

        {
            desc: '2 mapnik layers',
            mapConfig: mapConfig([
                {
                    type: 'cartodb',
                    options: {
                        sql: "select * from analysis_banks",
                        cartocss: cartocss('#2167AB'),
                        cartocss_version: '2.3.0'
                    }
                },
                {
                    type: 'cartodb',
                    options: {
                        sql: "select * from analysis_rent_listings",
                        cartocss: DEFAULT_MULTITYPE_STYLE,
                        cartocss_version: '2.3.0'
                    }
                }
            ])
        },

        {
            desc: 'rent listings + buffer over atm-machines',
            mapConfig: mapConfig([
                {
                    type: 'cartodb',
                    options: {
                        sql: "select * from analysis_rent_listings",
                        cartocss: DEFAULT_MULTITYPE_STYLE,
                        cartocss_version: '2.3.0'
                    }
                },
                {
                    type: 'analysis',
                    options: {
                        def: analysisDef({
                            "type": "buffer",
                            "params": {
                                "source": {
                                    "type": "source",
                                    "params": {
                                        "query": "select * from analysis_banks"
                                    }
                                },
                                "radio": 250
                            }
                        }),
                        cartocss: cartocss('black', 0.5)
                    }
                }
            ])
        },

        {
            desc: 'rent listings + point-in-polygon from buffer atm-machines and rent listings',
            mapConfig: mapConfig([
                {
                    type: 'cartodb',
                    options: {
                        sql: "select * from analysis_rent_listings",
                        cartocss: DEFAULT_MULTITYPE_STYLE,
                        cartocss_version: '2.3.0'
                    }
                },
                {
                    type: 'analysis',
                    options: {
                        def: analysisDef({
                            "type": "point-in-polygon",
                            "params": {
                                "pointsSource": {
                                    "type": "source",
                                    "params": {
                                        "query": "select * from analysis_rent_listings"
                                    }
                                },
                                "polygonsSource": {
                                    "type": "buffer",
                                    "params": {
                                        "source": {
                                            "type": "source",
                                            "params": {
                                                "query": "select * from analysis_banks"
                                            }
                                        },
                                        "radio": 250
                                    }
                                }
                            }
                        }),
                        cartocss: cartocss('green', 1.0)
                    }
                }
            ])
        },

        {
            desc: 'point-in-polygon from buffer atm-machines and rent listings + rent listings',
            mapConfig: mapConfig([
                {
                    type: 'analysis',
                    options: {
                        def: analysisDef({
                            "type": "point-in-polygon",
                            "params": {
                                "pointsSource": {
                                    "type": "source",
                                    "params": {
                                        "query": "select * from analysis_rent_listings"
                                    }
                                },
                                "polygonsSource": {
                                    "type": "buffer",
                                    "params": {
                                        "source": {
                                            "type": "source",
                                            "params": {
                                                "query": "select * from analysis_banks"
                                            }
                                        },
                                        "radio": 250
                                    }
                                }
                            }
                        }),
                        cartocss: cartocss('green', 1.0)
                    }
                },
                {
                    type: 'cartodb',
                    options: {
                        sql: "select * from analysis_rent_listings",
                        cartocss: DEFAULT_MULTITYPE_STYLE,
                        cartocss_version: '2.3.0'
                    }
                }
            ])
        },

        {
            desc: 'buffer + point-in-polygon from buffer atm-machines and rent listings + rent listings',
            mapConfig: mapConfig([
                {
                    type: 'cartodb',
                    options: {
                        sql: "select * from analysis_rent_listings",
                        cartocss: DEFAULT_MULTITYPE_STYLE,
                        cartocss_version: '2.3.0'
                    }
                },
                {
                    type: 'analysis',
                    options: {
                        def: analysisDef({
                            "type": "buffer",
                            "params": {
                                "source": {
                                    "type": "source",
                                    "params": {
                                        "query": "select * from analysis_banks"
                                    }
                                },
                                "radio": 300
                            }
                        }),
                        cartocss: cartocss('magenta', 0.5)
                    }
                },
                {
                    type: 'analysis',
                    options: {
                        def: analysisDef({
                            "type": "point-in-polygon",
                            "params": {
                                "pointsSource": {
                                    "type": "source",
                                    "params": {
                                        "query": "select * from analysis_rent_listings"
                                    }
                                },
                                "polygonsSource": {
                                    "type": "buffer",
                                    "params": {
                                        "source": {
                                            "type": "source",
                                            "params": {
                                                "query": "select * from analysis_banks"
                                            }
                                        },
                                        "radio": 300
                                    }
                                }
                            }
                        }),
                        cartocss: cartocss('green', 1.0)
                    }
                }
            ])
        },

        {
            skip: true,
            desc: 'buffer + point-in-polygon from buffer atm-machines and rent listings + rent listings',
            mapConfig: mapConfig([
                {
                    type: 'cartodb',
                    options: {
                        "source": { id: "a" },
                        "cartocss": DEFAULT_MULTITYPE_STYLE,
                        "cartocss_version": "2.3.0"
                    }
                },
                {
                    type: 'cartodb',
                    options: {
                        "source": { id: "b1" },
                        "cartocss": cartocss('green', 1.0),
                        "cartocss_version": "2.3.0"
                    }
                },
                {
                    type: 'cartodb',
                    options: {
                        "source": { id: "b2" },
                        "cartocss": cartocss('magenta', 0.5),
                        "cartocss_version": "2.3.0"
                    }
                }
            ],
            [
                {
                    id: "b2",
                    options: {
                        def: analysisDef({
                            "type": "count-in-polygon",
                            "id": "a0",
                            "params": {
                                "columnName": 'count_airbnb',
                                "pointsSource": {
                                    "type": "source",
                                    "params": {
                                        query: "select * from analysis_rent_listings"
                                    },
                                    dataviews: {
                                        price_histogram: {
                                            type: 'histogram',
                                            options: {
                                                column: 'price'
                                            }
                                        }
                                    }
                                },
                                "polygonsSource": {
                                    "id": "b1",
                                    "type": "buffer",
                                    "params": {
                                        "source": {
                                            "id": "b0",
                                            "type": "source",
                                            "params": {
                                                query: "select * from analysis_banks"
                                            }
                                        },
                                        "radio": 250
                                    },
                                    dataviews: {
                                        bank_category: {
                                            type: 'aggregation',
                                            options: {
                                                column: 'bank'
                                            }
                                        }
                                    }
                                }
                            },
                            dataviews: {
                                count_histogram: {
                                    type: 'histogram',
                                    options: {
                                        column: 'count_airbnb'
                                    }
                                }
                            }
                        }),
                        cartocss: cartocss('green', 1.0)
                    }
                }
            ])
        },

        {
            skip: true,
            desc: 'I. Distribution centers',
            mapConfig: mapConfig(
                [
                    {
                        type: 'cartodb',
                        options: {
                            "source": { id: "b0" },
                            "cartocss": [
                                "#distribution_centers {",
                                "  marker-fill-opacity: 1.0;",
                                "  marker-line-color: #FFF;",
                                "  marker-line-width: 0.5;",
                                "  marker-line-opacity: 0.7;",
                                "  marker-placement: point;",
                                "  marker-type: ellipse;",
                                "  marker-width: 8;",
                                "  marker-fill: blue;",
                                "  marker-allow-overlap: true;",
                                "}"
                            ].join('\n'),
                            "cartocss_version": "2.3.0"
                        }
                    },
                    {
                        type: 'cartodb',
                        options: {
                            "source": { id: "a0" },
                            "cartocss": [
                                "#shops {",
                                "  marker-fill-opacity: 1.0;",
                                "  marker-line-color: #FFF;",
                                "  marker-line-width: 0.5;",
                                "  marker-line-opacity: 0.7;",
                                "  marker-placement: point;",
                                "  marker-type: ellipse;",
                                "  marker-width: 8;",
                                "  marker-fill: red;",
                                "  marker-allow-overlap: true;",
                                "}"
                            ].join('\n'),
                            "cartocss_version": "2.3.0"
                        }
                    },
                    {
                        type: 'cartodb',
                        options: {
                            "source": { id: "a1" },
                            "cartocss": [
                                "#routing {",
                                "  line-color: ramp([routing_time], colorbrewer(Reds));",
                                "  line-width: ramp([routing_time], 2, 8);",
                                "  line-opacity: 1.0;",
                                "}"
                            ].join('\n'),
                            "cartocss_version": "2.3.0"
                        }
                    }
                ],
                [
                    {
                        id: 'a1',
                        type: 'routing-n-to-n',
                        params: {
                            // distanceColumn: 'routing_distance',
                            // timeColumn: 'routing_time',
                            originSource: {
                                id: 'b0',
                                type: 'source',
                                params: {
                                    query: 'select * from distribution_centers'
                                },
                                dataviews: {
                                    distribution_center_name_category: {
                                        type: 'aggregation',
                                        options: {
                                            column: 'name'
                                        }
                                    }
                                }
                            },
                            destinationSource: {
                                id: 'a0',
                                type: 'source',
                                params: {
                                    query: 'select * from shops'
                                }
                            }
                        },
                        dataviews: {
                            time_histogram: {
                                type: 'histogram',
                                options: {
                                    column: 'routing_time'
                                }
                            },
                            distance_histogram: {
                                type: 'histogram',
                                options: {
                                    column: 'routing_distance'
                                }
                            }
                        }
                    }
                ]
            )
        },

        {
            skip: true,
            desc: 'II. Population analysis',
            mapConfig: mapConfig([
                {
                    type: 'cartodb',
                    options: {
                        "source": { id: "a2" },
                        "cartocss": [
                            "#count_in_polygon {",
                            "  polygon-opacity: 1.0",
                            "  line-color: #FFF;",
                            "  line-width: 0.5;",
                            "  line-opacity: 0.7",
                            "  polygon-fill: ramp([estimated_people], colorbrewer(Reds));",
                            "}"
                        ].join('\n'),
                        "cartocss_version": "2.3.0"
                    }
                },
                {
                    type: 'cartodb',
                    options: {
                        "source": { id: "a0" },
                        "cartocss": DEFAULT_MULTITYPE_STYLE,
                        "cartocss_version": "2.3.0"
                    }
                }
            ],
            [
                {
                    id: 'a3',
                    // this will union the polygons, produce just one polygon, and calculate the total population for it
                    type: 'total-population',
                    params: {
                        columnName: 'total_population',
                        source: {
                            id: 'a2',
                            type: 'estimated-population',
                            params: {
                                columnName: 'estimated_people',
                                source: {
                                    id: 'a1',
                                    type: 'trade-area',
                                    params: {
                                        source: {
                                            "id": "a0",
                                            "type": "source",
                                            "params": {
                                                query: "select * from subway_stops"
                                            }
                                        },
                                        kind: 'walk',
                                        time: 300
                                    },
                                    dataviews: {
                                        subway_line_category: {
                                            type: 'aggregation',
                                            options: {
                                                column: 'subway_line'
                                            }
                                        }
                                    }
                                }
                            },
                            dataviews: {
                                people_histogram: {
                                    type: 'histogram',
                                    options: {
                                        column: 'estimated_people'
                                    }
                                }
                            }
                        }
                    },
                    dataviews: {
                        total_population_formula: {
                            type: 'formula',
                            options: {
                                column: 'estimated_people',
                                operation: 'sum'
                            }
                        }
                    }
                }
            ])
        },

        {
            skip: true,
            desc: 'III. Point in polygon',
            mapConfig: mapConfig(
                [
                    {
                        type: 'cartodb',
                        options: {
                            "source": { id: "a1" },
                            "cartocss": [
                                "#count_in_polygon {",
                                "  polygon-opacity: 1.0",
                                "  line-color: #FFF;",
                                "  line-width: 0.5;",
                                "  line-opacity: 0.7",
                                "  polygon-fill: ramp([count_people], colorbrewer(Reds));",
                                "}"
                            ].join('\n'),
                            "cartocss_version": "2.3.0"
                        }
                    }
                ],
                [
                    {
                        "id": "a1",
                        "type": "count-in-polygon",
                        "params": {
                            "columnName": 'count_people',
                            "pointsSource": {
                                "id": 'a0',
                                "type": "source",
                                "params": {
                                    query: "select the_geom, age, gender, income from people"
                                },
                                dataviews: {
                                    age_histogram: {
                                        type: 'histogram',
                                        options: {
                                            column: 'age'
                                        }
                                    },
                                    income_histogram: {
                                        type: 'histogram',
                                        options: {
                                            column: 'income'
                                        }
                                    },
                                    gender_category: {
                                        type: 'aggregation',
                                        options: {
                                            column: 'gender'
                                        }
                                    }
                                }
                            },
                            "polygonsSource": {
                                "id": "b0",
                                "type": "source",
                                "params": {
                                    query: "select * from postal_codes"
                                }
                            }
                        }
                    }
                ]
            )
        }

    ];

    useCases.forEach(function(useCase, imageIdx) {
        if (!!useCase.skip) {
            console.log(JSON.stringify(useCase.mapConfig, null, 4));
        }
        it.skip('should implement use case: "' + useCase.desc + '"', function(done) {

            var testClient = new TestClient(useCase.mapConfig, 1234);

            var tile = useCase.tile || TILE_ANALYSIS_TABLES;

            testClient.getTile(tile.z, tile.x, tile.y, function(err, res, image) {
                assert.ok(!err, err);

                image.save('/tmp/tests/' + imageIdx + '---' + useCase.desc.replace(/\s/g, '-') + '.png');

                assert.equal(image.width(), 256);

                testClient.drain(done);
            });
        });
    });
});
<|endoftext|>


<commit_before>var React = require('react/addons');

React.createElement(React.addons.CSSTransitionGroup, null, "");
<commit_msg>Fix linter warning in a test file<commit_after>var React = require('react/addons');

React.createElement(React.addons.CSSTransitionGroup, null, '');
<|endoftext|>


<commit_before>var Q = require('q');
var Economy = require('../economy');
var User = require('../mongo').userModel;
var fs = require('fs');

var shop = [
    ['Symbol', 'Buys a custom symbol to go infront of name and puts you at top of userlist. (Temporary until restart, certain symbols are blocked)', 5],
    ['Fix', 'Buys the ability to alter your current custom avatar or trainer card. (don\'t buy if you have neither)', 10],
    ['PM', 'Send a message to everyone on the server. [Can be refused] (Everyone on the server will receive a message from "~Server PM - [Do not reply] Uses: League Advertisements, Celebrations, ETC', 20],
    ['Avatar', 'Buys an custom avatar to be applied to your name (You supply. Images larger than 80x80 may not show correctly)', 50],
    ['Declare', 'Globally declare a message to the whole server! [Can be refused](A small blue message that every chatroom can see; Uses: League Advertisements, Celebrations, ETC)', 50],
    ['Trainer', 'Buys a trainer card which shows information through a command. (You supply, can be refused)', 50],
    ['Room', 'Buys a chatroom for you to own. (within reason, can be refused)', 100],
    ['Tacosaur', 'Your name gets added to /tacosaur.', 150],
    ['Félicette', 'Backdoor Access: Félicette! Back by popular demand!', 300]
];

var shopDisplay = getShopDisplay(shop);

module.exports = {
    atm: 'wallet',
    purse: 'wallet',
    wallet: function(target, room, user) {
        if (!this.canBroadcast()) return;
        if (!target) target = user.name;
        Economy.get(target).then(function(amount) {
            this.sendReplyBox(Tools.escapeHTML(target) + ' has ' + amount + Economy.currency(amount) + '.');
            room.update();
        }.bind(this));
    },

    givebuck: 'givemoney',
    givebucks: 'givemoney',
    givemoney: function(target, room, user) {
        if (!user.can('givemoney')) return this.sendReply('/givemoney - Access denied.');
        if (!target || target.indexOf(',') < 0) {
            return this.sendReply('/givemoney [user], [amount] - Give a user a certain amount of money.');
        }

        var parts = target.split(',');
        this.splitTarget(parts[0]);
        var amount = Number(parts[1].trim());
        var currency = amount + Economy.currency(amount);

        if (!this.targetUser) return this.sendReply('User ' + this.targetUsername + ' not found.');
        if (isNaN(parts[1])) return this.sendReply('Must be a number.');
        if (String(parts[1]).indexOf('.') >= 0) return this.sendReply('Cannot contain a decimal.');
        if (amount < 1) return this.sendReply('You can\'t give less than one' + Economy.currency(amount));

        Economy.give(this.targetUsername, amount).then(function(total) {
            this.sendReply(this.targetUsername + ' was given ' + currency  + '. This user now has ' + total + Economy.currency(total) + '.');
            Users.get(this.targetUsername).connections[0].sendTo(room.id, user.name + ' has given you ' + currency + '. You now have ' + total + Economy.currency(total) + '.');
        }.bind(this));
    },

    takebuck: 'takemoney',
    takebucks: 'takemoney',
    takemoney: function(target, room, user) {
        if (!user.can('takemoney')) return this.sendReply('/takemoney - Access denied.');
        if (!target || target.indexOf(',') < 0) {
            return this.sendReply('/takemoney [user], [amount] - Take a certain amount of money from a user.');
        }

        var parts = target.split(',');
        this.splitTarget(parts[0]);
        var amount = Number(parts[1].trim());
        var currency = amount + Economy.currency(amount);

        if (!this.targetUser) return this.sendReply('User ' + this.targetUsername + ' not found.');
        if (isNaN(parts[1])) return this.sendReply('Must be a number.');
        if (String(parts[1]).indexOf('.') >= 0) return this.sendReply('Cannot contain a decimal.');
        if (amount < 1) return this.sendReply('You can\'t give less than one' + Economy.currency(amount));

        Economy.take(this.targetUsername, amount).then(function(total) {
            this.sendReply(this.targetUsername + ' losted ' + currency + '. This user now has ' + total + Economy.currency(total) + '.');
            Users.get(this.targetUsername).send(user.name + ' has taken ' + currency + ' from you. You now have ' + total + Economy.currency(total) + '.');
        }.bind(this));
    },

    transfer: 'transfermoney',
    transferbuck: 'transfermoney',
    transferbucks: 'transfermoney',
    transfermoney: function(target, room, user) {
        if (!target || target.indexOf(',') < 0) {
            return this.sendReply('/transfer [user], [amount] - Transfer a certain amount of money to a user.');
        }

        var parts = target.split(',');
        var amount = Number(parts[1].trim());
        var targetName = parts[0];
        var currency = amount + Economy.currency(amount);

        if (toId(targetName) === user.userid) return this.sendReply('You cannot transfer to yourself.');
        if (isNaN(parts[1])) return this.sendReply('Must be a number.');
        if (String(parts[1]).indexOf('.') >= 0) return this.sendReply('Cannot contain a decimal.');
        if (amount < 1) return this.sendReply('You can\'t give less than one' + Economy.currency(amount));

        var self = this;
        Economy.get(user.name)
            .then(function(money) {
                if (amount > money) return self.sendReply('You cannot transfer more money than what you have.');
                return [Economy.give(targetName, amount), Economy.take(user.name, amount)];
            })
            .spread(function(targetTotal, userTotal) {
                self.sendReply('You have successfully transferred ' + currency + '. You now have ' + userTotal + Economy.currency(userTotal) + '.');
                if (Users.get(targetName)) {
                    Users.get(targetName).connections[0].sendTo(room.id, user.name + ' has transferred ' + currency + '. You now have ' + targetTotal + Economy.currency(targetTotal) + '.');
                }
            }, function(err) {
                if (err) console.error(err);
            }).done();
    },

    shop: function(target, room, user) {
       if (!this.canBroadcast()) return;
       return this.sendReply('|raw|' + shopDisplay);
    },

    buy: function(target, room, user) {
        if (!target) return this.sendReply('/buy [command] - Buys an item from the shop.');
        var self = this;
        Economy.get(user.name).then(function(money) {
            var cost = findItem.call(self, target, money);
            if (!cost) return room.update();

            Economy.take(user.name, cost).then(function(total) {
                self.sendReply('You have bought ' + target + ' for ' + cost +
                    Economy.currency(cost) + '. You now have ' + total +
                    Economy.currency(total) + ' left.');
                room.addRaw(user.name + ' has bought ' + target + ' from the shop.');
                handleBoughtItem.call(self, target.toLowerCase(), user);
                room.update();
            });
        });
    },

    customsymbol: function(target, room, user) {
        if (!user.canCustomSymbol) return this.sendReply('You need to buy this item from the shop.');
        if (!target || target.length > 1) return this.sendReply('/customsymbol [symbol] - Get a custom symbol.');
        if (target.match(/[A-Za-z\d]+/g) || '?!+%@\u2605&~#'.indexOf(target) >= 0) return this.sendReply('Sorry, but you cannot change your symbol to this for safety/stability reasons.');
        user.customSymbol = target;
        user.updateIdentity();
        user.canCustomSymbol = false;
        user.hasCustomSymbol = true;
    },

    resetcustomsymbol: 'resetsymbol',
    resetsymbol: function(target, room, user) {
        if (!user.hasCustomSymbol) return this.sendReply('You don\'t have a custom symbol.');
        user.customSymbol = null;
        user.updateIdentity();
        user.hasCustomSymbol = false;
        this.sendReply('Your symbol has been reset.');
    },

    moneyladder: 'richestuser',
    richladder: 'richestuser',
    richestusers: 'richestuser',
    richestuser: function(target, room) {
        if (!this.canBroadcast()) return;
        var self = this;
        var display = 'Richest Users
\

\

\

\
                       Rank	\
                       Username	\
                       Money	\

';
        User
            .find()
            .sort({money: -1})
            .limit(10)
            .exec(function(err, users) {
                if (err) return;
                users.forEach(function(user, index) {
                    display += '
\
                                    ' + (index + 1) + '	\
                                    ' + user.name + '	\
                                    ' + user.money + '	\

';
                });
                display += '

';
                self.sendReply('|raw|' + display);
                room.update();
            });
    },

    resetbuck: 'resetmoney',
    resetbucks: 'resetmoney',
    resetmoney: function(target, room, user) {
        if (!user.can('resetmoney')) return this.sendReply('/resetmoney - Access denied.');
        var self = this;
        User.findOne({name: toId(target)}, function(err, user) {
            if (err) throw err;
            if (!user) {
                self.sendReply(target + ' already has 0 bucks.');
                return room.update();
            }
            user.money = 0;
            user.save(function(err) {
                if (err) throw err;
                self.sendReply(target + ' now has 0 bucks.');
                room.update();
            });
        });
    },

    registershop: function (target, room, user) {
    	if (!user.can('takemoney')) return this.sendReply('/registershop - Access Denied you silly goose!');
    	if (!target) return this.sendReply('Please specify a room you silly goose!');
    	if (!Rooms(toId(target))) return this.sendReply('That\'s not a real room you silly goose!');
    	var targetRoom = Rooms(toId(target));
    	targetRoom.add('|raw|
'+user.name+' has just purchased a league shop for this room.
');
	 				targetRoom.update();
	 				targetRoom.shop = new Object();
	 				targetRoom.shopList = new Array();
					targetRoom.chatRoomData.shop = targetRoom.shop;
					targetRoom.chatRoomData.shopList = targetRoom.shopList;
					Rooms.global.writeChatRoomData();
    },

    shopdeclare: function (target, room, user) {
        if (!user.canShopDeclare) return this.sendReply('You need to buy this item from the shop to use.');
        if (!target) return this.sendReply('/shopdeclare [message] - Send message to all rooms.');

        for (var id in Rooms.rooms) {
            if (id !== 'global') {
                Rooms.rooms[id].addRaw('
' + target + '
');
            }
        }
        this.logModCommand(user.name + " globally declared " + target);
        user.canShopDeclare = false;
    },

    shoppm: function (target, room, user) {
        if (!user.canShopPM) return this.sendReply('You need to buy this item from the shop to use.');
        if (!target) return this.sendReply('/shoppm [message] - PM all users in the server.');
        if (target.indexOf('/html') >= 0) return this.sendReply('Cannot contain /html.');

        var pmName = '~Global PM from ' + user.name +' [Do not reply]';

        for (var name in Users.users) {
            var message = '|pm|' + pmName + '|' + Users.users[name].getIdentity() + '|' + target;
            Users.users[name].send(message);
        }
        user.canShopPM = false;
    }
};

/**
 * Displays the shop
 *
 * @param {Array} shop
 * @return {String} display
 */

function getShopDisplay(shop) {
    var display = '
\

\

\
                            Command	\
                            Description	\
                            Cost	\

';
    var start = 0;
    while (start < shop.length) {
        display += '
\
                        <button name="send" value="/buy ' + shop[start][0] + '">' + shop[start][0] + '</button>' + '	\
                        ' + shop[start][1] + '	\
                        ' + shop[start][2] + '	\

';
        start++;
    }
    display += '

To buy an item from the shop, use /buy command.';
    return display;
}

/**
 * Find the item in the shop.
 *
 * @param {String} item
 * @param {Number} money
 * @return {Object}
 */

function findItem(item, money) {
    var len = shop.length;
    var price = 0;
    var amount = 0;
    while(len--) {
        if (item.toLowerCase() !== shop[len][0].toLowerCase()) continue;
        price = shop[len][2];
        if (price > money) {
            amount = price - money;
            this.sendReply('You don\'t have you enough money for this. You need ' + amount + Economy.currency(amount) + ' more to buy ' + item + '.');
            return false;
        }
        return price;
    }
    this.sendReply(item + ' not found in shop.');
}

/**
 * Handling the bought item from the shop.
 *
 * @param {String} item
 * @param {Object} user
 */

function handleBoughtItem(item, user) {
    if (item === 'symbol') {
        user.canCustomSymbol = true;
        this.sendReply('You have purchased a custom symbol. You can use /customsymbol to get your custom symbol.');
        this.sendReply('You will have this until you log off for more than an hour.');
        this.sendReply('If you do not want your custom symbol anymore, you may use /resetsymbol to go back to your old symbol.');
   } else if (item === 'declare') {
        user.canShopDeclare = true;
        this.sendReply('You have purchased a declare. You can use /shopdeclare to declare your message.');
   } else if (item === 'pm') {
        user.canShopPM = true;
        this.sendReply('You have purchased a pm. You can use /shoppm to declare your message.');
   } else {
        var msg = user.name + ' has bought ' + item + '.';
        for (var i in Users.users) {
            if (Users.users[i].group === '~') {
                Users.users[i].send('|pm|~Shop Alert|' + Users.users[i].getIdentity() + '|' + msg);
            }
        }
   }
}
<commit_msg>Grammar Error<commit_after>var Q = require('q');
var Economy = require('../economy');
var User = require('../mongo').userModel;
var fs = require('fs');

var shop = [
    ['Symbol', 'Buys a custom symbol to go infront of name and puts you at top of userlist. (Temporary until restart, certain symbols are blocked)', 5],
    ['Fix', 'Buys the ability to alter your current custom avatar or trainer card. (don\'t buy if you have neither)', 10],
    ['PM', 'Send a message to everyone on the server. [Can be refused] (Everyone on the server will receive a message from "~Server PM - [Do not reply] Uses: League Advertisements, Celebrations, ETC', 20],
    ['Avatar', 'Buys an custom avatar to be applied to your name (You supply. Images larger than 80x80 may not show correctly)', 50],
    ['Declare', 'Globally declare a message to the whole server! [Can be refused](A small blue message that every chatroom can see; Uses: League Advertisements, Celebrations, ETC)', 50],
    ['Trainer', 'Buys a trainer card which shows information through a command. (You supply, can be refused)', 50],
    ['Room', 'Buys a chatroom for you to own. (within reason, can be refused)', 100],
    ['Tacosaur', 'Your name gets added to /tacosaur.', 150],
    ['Félicette', 'Backdoor Access: Félicette! Back by popular demand!', 300]
];

var shopDisplay = getShopDisplay(shop);

module.exports = {
    atm: 'wallet',
    purse: 'wallet',
    wallet: function(target, room, user) {
        if (!this.canBroadcast()) return;
        if (!target) target = user.name;
        Economy.get(target).then(function(amount) {
            this.sendReplyBox(Tools.escapeHTML(target) + ' has ' + amount + Economy.currency(amount) + '.');
            room.update();
        }.bind(this));
    },

    givebuck: 'givemoney',
    givebucks: 'givemoney',
    givemoney: function(target, room, user) {
        if (!user.can('givemoney')) return this.sendReply('/givemoney - Access denied.');
        if (!target || target.indexOf(',') < 0) {
            return this.sendReply('/givemoney [user], [amount] - Give a user a certain amount of money.');
        }

        var parts = target.split(',');
        this.splitTarget(parts[0]);
        var amount = Number(parts[1].trim());
        var currency = amount + Economy.currency(amount);

        if (!this.targetUser) return this.sendReply('User ' + this.targetUsername + ' not found.');
        if (isNaN(parts[1])) return this.sendReply('Must be a number.');
        if (String(parts[1]).indexOf('.') >= 0) return this.sendReply('Cannot contain a decimal.');
        if (amount < 1) return this.sendReply('You can\'t give less than one' + Economy.currency(amount));

        Economy.give(this.targetUsername, amount).then(function(total) {
            this.sendReply(this.targetUsername + ' was given ' + currency  + '. This user now has ' + total + Economy.currency(total) + '.');
            Users.get(this.targetUsername).connections[0].sendTo(room.id, user.name + ' has given you ' + currency + '. You now have ' + total + Economy.currency(total) + '.');
        }.bind(this));
    },

    takebuck: 'takemoney',
    takebucks: 'takemoney',
    takemoney: function(target, room, user) {
        if (!user.can('takemoney')) return this.sendReply('/takemoney - Access denied.');
        if (!target || target.indexOf(',') < 0) {
            return this.sendReply('/takemoney [user], [amount] - Take a certain amount of money from a user.');
        }

        var parts = target.split(',');
        this.splitTarget(parts[0]);
        var amount = Number(parts[1].trim());
        var currency = amount + Economy.currency(amount);

        if (!this.targetUser) return this.sendReply('User ' + this.targetUsername + ' not found.');
        if (isNaN(parts[1])) return this.sendReply('Must be a number.');
        if (String(parts[1]).indexOf('.') >= 0) return this.sendReply('Cannot contain a decimal.');
        if (amount < 1) return this.sendReply('You can\'t give less than one' + Economy.currency(amount));

        Economy.take(this.targetUsername, amount).then(function(total) {
            this.sendReply(this.targetUsername + ' losted ' + currency + '. This user now has ' + total + Economy.currency(total) + '.');
            Users.get(this.targetUsername).send(user.name + ' has taken ' + currency + ' from you. You now have ' + total + Economy.currency(total) + '.');
        }.bind(this));
    },

    transfer: 'transfermoney',
    transferbuck: 'transfermoney',
    transferbucks: 'transfermoney',
    transfermoney: function(target, room, user) {
        if (!target || target.indexOf(',') < 0) {
            return this.sendReply('/transfer [user], [amount] - Transfer a certain amount of money to a user.');
        }

        var parts = target.split(',');
        var amount = Number(parts[1].trim());
        var targetName = parts[0];
        var currency = amount + Economy.currency(amount);

        if (toId(targetName) === user.userid) return this.sendReply('You cannot transfer to yourself.');
        if (isNaN(parts[1])) return this.sendReply('Must be a number.');
        if (String(parts[1]).indexOf('.') >= 0) return this.sendReply('Cannot contain a decimal.');
        if (amount < 1) return this.sendReply('You can\'t give less than one' + Economy.currency(amount));

        var self = this;
        Economy.get(user.name)
            .then(function(money) {
                if (amount > money) return self.sendReply('You cannot transfer more money than what you have.');
                return [Economy.give(targetName, amount), Economy.take(user.name, amount)];
            })
            .spread(function(targetTotal, userTotal) {
                self.sendReply('You have successfully transferred ' + currency + '. You now have ' + userTotal + Economy.currency(userTotal) + '.');
                if (Users.get(targetName)) {
                    Users.get(targetName).connections[0].sendTo(room.id, user.name + ' has transferred ' + currency + '. You now have ' + targetTotal + Economy.currency(targetTotal) + '.');
                }
            }, function(err) {
                if (err) console.error(err);
            }).done();
    },

    shop: function(target, room, user) {
       if (!this.canBroadcast()) return;
       return this.sendReply('|raw|' + shopDisplay);
    },

    buy: function(target, room, user) {
        if (!target) return this.sendReply('/buy [command] - Buys an item from the shop.');
        var self = this;
        Economy.get(user.name).then(function(money) {
            var cost = findItem.call(self, target, money);
            if (!cost) return room.update();

            Economy.take(user.name, cost).then(function(total) {
                self.sendReply('You have bought ' + target + ' for ' + cost +
                    Economy.currency(cost) + '. You now have ' + total +
                    Economy.currency(total) + ' left.');
                room.addRaw(user.name + ' has bought ' + target + ' from the shop.');
                handleBoughtItem.call(self, target.toLowerCase(), user);
                room.update();
            });
        });
    },

    customsymbol: function(target, room, user) {
        if (!user.canCustomSymbol) return this.sendReply('You need to buy this item from the shop.');
        if (!target || target.length > 1) return this.sendReply('/customsymbol [symbol] - Get a custom symbol.');
        if (target.match(/[A-Za-z\d]+/g) || '?!+%@\u2605&~#'.indexOf(target) >= 0) return this.sendReply('Sorry, but you cannot change your symbol to this for safety/stability reasons.');
        user.customSymbol = target;
        user.updateIdentity();
        user.canCustomSymbol = false;
        user.hasCustomSymbol = true;
    },

    resetcustomsymbol: 'resetsymbol',
    resetsymbol: function(target, room, user) {
        if (!user.hasCustomSymbol) return this.sendReply('You don\'t have a custom symbol.');
        user.customSymbol = null;
        user.updateIdentity();
        user.hasCustomSymbol = false;
        this.sendReply('Your symbol has been reset.');
    },

    moneyladder: 'richestuser',
    richladder: 'richestuser',
    richestusers: 'richestuser',
    richestuser: function(target, room) {
        if (!this.canBroadcast()) return;
        var self = this;
        var display = 'Richest Users
\

\

\

\
                       Rank	\
                       Username	\
                       Money	\

';
        User
            .find()
            .sort({money: -1})
            .limit(10)
            .exec(function(err, users) {
                if (err) return;
                users.forEach(function(user, index) {
                    display += '
\
                                    ' + (index + 1) + '	\
                                    ' + user.name + '	\
                                    ' + user.money + '	\

';
                });
                display += '

';
                self.sendReply('|raw|' + display);
                room.update();
            });
    },

    resetbuck: 'resetmoney',
    resetbucks: 'resetmoney',
    resetmoney: function(target, room, user) {
        if (!user.can('resetmoney')) return this.sendReply('/resetmoney - Access denied.');
        var self = this;
        User.findOne({name: toId(target)}, function(err, user) {
            if (err) throw err;
            if (!user) {
                self.sendReply(target + ' already has 0 bucks.');
                return room.update();
            }
            user.money = 0;
            user.save(function(err) {
                if (err) throw err;
                self.sendReply(target + ' now has 0 bucks.');
                room.update();
            });
        });
    },

    registershop: function (target, room, user) {
    	if (!user.can('takemoney')) return this.sendReply('/registershop - Access Denied you silly goose!');
    	if (!target) return this.sendReply('Please specify a room you silly goose!');
    	if (!Rooms(toId(target))) return this.sendReply('That\'s not a real room you silly goose!');
    	var targetRoom = Rooms(toId(target));
    	targetRoom.add('|raw|
'+user.name+' has just added a league shop to this room.
');
	 				targetRoom.update();
	 				targetRoom.shop = new Object();
	 				targetRoom.shopList = new Array();
					targetRoom.chatRoomData.shop = targetRoom.shop;
					targetRoom.chatRoomData.shopList = targetRoom.shopList;
					Rooms.global.writeChatRoomData();
    },

    shopdeclare: function (target, room, user) {
        if (!user.canShopDeclare) return this.sendReply('You need to buy this item from the shop to use.');
        if (!target) return this.sendReply('/shopdeclare [message] - Send message to all rooms.');

        for (var id in Rooms.rooms) {
            if (id !== 'global') {
                Rooms.rooms[id].addRaw('
' + target + '
');
            }
        }
        this.logModCommand(user.name + " globally declared " + target);
        user.canShopDeclare = false;
    },

    shoppm: function (target, room, user) {
        if (!user.canShopPM) return this.sendReply('You need to buy this item from the shop to use.');
        if (!target) return this.sendReply('/shoppm [message] - PM all users in the server.');
        if (target.indexOf('/html') >= 0) return this.sendReply('Cannot contain /html.');

        var pmName = '~Global PM from ' + user.name +' [Do not reply]';

        for (var name in Users.users) {
            var message = '|pm|' + pmName + '|' + Users.users[name].getIdentity() + '|' + target;
            Users.users[name].send(message);
        }
        user.canShopPM = false;
    }
};

/**
 * Displays the shop
 *
 * @param {Array} shop
 * @return {String} display
 */

function getShopDisplay(shop) {
    var display = '
\

\

\
                            Command	\
                            Description	\
                            Cost	\

';
    var start = 0;
    while (start < shop.length) {
        display += '
\
                        <button name="send" value="/buy ' + shop[start][0] + '">' + shop[start][0] + '</button>' + '	\
                        ' + shop[start][1] + '	\
                        ' + shop[start][2] + '	\

';
        start++;
    }
    display += '

To buy an item from the shop, use /buy command.';
    return display;
}

/**
 * Find the item in the shop.
 *
 * @param {String} item
 * @param {Number} money
 * @return {Object}
 */

function findItem(item, money) {
    var len = shop.length;
    var price = 0;
    var amount = 0;
    while(len--) {
        if (item.toLowerCase() !== shop[len][0].toLowerCase()) continue;
        price = shop[len][2];
        if (price > money) {
            amount = price - money;
            this.sendReply('You don\'t have you enough money for this. You need ' + amount + Economy.currency(amount) + ' more to buy ' + item + '.');
            return false;
        }
        return price;
    }
    this.sendReply(item + ' not found in shop.');
}

/**
 * Handling the bought item from the shop.
 *
 * @param {String} item
 * @param {Object} user
 */

function handleBoughtItem(item, user) {
    if (item === 'symbol') {
        user.canCustomSymbol = true;
        this.sendReply('You have purchased a custom symbol. You can use /customsymbol to get your custom symbol.');
        this.sendReply('You will have this until you log off for more than an hour.');
        this.sendReply('If you do not want your custom symbol anymore, you may use /resetsymbol to go back to your old symbol.');
   } else if (item === 'declare') {
        user.canShopDeclare = true;
        this.sendReply('You have purchased a declare. You can use /shopdeclare to declare your message.');
   } else if (item === 'pm') {
        user.canShopPM = true;
        this.sendReply('You have purchased a pm. You can use /shoppm to declare your message.');
   } else {
        var msg = user.name + ' has bought ' + item + '.';
        for (var i in Users.users) {
            if (Users.users[i].group === '~') {
                Users.users[i].send('|pm|~Shop Alert|' + Users.users[i].getIdentity() + '|' + msg);
            }
        }
   }
}
<|endoftext|>


<commit_before>'use strict';

describe('MwListCollectionFilter', function() {
  var MwListCollectionFilter,
    filterInLocalStorage;

  beforeEach(module('mwCollection'));

  beforeEach(module(function($provide) {
    var LocalForage = {
      getItem: function(identifier) {
        return {
          then: function() {
            return filterInLocalStorage;
          }
        };
      }
    };
    $provide.value('LocalForage', LocalForage);

    function MCAPFilterHolder() {};
    MCAPFilterHolder.prototype.get = function fn() {
    };
    $provide.value('MCAPFilterHolder', MCAPFilterHolder);

    function MCAPFilterHolders(irrelevant, type) {
      this.type = type;
    };
    $provide.value('MCAPFilterHolders', MCAPFilterHolders);
  }));

  beforeEach(inject(function(_MwListCollectionFilter_) {
    MwListCollectionFilter = _MwListCollectionFilter_;
  }));

  describe('fetching applied filters', function() {
    it('returns null if no applied filter is in localstorage', function() {
      filterInLocalStorage = null;

      var appliedFilter = new MwListCollectionFilter('IRRELEVANT').fetchAppliedFilter();

      expect(appliedFilter).toBeNull();
    });

    it('returns filter in localstorage if present', function() {
      filterInLocalStorage = '{"content":"IRRELEVANT"}';

      var appliedFilter = new MwListCollectionFilter('IRRELEVANT').fetchAppliedFilter();

      expect(appliedFilter).not.toBeNull();
    });
  });

});<commit_msg>MDM-7712: specify test to fix bug<commit_after>'use strict';

describe('MwListCollectionFilter', function() {
  var MwListCollectionFilter,
    filterInLocalStorage,
    currentUserUuid;

  beforeEach(module('mwCollection'));

  beforeEach(module(function($provide) {
    var LocalForage = {
      getItem: function(identifier) {
        return {
          then: function() {
            return filterInLocalStorage;
          }
        };
      }
    };
    $provide.value('LocalForage', LocalForage);

    function MCAPFilterHolder() {};
    MCAPFilterHolder.prototype.get = function() {
    };
    $provide.value('MCAPFilterHolder', MCAPFilterHolder);

    function MCAPFilterHolders(irrelevant, type) {
      this.type = type;
    };
    $provide.value('MCAPFilterHolders', MCAPFilterHolders);

    function MCAPauthenticatedUser() {};
    MCAPauthenticatedUser.prototype.get = function() {
      return currentUserUuid;
    };
    $provide.value('MCAPauthenticatedUser', MCAPauthenticatedUser);
  }));

  beforeEach(inject(function(_MwListCollectionFilter_) {
    MwListCollectionFilter = _MwListCollectionFilter_;
  }));

  describe('fetching applied filters', function() {
    it('returns null if no applied filter is in localstorage', function() {
      filterInLocalStorage = null;

      var appliedFilter = new MwListCollectionFilter('IRRELEVANT').fetchAppliedFilter();

      expect(appliedFilter).toBeNull();
    });

    it('returns filter in localstorage if present', function() {
      filterInLocalStorage = '{"content":"IRRELEVANT"}';

      var appliedFilter = new MwListCollectionFilter('IRRELEVANT').fetchAppliedFilter();

      expect(appliedFilter).not.toBeNull();
    });

    xit('returns null if filter in localstorage does not match current users id', function() {
      currentUserUuid = 'DFD04C8B-519A-4D0A-BE60-F47EB4D563E8';
      filterInLocalStorage = '{"content":"IRRELEVANT", "172FB965-64B2-4B6A-BF8C-679B02460B7B"}';

      var appliedFilter = new MwListCollectionFilter('IRRELEVANT').fetchAppliedFilter();

      expect(appliedFilter).toBeNull();
    });
  });

});<|endoftext|>


<commit_before>var Error =
{
		// Generic return values
		ERRMSG_OK=0,                      // everything is fine
		ERRMSG_FAILURE=1,                     // the action failed
		ERRMSG_NO_LOGIN=2,                    // the user is not yet logged
		ERRMSG_NO_CHARACTER_SELECTED=3,     // the user needs a character
		ERRMSG_INSUFFICIENT_RIGHTS=4,         // the user is not privileged
		ERRMSG_INVALID_ARGUMENT=5,          // part of the received message was invalid
		ERRMSG_EMAIL_ALREADY_EXISTS=6,       // The Email Address already exists
		ERRMSG_ALREADY_TAKEN=7,             // name used was already taken
		ERRMSG_SERVER_FULL=8,                // the server is overloaded
		ERRMSG_TIME_OUT=9,                   // data failed to arrive in due time
		ERRMSG_LIMIT_REACHED=10,            // limit reached
		ERRMSG_ADMINISTRATIVE_LOGOFF=11       // kicked by server administrator
}<commit_msg>Enumsyntax korrigiert.<commit_after>var Error =
{
		// Generic return values
		ERRMSG_OK:0,                      // everything is fine
		ERRMSG_FAILURE:1,                     // the action failed
		ERRMSG_NO_LOGIN:2,                    // the user is not yet logged
		ERRMSG_NO_CHARACTER_SELECTED:3,     // the user needs a character
		ERRMSG_INSUFFICIENT_RIGHTS:4,         // the user is not privileged
		ERRMSG_INVALID_ARGUMENT:5,          // part of the received message was invalid
		ERRMSG_EMAIL_ALREADY_EXISTS:6,       // The Email Address already exists
		ERRMSG_ALREADY_TAKEN:7,             // name used was already taken
		ERRMSG_SERVER_FULL:8,                // the server is overloaded
		ERRMSG_TIME_OUT:9,                   // data failed to arrive in due time
		ERRMSG_LIMIT_REACHED:10,            // limit reached
		ERRMSG_ADMINISTRATIVE_LOGOFF:11       // kicked by server administrator
}<|endoftext|>


<commit_before>var stephanie=[]
var xander = []
var maps = {}
var fullClient = retinaSDK.FullClient("9d562520-d285-11e5-8378-4dad29be0fab")
var liteClient = retinaSDK.LiteClient("9d562520-d285-11e5-8378-4dad29be0fab")
$(document).ready(function(){
  getInfo()
  window.setTimeout(compare, 1000)

})

var reallyGetInfo = getInfo()

function getInfo(){
    getStephanieFacebook()
    getXanderFacebook()
    getXanderLinkedIn()
    getStephanieLinkedIn()
    getSMHTwitter()
    getXTwitter()
  }

function appendImg(img){
  $("#results").append( "")
}

function getSMHTwitter(){
  $.get("scraped/amuttican.json", function(response){
    response["results"]["collection1"].map( tweet => stephanie.push(tweet["twitter"]))
    return true
  })
}

function getXTwitter(){
  $.get("scraped/XPSON.json", function(response){
    response["results"]["collection1"].map( tweet => xander.push(tweet["twitter"]) )
    return true
  })
}

function compare(){
  getXPmap()
  getSMHmap()
  compareBulk()
  // $.get("scraped/XPSON.json", function(response){
    // response["results"]["collection1"].map( tweet => xander.push(tweet["twitter"]))
    fullClient.compareImage({expressions: [{"text": stephanie.join(" ")}, {"text": xander.join(" ")}]}, function(img){
      maps.comparison = img
    })
  // })
}

function getStephanieFacebook(){
  $.get("scraped/smhfb.json", function(response){
    addFBData(response, stephanie)
    return true
  })

}
function getXanderFacebook(){
  $.ajax({url: "scraped/xpFB.json"})
  .done(function(response){addFBData(response, xander)})
    return true
}
function getXanderLinkedIn(){
  $.ajax({url: "xpLN.json"})
  .done(function(response){
    addLNData(response, xander)
    return true
  })
}
function getStephanieLinkedIn(){
  $.ajax({url: "scraped/smhLN.json"})
  .done(function(response){
    addLNData(response, stephanie)
    return true
  })
}

function log(response){
  console.log(response)

}
function addLNData(lndata, person) {
  person.push(lndata.summary)
  // console.log(lndata.threeCurrentPositions.values)
  lndata.threePastPositions.values.map(job => person.push(job.summary))
  lndata.volunteer.volunteerExperiences.values.map(job => person.push(job.role))
  try {lndata.threeCurrentPositions.values.map(job => person.push(job.summary))}
  catch (e){}
  // console.log(person)
}

function addFBData(fbdata, person) {
  // console.log(fbdata)
  var person = person
  fbdata.likes.data.map( like => person.push(like.name))
  person.push(fbdata.about)
  fbdata.feed.data.map( post => post.message ? person.push(post.message) : person )
  fbdata.books.data.map( book => person.push(book.name))

  fbdata.music.data.map( artist => person.push( artist.name ))

}

function getXPmap(){
  fullClient.getImage({expression: {"text": xander.join()}}, addToMapsX)
}

function getSMHmap(){
  fullClient.getImage({expression: {"text": stephanie.join()}}, addToMapsS)
}

function addToMapsX(img){
    maps.xander = img
}
function addToMapsS(img){
    maps.stephanie = img
}

function compareBulk(){
  c1=[]
  c2=[]
  // xander.map(text => c1.push({"text": text}))
  // stephanie.map(text => c2.push({"text": text}))
  fullClient.getKeywordsForText({"text": xander.join(" ")}, function(response){
    response.map( term => c1.push({"term": term}))
    fullClient.getKeywordsForText({"text": stephanie.join(" ")}, function(response){
      response.map( term => c2.push({"term": term}))
      console.log(c1)
      console.log(c2)
      addAllImgs();
    })
  })
}

function addAllImgs(){
  appendImg(maps.xander)
  appendImg(maps.stephanie)
  appendImg(maps.comparison)
}

<commit_msg>rename maps to dataobj<commit_after>var stephanie=[]
var xander = []
var dataObj = {}
var fullClient = retinaSDK.FullClient("9d562520-d285-11e5-8378-4dad29be0fab")
var liteClient = retinaSDK.LiteClient("9d562520-d285-11e5-8378-4dad29be0fab")
$(document).ready(function(){
  getInfo()
  window.setTimeout(compare, 1000)

})

var reallyGetInfo = getInfo()

function getInfo(){
    getStephanieFacebook()
    getXanderFacebook()
    getXanderLinkedIn()
    getStephanieLinkedIn()
    getSMHTwitter()
    getXTwitter()
  }

function appendImg(img){
  $("#results").append( "")
}

function getSMHTwitter(){
  $.get("scraped/amuttican.json", function(response){
    response["results"]["collection1"].map( tweet => stephanie.push(tweet["twitter"]))
    return true
  })
}

function getXTwitter(){
  $.get("scraped/XPSON.json", function(response){
    response["results"]["collection1"].map( tweet => xander.push(tweet["twitter"]) )
    return true
  })
}

function compare(){
  getXPmap()
  getSMHmap()
  compareBulk()
  // $.get("scraped/XPSON.json", function(response){
    // response["results"]["collection1"].map( tweet => xander.push(tweet["twitter"]))
    fullClient.compareImage({expressions: [{"text": stephanie.join(" ")}, {"text": xander.join(" ")}]}, function(img){
      dataObj.comparison = img
    })
  // })
}

function getStephanieFacebook(){
  $.get("scraped/smhfb.json", function(response){
    addFBData(response, stephanie)
    return true
  })

}
function getXanderFacebook(){
  $.ajax({url: "scraped/xpFB.json"})
  .done(function(response){addFBData(response, xander)})
    return true
}
function getXanderLinkedIn(){
  $.ajax({url: "xpLN.json"})
  .done(function(response){
    addLNData(response, xander)
    return true
  })
}
function getStephanieLinkedIn(){
  $.ajax({url: "scraped/smhLN.json"})
  .done(function(response){
    addLNData(response, stephanie)
    return true
  })
}

function log(response){
  console.log(response)

}
function addLNData(lndata, person) {
  person.push(lndata.summary)
  // console.log(lndata.threeCurrentPositions.values)
  lndata.threePastPositions.values.map(job => person.push(job.summary))
  lndata.volunteer.volunteerExperiences.values.map(job => person.push(job.role))
  try {lndata.threeCurrentPositions.values.map(job => person.push(job.summary))}
  catch (e){}
  // console.log(person)
}

function addFBData(fbdata, person) {
  // console.log(fbdata)
  var person = person
  fbdata.likes.data.map( like => person.push(like.name))
  person.push(fbdata.about)
  fbdata.feed.data.map( post => post.message ? person.push(post.message) : person )
  fbdata.books.data.map( book => person.push(book.name))

  fbdata.music.data.map( artist => person.push( artist.name ))

}

function getXPmap(){
  fullClient.getImage({expression: {"text": xander.join()}}, addToMapsX)
}

function getSMHmap(){
  fullClient.getImage({expression: {"text": stephanie.join()}}, addToMapsS)
}

function addToMapsX(img){
    dataObj.xander = img
}
function addToMapsS(img){
    dataObj.stephanie = img
}

function compareBulk(){
  c1=[]
  c2=[]
  // xander.map(text => c1.push({"text": text}))
  // stephanie.map(text => c2.push({"text": text}))
  fullClient.getKeywordsForText({"text": xander.join(" ")}, function(response){
    response.map( term => c1.push({"term": term}))
    fullClient.getKeywordsForText({"text": stephanie.join(" ")}, function(response){
      response.map( term => c2.push({"term": term}))
      console.log(c1)
      console.log(c2)
      addAllImgs();
    })
  })
}

function addAllImgs(){
  appendImg(dataObj.xander)
  appendImg(dataObj.stephanie)
  appendImg(dataObj.comparison)
}

<|endoftext|>