<commit_before>var Timer = require('../../stats/timer');
var GeojsonSqlWrapper = require('./geojson_sql_wrapper');
var queue = require('queue-async');
var _ = require('underscore');
var geojsonUtils = require('../../utils/geojson_utils');

function GeojsonRenderer(cartoPSQL, layers, options) {
    this.cartoPSQL = cartoPSQL;
    this.layers = layers;
    this.options = options;
}

module.exports = GeojsonRenderer;

GeojsonRenderer.prototype.getTile = function(z, x, y, callback) {
    var self = this;

    var timer = new Timer();
    timer.start('render');

    var rendererGetTileQueue = queue(this.layers.length);

    this.layers.forEach(function(layer) {
        if (layer.type === 'mapnik' || layer.type === 'cartodb') {
            var coord = {x: x, y: y};
            rendererGetTileQueue.defer(self._getTileData.bind(self), self.cartoPSQL, coord, z, layer);
        }
    });

    rendererGetTileQueue.awaitAll(function (err, result) {
        timer.end('render');
        if (err) {
            return callback(err);
        }

        var stats = _.extend(timer.getTimes(), {
            'render-details': _.pluck(result, 'stats')
        });

        var geoJsonTiles = self._formatTileResponse(result);

        // FIXME: response's header shouldn't be here. it must be at server level
        callback(null, geoJsonTiles, { 'Content-Type': 'application/json' } , stats);
    });
};

GeojsonRenderer.prototype._formatTileResponse = function (result) {
    if (result.length === 1) {
        return result[0].data;
    }

    return {
        type: 'FeatureCollection',
        features: _.pluck(result, 'data')
    };
};

GeojsonRenderer.prototype._getTileData = function(cartoPSQL, coord, zoom, layer, callback) {
    var self = this;

    var BUFFER_SIZE = 16;

    if (typeof self.options['buffer-size'] === 'number'){
        BUFFER_SIZE = self.options['buffer-size'];
    }

    var query = self._composeGeojsonQuery({
        coord: coord,
        zoom: zoom,
        layerSql: layer.options.sql,
        geomColumn: layer.options.geom_column || 'the_geom_webmercator',
        clipByBox2d: this.options.clipByBox2d,
        columns: geojsonUtils.getGeojsonProperties(layer.options),
        bufferSize: BUFFER_SIZE
    });

    self._queryGeojson(cartoPSQL, query, function (err, result) {
        if (err) {
            return callback(err);
        }

        callback(null, {
            data: result.data,
            stats: result.stats
        });
    });
};

GeojsonRenderer.prototype._composeGeojsonQuery = function (queryContext) {
    return new GeojsonSqlWrapper().wrap(queryContext);
};

GeojsonRenderer.prototype._queryGeojson = function (cartoPSQL, query, callback) {
    var self = this;

    this._measureSQLQuery(cartoPSQL, query, 'geojson', function (err, result) {
        if (err) {
            return callback(err);
        }

        callback(null, {
            data: self._formatGeoJSONData(result.data),
            stats: result.stats
        });
    });
};

GeojsonRenderer.prototype._measureSQLQuery = function (cartoPSQL, query, name, callback) {
    var timer = new Timer();
    var timerKey = 'query-' + name;

    timer.start(timerKey);
    cartoPSQL.query(query, function (err, data) {
        timer.end(timerKey);
        if (err) {
            return callback(err);
        }

        callback(null, {
            data: data,
            stats: timer.getTimes()
        });
    }, true);
};

GeojsonRenderer.prototype._formatGeoJSONData = function (data) {
    if (data && data.rows && data.rows[0] && data.rows[0].geojson && !data.rows[0].geojson.features) {
        data.rows[0].geojson.features = [];
    }

    return data.rows[0].geojson;
};
<commit_msg>Passed the right clipping function to geojson's query<commit_after>var Timer = require('../../stats/timer');
var GeojsonSqlWrapper = require('./geojson_sql_wrapper');
var queue = require('queue-async');
var _ = require('underscore');
var geojsonUtils = require('../../utils/geojson_utils');

function GeojsonRenderer(cartoPSQL, layers, options) {
    this.cartoPSQL = cartoPSQL;
    this.layers = layers;
    this.options = options;
}

module.exports = GeojsonRenderer;

GeojsonRenderer.prototype.getTile = function(z, x, y, callback) {
    var self = this;

    var timer = new Timer();
    timer.start('render');

    var rendererGetTileQueue = queue(this.layers.length);

    this.layers.forEach(function(layer) {
        if (layer.type === 'mapnik' || layer.type === 'cartodb') {
            var coord = {x: x, y: y};
            rendererGetTileQueue.defer(self._getTileData.bind(self), self.cartoPSQL, coord, z, layer);
        }
    });

    rendererGetTileQueue.awaitAll(function (err, result) {
        timer.end('render');
        if (err) {
            return callback(err);
        }

        var stats = _.extend(timer.getTimes(), {
            'render-details': _.pluck(result, 'stats')
        });

        var geoJsonTiles = self._formatTileResponse(result);

        // FIXME: response's header shouldn't be here. it must be at server level
        callback(null, geoJsonTiles, { 'Content-Type': 'application/json' } , stats);
    });
};

GeojsonRenderer.prototype._formatTileResponse = function (result) {
    if (result.length === 1) {
        return result[0].data;
    }

    return {
        type: 'FeatureCollection',
        features: _.pluck(result, 'data')
    };
};

GeojsonRenderer.prototype._getTileData = function(cartoPSQL, coord, zoom, layer, callback) {
    var self = this;

    var BUFFER_SIZE = 16;

    if (typeof self.options['buffer-size'] === 'number'){
        BUFFER_SIZE = self.options['buffer-size'];
    }

    var query = self._composeGeojsonQuery({
        coord: coord,
        zoom: zoom,
        layerSql: layer.options.sql,
        geomColumn: layer.options.geom_column || 'the_geom_webmercator',
        clipFn: this.options.clipByBox2d ? 'ST_ClipByBox2D' : 'ST_Intersection',
        columns: geojsonUtils.getGeojsonProperties(layer.options),
        bufferSize: BUFFER_SIZE
    });

    self._queryGeojson(cartoPSQL, query, function (err, result) {
        if (err) {
            return callback(err);
        }

        callback(null, {
            data: result.data,
            stats: result.stats
        });
    });
};

GeojsonRenderer.prototype._composeGeojsonQuery = function (queryContext) {
    return new GeojsonSqlWrapper().wrap(queryContext);
};

GeojsonRenderer.prototype._queryGeojson = function (cartoPSQL, query, callback) {
    var self = this;

    this._measureSQLQuery(cartoPSQL, query, 'geojson', function (err, result) {
        if (err) {
            return callback(err);
        }

        callback(null, {
            data: self._formatGeoJSONData(result.data),
            stats: result.stats
        });
    });
};

GeojsonRenderer.prototype._measureSQLQuery = function (cartoPSQL, query, name, callback) {
    var timer = new Timer();
    var timerKey = 'query-' + name;

    timer.start(timerKey);
    cartoPSQL.query(query, function (err, data) {
        timer.end(timerKey);
        if (err) {
            return callback(err);
        }

        callback(null, {
            data: data,
            stats: timer.getTimes()
        });
    }, true);
};

GeojsonRenderer.prototype._formatGeoJSONData = function (data) {
    if (data && data.rows && data.rows[0] && data.rows[0].geojson && !data.rows[0].geojson.features) {
        data.rows[0].geojson.features = [];
    }

    return data.rows[0].geojson;
};
<|endoftext|>


<commit_before>/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);<commit_msg>Update bundled jQuery.ScrollTo to version 1.4.7<commit_after>/**
 * Copyright (c) 2007-2013 Ariel Flesler - aflesler<a>gmail<d>com | http://flesler.blogspot.com
 * Licensed under MIT
 * @author Ariel Flesler
 * @version 1.4.7
 */
(function(d){function h(b){return"object"==typeof b?b:{top:b,left:b}}var n=d.scrollTo=function(b,c,a){return d(window).scrollTo(b,c,a)};n.defaults={axis:"xy",duration:1.3<=parseFloat(d.fn.jquery)?0:1,limit:!0};n.window=function(b){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){if(this.nodeName&&-1==d.inArray(this.nodeName.toLowerCase(),["iframe","#document","html","body"]))return this;var b=(this.contentWindow||this).document||this.ownerDocument||this;return/webkit/i.test(navigator.userAgent)|| "BackCompat"==b.compatMode?b.body:b.documentElement})};d.fn.scrollTo=function(b,c,a){"object"==typeof c&&(a=c,c=0);"function"==typeof a&&(a={onAfter:a});"max"==b&&(b=9E9);a=d.extend({},n.defaults,a);c=c||a.duration;a.queue=a.queue&&1<a.axis.length;a.queue&&(c/=2);a.offset=h(a.offset);a.over=h(a.over);return this._scrollable().each(function(){function q(b){k.animate(e,c,a.easing,b&&function(){b.call(this,g,a)})}if(null!=b){var l=this,k=d(l),g=b,p,e={},s=k.is("html,body");switch(typeof g){case "number":case "string":if(/^([+-]=?)?\d+(\.\d+)?(px|%)?$/.test(g)){g= h(g);break}g=d(g,this);if(!g.length)return;case "object":if(g.is||g.style)p=(g=d(g)).offset()}d.each(a.axis.split(""),function(b,d){var c="x"==d?"Left":"Top",m=c.toLowerCase(),f="scroll"+c,h=l[f],r=n.max(l,d);p?(e[f]=p[m]+(s?0:h-k.offset()[m]),a.margin&&(e[f]-=parseInt(g.css("margin"+c))||0,e[f]-=parseInt(g.css("border"+c+"Width"))||0),e[f]+=a.offset[m]||0,a.over[m]&&(e[f]+=g["x"==d?"width":"height"]()*a.over[m])):(c=g[m],e[f]=c.slice&&"%"==c.slice(-1)?parseFloat(c)/100*r:c);a.limit&&/^\d+$/.test(e[f])&& (e[f]=0>=e[f]?0:Math.min(e[f],r));!b&&a.queue&&(h!=e[f]&&q(a.onAfterFirst),delete e[f])});q(a.onAfter)}}).end()};n.max=function(b,c){var a="x"==c?"Width":"Height",h="scroll"+a;if(!d(b).is("html,body"))return b[h]-d(b)[a.toLowerCase()]();var a="client"+a,l=b.ownerDocument.documentElement,k=b.ownerDocument.body;return Math.max(l[h],k[h])-Math.min(l[a],k[a])}})(jQuery);
<|endoftext|>


<commit_before>// redisdatabank.js
//
// implementation of Databank interface using redis
//
// Copyright 2011, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var databank = require('../databank');
var redis = require('redis');

var Databank = databank.Databank;
var DatabankError = databank.DatabankError;
var AlreadyExistsError = databank.AlreadyExistsError;
var NoSuchThingError = databank.NoSuchThingError;

function RedisDatabank(params) {
    // Ignore params
    this.client = null;
    this.schema = params.schema || {};
}

RedisDatabank.prototype = new Databank();

RedisDatabank.prototype.toKey = function(type, id) {
    return type + ':' + id;
};

RedisDatabank.prototype.connect = function(params, onCompletion) {
    this.client = redis.createClient();
    this.client.on('error', function(err) {
        if (onCompletion) {
            onCompletion(new DatabankError(err));
        }
    });
    this.client.on('connect', function() {
        if (onCompletion) {
            onCompletion(null);
        }
    });
};

RedisDatabank.prototype.disconnect = function(onCompletion) {
    this.client.quit(function(err) {
        if (err) {
            onCompletion(new DatabankError());
        } else {
            onCompletion(null);
        }
    });
};

RedisDatabank.prototype.create = function(type, id, value, onCompletion) {
    this.client.setnx(this.toKey(type, id), JSON.stringify(value), function(err, result) {
        if (err) {
            onCompletion(new DatabankError(err));
        } else if (result === 0) {
            onCompletion(new AlreadyExistsError(type, id));
        } else {
            onCompletion(null, value);
        }
    });
};

RedisDatabank.prototype.read = function(type, id, onCompletion) {
    this.client.get(this.toKey(type, id), function(err, value) {
        if (err) {
            onCompletion(new DatabankError(err), null);
        } else if (value === null) {
            onCompletion(new NoSuchThingError(type, id), null);
        } else {
            onCompletion(null, JSON.parse(value));
        }
    });
};

RedisDatabank.prototype.update = function(type, id, value, onCompletion) {
    this.client.set(this.toKey(type, id), JSON.stringify(value), function(err) {
        if (err) {
            onCompletion(new DatabankError(err), null);
        } else {
            onCompletion(null, value);
        }
    });
};

RedisDatabank.prototype.del = function(type, id, onCompletion) {
    this.client.del(this.toKey(type, id), function(err, count) {
        if (err) {
            onCompletion(err);
        } else if (count === 0) {
            onCompletion(new NoSuchThingError(type, id));
        } else {
            onCompletion(null);
        }
    });
};

RedisDatabank.prototype.readAll = function(type, ids, onCompletion) {

    var keys = [],
        bank = this;

    keys = ids.map(function(id) { return bank.toKey(type, id); } );

    this.client.mget(keys, function(err, values) {
        var results = {}, i = 0, key, id, value;

        if (err) {
            onCompletion(new DatabankError(err), null);
        } else {
            for (i = 0; i < values.length; i++) {
                key = keys[i];
                id = ids[i];
                value = JSON.parse(values[i]);
                results[id] = value;
            }
            onCompletion(null, results);
        }
    });
};

RedisDatabank.prototype.search = function(type, criteria, onResult, onCompletion) {
    var bank = this;
    // FIXME: use indices to make this less horrific
    bank.client.keys(type + ':*', function(err, keys) {
        var i, cnt = 0, hadErr;
        if (err) {
            onCompletion(err);
        } else {
            for (i in keys) {
                bank.client.get(keys[i], function(err, value) {
                    if (err) {
                        hadErr = true;
                        onCompletion(err);
                    } else if (!hadErr) {
                        if (bank.matchesCriteria(value, criteria)) {
                            onResult(value);
                        }
                        cnt++;
                        if (cnt == keys.length) {
                            // last one out turn off the lights
                            onCompletion(null);
                        }
                    }
                });
            }
        }
    });
};

RedisDatabank.prototype.incr = function(type, id, onCompletion) {
    this.client.incr(this.toKey(type, id), onCompletion);
};

RedisDatabank.prototype.decr = function(type, id, onCompletion) {
    this.client.decr(this.toKey(type, id), onCompletion);
};

exports.RedisDatabank = RedisDatabank;
<commit_msg>parse results before checking against criteria in Redis driver<commit_after>// redisdatabank.js
//
// implementation of Databank interface using redis
//
// Copyright 2011, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var databank = require('../databank');
var redis = require('redis');

var Databank = databank.Databank;
var DatabankError = databank.DatabankError;
var AlreadyExistsError = databank.AlreadyExistsError;
var NoSuchThingError = databank.NoSuchThingError;

function RedisDatabank(params) {
    // Ignore params
    this.client = null;
    this.schema = params.schema || {};
}

RedisDatabank.prototype = new Databank();

RedisDatabank.prototype.toKey = function(type, id) {
    return type + ':' + id;
};

RedisDatabank.prototype.connect = function(params, onCompletion) {
    this.client = redis.createClient();
    this.client.on('error', function(err) {
        if (onCompletion) {
            onCompletion(new DatabankError(err));
        }
    });
    this.client.on('connect', function() {
        if (onCompletion) {
            onCompletion(null);
        }
    });
};

RedisDatabank.prototype.disconnect = function(onCompletion) {
    this.client.quit(function(err) {
        if (err) {
            onCompletion(new DatabankError());
        } else {
            onCompletion(null);
        }
    });
};

RedisDatabank.prototype.create = function(type, id, value, onCompletion) {
    this.client.setnx(this.toKey(type, id), JSON.stringify(value), function(err, result) {
        if (err) {
            onCompletion(new DatabankError(err));
        } else if (result === 0) {
            onCompletion(new AlreadyExistsError(type, id));
        } else {
            onCompletion(null, value);
        }
    });
};

RedisDatabank.prototype.read = function(type, id, onCompletion) {
    this.client.get(this.toKey(type, id), function(err, value) {
        if (err) {
            onCompletion(new DatabankError(err), null);
        } else if (value === null) {
            onCompletion(new NoSuchThingError(type, id), null);
        } else {
            onCompletion(null, JSON.parse(value));
        }
    });
};

RedisDatabank.prototype.update = function(type, id, value, onCompletion) {
    this.client.set(this.toKey(type, id), JSON.stringify(value), function(err) {
        if (err) {
            onCompletion(new DatabankError(err), null);
        } else {
            onCompletion(null, value);
        }
    });
};

RedisDatabank.prototype.del = function(type, id, onCompletion) {
    this.client.del(this.toKey(type, id), function(err, count) {
        if (err) {
            onCompletion(err);
        } else if (count === 0) {
            onCompletion(new NoSuchThingError(type, id));
        } else {
            onCompletion(null);
        }
    });
};

RedisDatabank.prototype.readAll = function(type, ids, onCompletion) {

    var keys = [],
        bank = this;

    keys = ids.map(function(id) { return bank.toKey(type, id); } );

    this.client.mget(keys, function(err, values) {
        var results = {}, i = 0, key, id, value;

        if (err) {
            onCompletion(new DatabankError(err), null);
        } else {
            for (i = 0; i < values.length; i++) {
                key = keys[i];
                id = ids[i];
                value = JSON.parse(values[i]);
                results[id] = value;
            }
            onCompletion(null, results);
        }
    });
};

RedisDatabank.prototype.search = function(type, criteria, onResult, onCompletion) {
    var bank = this;
    // Get every record of a given type
    // FIXME: use indices to make this less horrific
    bank.client.keys(type + ':*', function(err, keys) {
        var i, cnt = 0, hadErr;
        if (err) {
            onCompletion(err);
        } else {
            for (i in keys) {
                bank.client.get(keys[i], function(err, value) {
                    if (err) {
                        hadErr = true;
                        onCompletion(err);
                    } else if (!hadErr) {
                        value = JSON.parse(value);
                        if (bank.matchesCriteria(value, criteria)) {
                            onResult(value);
                        }
                        cnt++;
                        if (cnt == keys.length) {
                            // last one out turn off the lights
                            onCompletion(null);
                        }
                    }
                });
            }
        }
    });
};

RedisDatabank.prototype.incr = function(type, id, onCompletion) {
    this.client.incr(this.toKey(type, id), onCompletion);
};

RedisDatabank.prototype.decr = function(type, id, onCompletion) {
    this.client.decr(this.toKey(type, id), onCompletion);
};

exports.RedisDatabank = RedisDatabank;
<|endoftext|>


<commit_before>/**
 * Created by ChengFuLin on 2015/5/11.
 */
var CFGExt = require('./cfgext'),
    AnalyzedCFG = require('./analyzedcfg'),
    Scope = require('./scope');

function Graphics() {
    "use strict";
}

/**
 * Output the representation of CFGs of all function scopes with dot language format
 * @param {AnalyzedCFG} analysisItem
 * @param {Function} dotConverter
 * @returns {string} dot formatted
 */
Graphics.prototype.analysisItemToCFG = function (analysisItem, dotConverter) {
    'use strict';
    var graph = 'digraph CFG {\n' + 'node [shape="box"]';
    var converter = CFGExt.toDotWithLabelLoc;
    if (dotConverter === CFGExt.toDot ||
        dotConverter === CFGExt.toDotWithLabelId ||
        dotConverter === CFGExt.toDotWithLabelLine ||
        dotConverter === CFGExt.toDotWithLabelLoc) {
        converter = dotConverter;
    }
    if (AnalyzedCFG.isAnalyzedCFG(analysisItem)) {
        graph += '\nlabel = "';
        if (analysisItem.scopeWrappers.length === 1) {
            graph += analysisItem.scopeWrappers[0].scope.type;
            if (analysisItem.scopeWrappers[0].scope.type === Scope.FUNCTION_TYPE) {
                graph += ' ' + analysisItem.scopeWrappers[0].scope.value;
            } else if (analysisItem.scopeWrappers[0].scope.type === Scope.ANONYMOUS_FUN_TYPE) {
                graph += '[ ' + analysisItem.scopeWrappers[0].scope.value + ' ]';
            }
        }
        graph += '"\n';
    }
    graph += converter(analysisItem.cfg);
    graph += '}';
    return graph;
};

/**
 * Output the representation of Def-Use pairs
 * @param inDUpairs
 * @returns {string}
 */
Graphics.dupairs = function (inDUpairs) {
    'use strict';
    var table = 'digraph structs {\n' +
        'node [shape="plaintext"]\n' +
        'struct1 [label=<\n' +
        '
\n',
        maxSize = 0;
    inDUpairs.forEach(function (val) {
        maxSize = (maxSize > val.size)? maxSize : val.size;
    });
    table += '
Variable	Def-Use pairs
';
    inDUpairs.forEach(function (val, key) {
        var rowSize = 0;
        table += '
' + key + '	';
        val.forEach(function (pair) {
            table += '' + pair + '	';
            rowSize++;
        });
        while (rowSize < maxSize) {
            table += '	';
            rowSize++;
        }
        rowSize = 0;
        table += '
\n';
    });
    table += '
\n>];\n}';
    return table;
};

var singleton = new Graphics();
module.exports = singleton;<commit_msg>Support to convert map of DUPairs to be dot formatted<commit_after>/**
 * Created by ChengFuLin on 2015/5/11.
 */
var CFGExt = require('./cfgext'),
    AnalyzedCFG = require('./analyzedcfg'),
    Scope = require('./scope');

function Graphics() {
    "use strict";
}

/**
 * Output the representation of CFGs of all function scopes with dot language format
 * @param {AnalyzedCFG} analysisItem
 * @param {Function} dotConverter
 * @returns {string} dot formatted
 */
Graphics.prototype.analysisItemToCFG = function (analysisItem, dotConverter) {
    'use strict';
    var graph = 'digraph CFG {\n' + 'node [shape="box"]';
    var converter = CFGExt.toDotWithLabelLoc;
    if (dotConverter === CFGExt.toDot ||
        dotConverter === CFGExt.toDotWithLabelId ||
        dotConverter === CFGExt.toDotWithLabelLine ||
        dotConverter === CFGExt.toDotWithLabelLoc) {
        converter = dotConverter;
    }
    if (AnalyzedCFG.isAnalyzedCFG(analysisItem)) {
        graph += '\nlabel = "';
        if (analysisItem.scopeWrappers.length === 1) {
            graph += analysisItem.scopeWrappers[0].scope.type;
            if (analysisItem.scopeWrappers[0].scope.type === Scope.FUNCTION_TYPE) {
                graph += ' ' + analysisItem.scopeWrappers[0].scope.value;
            } else if (analysisItem.scopeWrappers[0].scope.type === Scope.ANONYMOUS_FUN_TYPE) {
                graph += '[ ' + analysisItem.scopeWrappers[0].scope.value + ' ]';
            }
        }
        graph += '"\n';
    }
    graph += converter(analysisItem.cfg);
    graph += '}';
    return graph;
};

/**
 * Output the representation of Def-Use pairs
 * @param inDUpairs
 * @returns {string}
 */
Graphics.prototype.dupairsToTable = function (inDUpairs) {
    'use strict';
    var table = 'digraph structs {\n' +
        'node [shape="plaintext"]\n' +
        'struct1 [label=<\n' +
        '
\n',
        maxSize = 0;
    inDUpairs.forEach(function (val) {
        maxSize = (maxSize > val.size)? maxSize : val.size;
    });
    table += '
Variable	Def-Use pairs
';
    inDUpairs.forEach(function (val, key) {
        var rowSize = 0;
        table += '
' + key.name + ' @ ' + key.scope + '	';
        val.forEach(function (pair) {
            table += '' + pair + '	';
            rowSize++;
        });
        while (rowSize < maxSize) {
            table += '	';
            rowSize++;
        }
        rowSize = 0;
        table += '
\n';
    });
    table += '
\n>];\n}';
    return table;
};

var singleton = new Graphics();
module.exports = singleton;<|endoftext|>


<commit_before>#! /usr/bin/env node
/*jslint node: true */

'use strict';

var fs = require('fs'),
    log,
    argv,
    dust = require('dustjs-linkedin'),
    path = require('path'),
    watch = require('watch'),
    colors = require('colors'),
    mkdirp = require('mkdirp'),
    wrench = require('wrench'),
    metaData = require('./package.json'),
    optimist = require('optimist'),
    sourcePath,
    destinationPath;

argv = optimist
    .usage('Usage: dust-compiler -s|--source source_path -d|--destination destination_path [--bootstrap] [--nonotify] [--includepath]')
    .alias('source', 's')
    .alias('destination', 'd')
    .alias('version', 'v')
    .describe('source', 'The source .dust templates to watch.')
    .describe('destination', 'The destination destination to write compiles .js files out to.')
    .describe('bootstrap', 'Does not replicate.  Displays the curl command that would be used.')
    .describe('nonotify', 'Do not notify.')
    .describe('includepath', 'Include the path in the name of the compiled dust template.')
    .describe('version', 'Show the current version installed of dust-compiler')
    .argv;

if (argv.v) {
    console.log('dust-compiler v' + metaData.version);
    process.exit();
}

if (argv.s && argv.d) {
    sourcePath = argv.s.match('/$') ? path.normalize(argv.s) : path.normalize(argv.s + '/');      // must end in slash
    destinationPath = argv.d.match('/$') ? path.normalize(argv.d) : path.normalize(argv.d + '/'); // must end in slash
} else {
    optimist.showHelp();
    console.log('ERROR: '.red + '-s and -d are required arguments');
    process.exit();
}

if (argv.nonotify) {
    log = console.log;
} else {
    log = (function () {
        var notifier;

        switch (process.platform) {
        case 'darwin':
            notifier = require('terminal-notifier');
            return function (message) {
                notifier(message.stripColors, {
                    title: 'Dust Compiler',
                    activate: 'com.apple.Terminal'
                });
                console.log(message);
            };

        case 'linux':
        case 'win32':
            notifier = require('growl');
            return function (message) {
                notifier(message.stripColors, { title: 'Dust Compiler' });
                console.log(message);
            };

        default:
            return console.log;
        }
    }());
}

function compile(source, currentStat, previousStat) {
    var data,
        errorFlag = false,
        filename,
        basename,
        filepath,
        compileFilename;

    source = path.normalize(source);

    if (path.extname(source) === '.dust') {
        fs.stat(source, function (error, stat) {
            if (error) {
                log('ERROR: '.red + 'fs.stat: ' + error.message);
                throw error;
            }

            if (!stat.isDirectory()) {

                filename = source.substring(sourcePath.length);
                basename = filename.substring(0, filename.length - 5);
                filepath = destinationPath + basename + '.js';
                compileFilename = argv.includepath ? sourcePath + basename : basename;

                fs.readFile(source, function (error, data) {
                    if (error) {
                        log('ERROR: '.red + 'fs.readFile: ' + error.message);
                        throw error;
                    }

                    try {
                        data = dust.compile(data.toString(), compileFilename);
                    } catch (err) {
                        /* error is passed into fs.readFile, so this catch can't be on error */
                        errorFlag = true;
                        log('ERROR: '.red + compileFilename.red + ': ' + err.message);
                    }

                    if (!errorFlag) {
                        mkdirp.mkdirp(path.dirname(filepath), function (error) {
                            if (error) {
                                log('ERROR: '.red + 'mkdirp.mkdirp: ' + error.message);
                                throw error;
                            }

                            fs.writeFile(filepath, data, function (error) {
                                if (error) {
                                    log('ERROR: '.red + 'fs.writeFile: ' + error.message);
                                    throw error;
                                }
                                log('Compiled '.green + sourcePath + filename + ' as '.green + compileFilename);
                            });
                        });
                    }
                });
            }
        });
    }
}

if (!fs.existsSync(sourcePath)) {
    console.log('ERROR: '.red + sourcePath + ' does not exist');
    process.exit();
}

if (!fs.existsSync(destinationPath)) {
    console.log('ERROR: '.red + destinationPath + ' does not exist');
    process.exit();
}

if (argv.bootstrap) {
    wrench.readdirRecursive(sourcePath, function (error, fileList) {
        if (fileList) {
            fileList.forEach(function (filename) {
                compile(sourcePath + filename);
            });
        }
    });
} else {
    watch.createMonitor(sourcePath, function (monitor) {
        log('Watching '.green + sourcePath);
        log('Will write to '.yellow + destinationPath.yellow);
        log('Type ^C to cancel'.yellow);

        monitor.on('created', compile);
        monitor.on('changed', compile);
    });
}

<commit_msg>making it work with wrapper, fixing help<commit_after>'use strict';

var fs = require('fs'),
    log,
    argv,
    dust = require('dustjs-linkedin'),
    path = require('path'),
    watch = require('watch'),
    colors = require('colors'),
    mkdirp = require('mkdirp'),
    wrench = require('wrench'),
    metaData = require('../package.json'),
    optimist = require('optimist'),
    sourcePath,
    destinationPath;

argv = optimist
    .usage('Usage: dust-compiler -s|--source source_path -d|--destination destination_path [--bootstrap] [--nonotify] [--includepath]')
    .alias('source', 's')
    .alias('destination', 'd')
    .alias('version', 'v')
    .describe('source', 'The source .dust templates to watch.')
    .describe('destination', 'The destination destination to write compiles .js files out to.')
    .describe('bootstrap', 'Compiles all files on start.')
    .describe('nonotify', 'Do not notify.')
    .describe('includepath', 'Include the path in the name of the compiled dust template.')
    .describe('version', 'Show the current version installed of dust-compiler')
    .argv;

if (argv.v) {
    console.log('dust-compiler v' + metaData.version);
    process.exit();
}

if (argv.s && argv.d) {
    sourcePath = argv.s.match('/$') ? path.normalize(argv.s) : path.normalize(argv.s + '/');      // must end in slash
    destinationPath = argv.d.match('/$') ? path.normalize(argv.d) : path.normalize(argv.d + '/'); // must end in slash
} else {
    optimist.showHelp();
    console.log('ERROR: '.red + '-s and -d are required arguments');
    process.exit();
}

if (argv.nonotify) {
    log = console.log;
} else {
    log = (function () {
        var notifier;

        switch (process.platform) {
        case 'darwin':
            notifier = require('terminal-notifier');
            return function (message) {
                notifier(message.stripColors, {
                    title: 'Dust Compiler',
                    activate: 'com.apple.Terminal'
                });
                console.log(message);
            };

        case 'linux':
        case 'win32':
            notifier = require('growl');
            return function (message) {
                notifier(message.stripColors, { title: 'Dust Compiler' });
                console.log(message);
            };

        default:
            return console.log;
        }
    }());
}

function compile(source, currentStat, previousStat) {
    var data,
        errorFlag = false,
        filename,
        basename,
        filepath,
        compileFilename;

    source = path.normalize(source);

    if (path.extname(source) === '.dust') {
        fs.stat(source, function (error, stat) {
            if (error) {
                log('ERROR: '.red + 'fs.stat: ' + error.message);
                throw error;
            }

            if (!stat.isDirectory()) {

                filename = source.substring(sourcePath.length);
                basename = filename.substring(0, filename.length - 5);
                filepath = destinationPath + basename + '.js';
                compileFilename = argv.includepath ? sourcePath + basename : basename;

                fs.readFile(source, function (error, data) {
                    if (error) {
                        log('ERROR: '.red + 'fs.readFile: ' + error.message);
                        throw error;
                    }

                    try {
                        data = dust.compile(data.toString(), compileFilename);
                    } catch (err) {
                        /* error is passed into fs.readFile, so this catch can't be on error */
                        errorFlag = true;
                        log('ERROR: '.red + compileFilename.red + ': ' + err.message);
                    }

                    if (!errorFlag) {
                        mkdirp.mkdirp(path.dirname(filepath), function (error) {
                            if (error) {
                                log('ERROR: '.red + 'mkdirp.mkdirp: ' + error.message);
                                throw error;
                            }

                            fs.writeFile(filepath, data, function (error) {
                                if (error) {
                                    log('ERROR: '.red + 'fs.writeFile: ' + error.message);
                                    throw error;
                                }
                                log('Compiled '.green + sourcePath + filename + ' as '.green + compileFilename);
                            });
                        });
                    }
                });
            }
        });
    }
}

if (!fs.existsSync(sourcePath)) {
    console.log('ERROR: '.red + sourcePath + ' does not exist');
    process.exit();
}

if (!fs.existsSync(destinationPath)) {
    console.log('ERROR: '.red + destinationPath + ' does not exist');
    process.exit();
}

if (argv.bootstrap) {
    wrench.readdirRecursive(sourcePath, function (error, fileList) {
        if (fileList) {
            fileList.forEach(function (filename) {
                compile(sourcePath + filename);
            });
        }
    });
} else {
    watch.createMonitor(sourcePath, function (monitor) {
        log('Watching '.green + sourcePath);
        log('Will write to '.yellow + destinationPath.yellow);
        log('Type ^C to cancel'.yellow);

        monitor.on('created', compile);
        monitor.on('changed', compile);
    });
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Oculus Info Inc.
 * http://www.oculusinfo.com/
 *
 * Released under the MIT License.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/**
 * An overridden OpenLayers.Tile object to create DOM elements based on
 * tile data. Used by HtmlTileLayers for client rendered layers. Uses
 * either Renderer objects or html functions to generate the DOM elements
 * or html strings.
 */
( function() {

    "use strict";

    OpenLayers.Tile.HTML = function() {
        this.url = null;
        this.imgDiv = null;
        this.imageReloadAttempts = null;
        OpenLayers.Tile.apply( this, arguments );
    };

    OpenLayers.Tile.HTML.prototype = Object.create( OpenLayers.Tile.prototype );

    OpenLayers.Tile.HTML.prototype.destroy = function() {
        if ( this.imgDiv )  {
            this.clear();
            this.imgDiv = null;
        }
        OpenLayers.Tile.prototype.destroy.apply( this, arguments );
    };

    OpenLayers.Tile.HTML.prototype.draw = function() {
        var shouldDraw = OpenLayers.Tile.prototype.draw.apply( this, arguments );
        if ( shouldDraw ) {
            if ( this.isLoading ) {
                //if we're already loading, send 'reload' instead of 'loadstart'.
                this._loadEvent = "reload";
            } else {
                this.isLoading = true;
                this._loadEvent = "loadstart";
            }
            this.renderTile();
            this.positionTile();
        } else if ( shouldDraw === false ) {
            this.unload();
        }
        return shouldDraw;
    };

    OpenLayers.Tile.HTML.prototype.getURL = function() {
        var url = this.layer.getURL( this.bounds );
        if ( url instanceof Array ) {
            url = url.join('|');
        }
        return url;
    };

    OpenLayers.Tile.HTML.prototype.renderTile = function() {
        this.url = this.getURL();
        this.initImage();
    };

    OpenLayers.Tile.HTML.prototype.positionTile = function() {
        var style = this.getTile().style,
            size = this.layer.getImageSize( this.bounds ),
            ratio = 1;
        if ( this.layer instanceof OpenLayers.Layer.Grid ) {
            ratio = this.layer.getServerResolution() / this.layer.map.getResolution();
        }
        style.left = this.position.x + "px";
        style.top = this.position.y + "px";
        style.width = Math.round( ratio * size.w ) + "px";
        style.height = Math.round( ratio * size.h ) + "px";
    };

    OpenLayers.Tile.HTML.prototype.clear = function() {
        OpenLayers.Tile.prototype.clear.apply( this, arguments );
        var img = this.imgDiv;
        if ( img ) {
            var tile = this.getTile();
            if ( tile.parentNode === this.layer.div ) {
                this.layer.div.removeChild( tile );
            }
            this.setImgSrc();
            OpenLayers.Element.removeClass(img, "olImageLoadError");
        }
    };

    OpenLayers.Tile.HTML.prototype.getImage = function() {
        if ( !this.imgDiv ) {
            this.imgDiv = document.createElement( 'div' );
            this.imgDiv.className = 'olTileHtml';
            var style = this.imgDiv.style;
            style.visibility = "hidden";
            style.opacity = 0;
            if ( this.layer.opacity < 1 ) {
                style.filter = 'alpha(opacity=' + (this.layer.opacity * 100) + ')';
            }
            style.position = "absolute";
        }
        return this.imgDiv;
    };

    OpenLayers.Tile.HTML.prototype.setImage = function( img ) {
        this.imgDiv = img;
    };

    /**/
    OpenLayers.Tile.HTML.prototype.initImage = function() {
        if ( !this.url && !this.imgDiv ) {
            // fast path out - if there is no tile url and no previous image
            this.isLoading = false;
            return;
        }
        this.events.triggerEvent('beforeload');
        this.layer.div.appendChild( this.getTile() );
        this.events.triggerEvent( this._loadEvent );
        var img = this.getImage();
        var dataUrl = img.getAttribute('data-url') || '';
        if ( dataUrl === this.url ) {
            this._loadTimeout = window.setTimeout(
                OpenLayers.Function.bind( this.onImageLoad, this ),
                0 );
        } else {
            this.stopLoading();
            this.imageReloadAttempts = 0;
            this.setImgSrc( this.url );
        }
    };

    OpenLayers.Tile.HTML.prototype.setImgSrc = function( url ) {
        var that  = this,
            img = this.imgDiv;
        if ( url ) {
            var urls = url.split('|');
            img.style.visibility = 'hidden';
            img.style.opacity = 0;
            img.setAttribute( "data-url", url );
            var pendingRequests = urls.map( function( url ) {
                img._lastRequest = Date.now();
                var deferred = $.Deferred();
                $.ajax({
                    url: url
                }).then(
                    function( results ) {
                        deferred.resolve( results );
                    },
                    function( xhr ) {
                        deferred.reject();
                        console.error( xhr.responseText );
                        console.error( xhr );
                    }
                );
                return deferred;
            });
            $.when.apply( $, pendingRequests ).then(
                function() {
                    if ( url === that.url ) {
                        that.onImageLoad.apply( that, arguments );
                    }
                },
                function() {
                    if ( url === that.url ) {
                        that.onImageError();
                    }
                }
            );
        } else {
            // Remove reference to the image, and leave it to the browser's
            // caching and garbage collection.
            this.stopLoading();
            this.imgDiv = null;
            if ( img.parentNode ) {
                img.parentNode.removeChild( img );
            }
        }
    };

    OpenLayers.Tile.HTML.prototype.getTile = function() {
        return this.getImage();
    };

    OpenLayers.Tile.HTML.prototype.createBackBuffer = function() {
        return;
    };

    OpenLayers.Tile.HTML.prototype.renderHtml = function() {
        var imgDiv = this.imgDiv,
            tileData = imgDiv._tileData,
            renderer = this.getRenderer(),
            aggregator,
            html,
            render;
        // clear tile contents
        imgDiv.innerHTML = "";
        // hide standard tile hover interaction
        if ( renderer.spec.hideTile ) {
            imgDiv.className = imgDiv.className + " hideTile";
        }
        if ( !tileData || tileData.length === 0 ) {
            // no data, exit
            return;
        }
        // ensure there is at least one set of data
        // tile data is under 'tile', elasticsearch is under 'hits'
        var hasTileOrHits = false;
        tileData.forEach( function( datum ) {
            if ( datum.tile || datum.hits ) {
                hasTileOrHits = true;
            }
        });
        // no content in data, exit
        if ( !hasTileOrHits ) {
            return;
        }
        // if aggregator, aggregate the data
        aggregator = renderer.aggregator;
        if ( aggregator ) {
            var outOfRangeCount = 0;
            tileData.forEach( function( datum ) {
                if ( datum.tile ) {
                    // only aggregate the data if it hasn't already been aggregated
                    if ( !datum.tile.meta.aggregated ) {
                        datum.tile.meta = {
                            raw: datum.tile.meta.map.bins,
                            aggregated: aggregator.aggregate( datum.tile.meta.map.bins )
                        };
                    }
                    // check if requested range is outside of available range
                    if ( datum.tile.meta.aggregated.length === 0 ) {
                        // no data, flag as out of range
                        outOfRangeCount++;
                    }
                }
            });
            // if all data is outside the range, exit early
            if ( outOfRangeCount === tileData.length ) {
                // data outside of range, exit
                return;
            }
        }
        var data = tileData.length === 1 ? tileData[0] : tileData;
        // render data
        render = renderer.render( data );
        html = render.html;
        this.entries = render.entries;
        // add html to the tile div
        if ( html instanceof $ ) {
            // if generated a jquery object, append it
            $( imgDiv ).append( html );
        } else if ( html instanceof HTMLElement ) {
            // if generated an HTMLElement, get html text
            imgDiv.appendChild( html );
        } else {
            // if generated string, set inner html
            imgDiv.innerHTML = html;
        }
        // inject selected entry classes
        renderer.injectEntries( imgDiv.children, this.entries );
        // call renderer hook function
        renderer.executeHooks( imgDiv.children, this.entries, data );
    };

    OpenLayers.Tile.HTML.prototype.getRenderer = function() {
        var renderer = this.layer.renderer;
        if ( typeof renderer === "function" ) {
            renderer = renderer.call( this.layer, this.bounds );
        }
        return renderer;
    };

    OpenLayers.Tile.HTML.prototype.onImageLoad = function() {
        var img = this.imgDiv;
        this.stopLoading();
        if ( img ) {
            img.style.visibility = 'inherit';
            img.style.opacity = this.layer.opacity;
            if ( arguments.length > 0 ) {
                // only set the data if there is new data to set
                var data = [],
                    i;
                for ( i=0; i<arguments.length; i++ ) {
                    data.push( arguments[i] );
                }
                img._tileData = data;
            }
            // render the data
            this.renderHtml();
            // trigger load end
            this.events.triggerEvent("loadend");
            this.isLoading = false;
        }
    };

    OpenLayers.Tile.HTML.prototype.onImageError = function() {
        var img = this.imgDiv;
        if ( img && img.getAttribute('data-url') ) {
            this.imageReloadAttempts++;
            if ( this.imageReloadAttempts <= OpenLayers.IMAGE_RELOAD_ATTEMPTS ) {
                this.setImgSrc( this.getURL() );
            } else {
                OpenLayers.Element.addClass( img, "olImageLoadError" );
                this.events.triggerEvent("loaderror");
                this.onImageLoad();
            }
        }
    };

    OpenLayers.Tile.HTML.prototype.stopLoading = function() {
        window.clearTimeout( this._loadTimeout );
        delete this._loadTimeout;
    };

    OpenLayers.Tile.HTML.prototype.getCanvasContext = function() {
        return undefined;
    };

    /**
     * OpenLayers overrides
     */

    OpenLayers.TileManager.prototype.addTile = function(evt) {
        if ( evt.tile instanceof OpenLayers.Tile.Image ||
            evt.tile instanceof OpenLayers.Tile.HTML ||
            evt.tile instanceof OpenLayers.Tile.Univariate ) {
          if ( !evt.tile.layer.singleTile ) {
            evt.tile.events.on({
                beforedraw: this.queueTileDraw,
                beforeload: this.manageTileCache,
                loadend: this.addToCache,
                unload: this.unloadTile,
                scope: this
            });
          }
        } else {
            // Layer has the wrong tile type, so don't handle it any longer
            this.removeLayer({layer: evt.tile.layer});
        }
    };

    OpenLayers.TileManager.prototype.queueTileDraw = function( evt ) {
        var tile = evt.object;
        var queued = false;
        var layer = tile.layer;
        var url = tile.getURL ? tile.getURL() : layer.getURL( tile.bounds );
        var img = this.tileCache[url];
        if ( img &&
            img.className !== 'olTileImage' &&
            img.className !== 'olTileHtml' &&
            img.className !== 'olTileUnivariate' ) {
            // cached image no longer valid, e.g. because we're olTileReplacing
            delete this.tileCache[ url ];
            OpenLayers.Util.removeItem( this.tileCacheIndex, url );
            img = null;
        }
        // queue only if image with same url not cached already
        if ( layer.url && ( layer.async || !img ) ) {
            // add to queue only if not in queue already
            var tileQueue = this.tileQueue[ layer.map.id ];
            if ( !~OpenLayers.Util.indexOf( tileQueue, tile ) ) {
                tileQueue.push(tile);
            }
            queued = true;
        }
        return !queued;
    };

    OpenLayers.Tile.Image.prototype.createBackBuffer = function() {
        return;
    };

    module.exports = OpenLayers.Tile.HTML;
}());
<commit_msg>Updated TileManager class check to hasClass instead of className check as tiles may have multiple classes.<commit_after>/*
 * Copyright (c) 2014 Oculus Info Inc.
 * http://www.oculusinfo.com/
 *
 * Released under the MIT License.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/**
 * An overridden OpenLayers.Tile object to create DOM elements based on
 * tile data. Used by HtmlTileLayers for client rendered layers. Uses
 * either Renderer objects or html functions to generate the DOM elements
 * or html strings.
 */
( function() {

    "use strict";

    OpenLayers.Tile.HTML = function() {
        this.url = null;
        this.imgDiv = null;
        this.imageReloadAttempts = null;
        OpenLayers.Tile.apply( this, arguments );
    };

    OpenLayers.Tile.HTML.prototype = Object.create( OpenLayers.Tile.prototype );

    OpenLayers.Tile.HTML.prototype.destroy = function() {
        if ( this.imgDiv )  {
            this.clear();
            this.imgDiv = null;
        }
        OpenLayers.Tile.prototype.destroy.apply( this, arguments );
    };

    OpenLayers.Tile.HTML.prototype.draw = function() {
        var shouldDraw = OpenLayers.Tile.prototype.draw.apply( this, arguments );
        if ( shouldDraw ) {
            if ( this.isLoading ) {
                //if we're already loading, send 'reload' instead of 'loadstart'.
                this._loadEvent = "reload";
            } else {
                this.isLoading = true;
                this._loadEvent = "loadstart";
            }
            this.renderTile();
            this.positionTile();
        } else if ( shouldDraw === false ) {
            this.unload();
        }
        return shouldDraw;
    };

    OpenLayers.Tile.HTML.prototype.getURL = function() {
        var url = this.layer.getURL( this.bounds );
        if ( url instanceof Array ) {
            url = url.join('|');
        }
        return url;
    };

    OpenLayers.Tile.HTML.prototype.renderTile = function() {
        this.url = this.getURL();
        this.initImage();
    };

    OpenLayers.Tile.HTML.prototype.positionTile = function() {
        var style = this.getTile().style,
            size = this.layer.getImageSize( this.bounds ),
            ratio = 1;
        if ( this.layer instanceof OpenLayers.Layer.Grid ) {
            ratio = this.layer.getServerResolution() / this.layer.map.getResolution();
        }
        style.left = this.position.x + "px";
        style.top = this.position.y + "px";
        style.width = Math.round( ratio * size.w ) + "px";
        style.height = Math.round( ratio * size.h ) + "px";
    };

    OpenLayers.Tile.HTML.prototype.clear = function() {
        OpenLayers.Tile.prototype.clear.apply( this, arguments );
        var img = this.imgDiv;
        if ( img ) {
            var tile = this.getTile();
            if ( tile.parentNode === this.layer.div ) {
                this.layer.div.removeChild( tile );
            }
            this.setImgSrc();
            OpenLayers.Element.removeClass(img, "olImageLoadError");
        }
    };

    OpenLayers.Tile.HTML.prototype.getImage = function() {
        if ( !this.imgDiv ) {
            this.imgDiv = document.createElement( 'div' );
            this.imgDiv.className = 'olTileHtml';
            var style = this.imgDiv.style;
            style.visibility = "hidden";
            style.opacity = 0;
            if ( this.layer.opacity < 1 ) {
                style.filter = 'alpha(opacity=' + (this.layer.opacity * 100) + ')';
            }
            style.position = "absolute";
        }
        return this.imgDiv;
    };

    OpenLayers.Tile.HTML.prototype.setImage = function( img ) {
        this.imgDiv = img;
    };

    /**/
    OpenLayers.Tile.HTML.prototype.initImage = function() {
        if ( !this.url && !this.imgDiv ) {
            // fast path out - if there is no tile url and no previous image
            this.isLoading = false;
            return;
        }
        this.events.triggerEvent('beforeload');
        this.layer.div.appendChild( this.getTile() );
        this.events.triggerEvent( this._loadEvent );
        var img = this.getImage();
        var dataUrl = img.getAttribute('data-url') || '';
        if ( dataUrl === this.url ) {
            this._loadTimeout = window.setTimeout(
                OpenLayers.Function.bind( this.onImageLoad, this ),
                0 );
        } else {
            this.stopLoading();
            this.imageReloadAttempts = 0;
            this.setImgSrc( this.url );
        }
    };

    OpenLayers.Tile.HTML.prototype.setImgSrc = function( url ) {
        var that  = this,
            img = this.imgDiv;
        if ( url ) {
            var urls = url.split('|');
            img.style.visibility = 'hidden';
            img.style.opacity = 0;
            img.setAttribute( "data-url", url );
            var pendingRequests = urls.map( function( url ) {
                img._lastRequest = Date.now();
                var deferred = $.Deferred();
                $.ajax({
                    url: url
                }).then(
                    function( results ) {
                        deferred.resolve( results );
                    },
                    function( xhr ) {
                        deferred.reject();
                        console.error( xhr.responseText );
                        console.error( xhr );
                    }
                );
                return deferred;
            });
            $.when.apply( $, pendingRequests ).then(
                function() {
                    if ( url === that.url ) {
                        that.onImageLoad.apply( that, arguments );
                    }
                },
                function() {
                    if ( url === that.url ) {
                        that.onImageError();
                    }
                }
            );
        } else {
            // Remove reference to the image, and leave it to the browser's
            // caching and garbage collection.
            this.stopLoading();
            this.imgDiv = null;
            if ( img.parentNode ) {
                img.parentNode.removeChild( img );
            }
        }
    };

    OpenLayers.Tile.HTML.prototype.getTile = function() {
        return this.getImage();
    };

    OpenLayers.Tile.HTML.prototype.createBackBuffer = function() {
        return;
    };

    OpenLayers.Tile.HTML.prototype.renderHtml = function() {
        var imgDiv = this.imgDiv,
            tileData = imgDiv._tileData,
            renderer = this.getRenderer(),
            aggregator,
            html,
            render;
        // clear tile contents
        imgDiv.innerHTML = "";
        // hide standard tile hover interaction
        if ( renderer.spec.hideTile ) {
            imgDiv.className = imgDiv.className + " hideTile";
        }
        if ( !tileData || tileData.length === 0 ) {
            // no data, exit
            return;
        }
        // ensure there is at least one set of data
        // tile data is under 'tile', elasticsearch is under 'hits'
        var hasTileOrHits = false;
        tileData.forEach( function( datum ) {
            if ( datum.tile || datum.hits ) {
                hasTileOrHits = true;
            }
        });
        // no content in data, exit
        if ( !hasTileOrHits ) {
            return;
        }
        // if aggregator, aggregate the data
        aggregator = renderer.aggregator;
        if ( aggregator ) {
            var outOfRangeCount = 0;
            tileData.forEach( function( datum ) {
                if ( datum.tile ) {
                    // only aggregate the data if it hasn't already been aggregated
                    if ( !datum.tile.meta.aggregated ) {
                        datum.tile.meta = {
                            raw: datum.tile.meta.map.bins,
                            aggregated: aggregator.aggregate( datum.tile.meta.map.bins )
                        };
                    }
                    // check if requested range is outside of available range
                    if ( datum.tile.meta.aggregated.length === 0 ) {
                        // no data, flag as out of range
                        outOfRangeCount++;
                    }
                }
            });
            // if all data is outside the range, exit early
            if ( outOfRangeCount === tileData.length ) {
                // data outside of range, exit
                return;
            }
        }
        var data = tileData.length === 1 ? tileData[0] : tileData;
        // render data
        render = renderer.render( data );
        html = render.html;
        this.entries = render.entries;
        // add html to the tile div
        if ( html instanceof $ ) {
            // if generated a jquery object, append it
            $( imgDiv ).append( html );
        } else if ( html instanceof HTMLElement ) {
            // if generated an HTMLElement, get html text
            imgDiv.appendChild( html );
        } else {
            // if generated string, set inner html
            imgDiv.innerHTML = html;
        }
        // inject selected entry classes
        renderer.injectEntries( imgDiv.children, this.entries );
        // call renderer hook function
        renderer.executeHooks( imgDiv.children, this.entries, data );
    };

    OpenLayers.Tile.HTML.prototype.getRenderer = function() {
        var renderer = this.layer.renderer;
        if ( typeof renderer === "function" ) {
            renderer = renderer.call( this.layer, this.bounds );
        }
        return renderer;
    };

    OpenLayers.Tile.HTML.prototype.onImageLoad = function() {
        var img = this.imgDiv;
        this.stopLoading();
        if ( img ) {
            img.style.visibility = 'inherit';
            img.style.opacity = this.layer.opacity;
            if ( arguments.length > 0 ) {
                // only set the data if there is new data to set
                var data = [],
                    i;
                for ( i=0; i<arguments.length; i++ ) {
                    data.push( arguments[i] );
                }
                img._tileData = data;
            }
            // render the data
            this.renderHtml();
            // trigger load end
            this.events.triggerEvent("loadend");
            this.isLoading = false;
        }
    };

    OpenLayers.Tile.HTML.prototype.onImageError = function() {
        var img = this.imgDiv;
        if ( img && img.getAttribute('data-url') ) {
            this.imageReloadAttempts++;
            if ( this.imageReloadAttempts <= OpenLayers.IMAGE_RELOAD_ATTEMPTS ) {
                this.setImgSrc( this.getURL() );
            } else {
                OpenLayers.Element.addClass( img, "olImageLoadError" );
                this.events.triggerEvent("loaderror");
                this.onImageLoad();
            }
        }
    };

    OpenLayers.Tile.HTML.prototype.stopLoading = function() {
        window.clearTimeout( this._loadTimeout );
        delete this._loadTimeout;
    };

    OpenLayers.Tile.HTML.prototype.getCanvasContext = function() {
        return undefined;
    };

    /**
     * OpenLayers overrides
     */

    OpenLayers.TileManager.prototype.addTile = function(evt) {
        if ( evt.tile instanceof OpenLayers.Tile.Image ||
            evt.tile instanceof OpenLayers.Tile.HTML ||
            evt.tile instanceof OpenLayers.Tile.Univariate ) {
          if ( !evt.tile.layer.singleTile ) {
            evt.tile.events.on({
                beforedraw: this.queueTileDraw,
                beforeload: this.manageTileCache,
                loadend: this.addToCache,
                unload: this.unloadTile,
                scope: this
            });
          }
        } else {
            // Layer has the wrong tile type, so don't handle it any longer
            this.removeLayer({layer: evt.tile.layer});
        }
    };

    OpenLayers.TileManager.prototype.queueTileDraw = function( evt ) {
        var tile = evt.object;
        var queued = false;
        var layer = tile.layer;
        var url = tile.getURL ? tile.getURL() : layer.getURL( tile.bounds );
        var img = this.tileCache[url];
        if ( img &&
            !OpenLayers.Element.hasClass( img, 'olTileImage' ) &&
            !OpenLayers.Element.hasClass( img, 'olTileHtml' ) &&
            !OpenLayers.Element.hasClass( img, 'olTileUnivariate' ) ) {
            // cached image no longer valid, e.g. because we're olTileReplacing
            delete this.tileCache[ url ];
            OpenLayers.Util.removeItem( this.tileCacheIndex, url );
            img = null;
        }
        // queue only if image with same url not cached already
        if ( layer.url && ( layer.async || !img ) ) {
            // add to queue only if not in queue already
            var tileQueue = this.tileQueue[ layer.map.id ];
            if ( !~OpenLayers.Util.indexOf( tileQueue, tile ) ) {
                tileQueue.push(tile);
            }
            queued = true;
        }
        return !queued;
    };

    OpenLayers.Tile.Image.prototype.createBackBuffer = function() {
        return;
    };

    module.exports = OpenLayers.Tile.HTML;
}());
<|endoftext|>


<commit_before>"use strict";

var Base = require('../base')
var proto = Base.prototype
var util = require('../util')

var Emitter = module.exports = new Base({
  $inject: require('../base/uid'),
  $define: {
    $ChildConstructor: Base,
    $executePostponed: true,
    $exec:function( bind, event, bound ) {
      var emitter = this

      var stamp = emitter.$lastStamp = event.$stamp

      // console.error('EXEC', bind.$path, emitter._$parent._$parent.$path)

      if(emitter.$onFn) {
        emitter.$onFn.each(function(property, key) {
          property.call( bind, event, emitter._$meta )
        }, exclude, stamp )
      }

      if( emitter.$onBase ) {
        emitter.$onBase.each(function(property) {
          // console.log('emit base (real) from:', emitter._$parent._$parent.$path, 'to:', property.$path)
          property.$emit('$change', event)
          //no instances nessecary ??? lets find out...
        }, exclude, stamp )
      }

      if( emitter.$onPasson ) {
        emitter.$onPasson.each(function(property) {
          execPasson( property, bind, event, emitter )
        }, exclude, stamp )
      }

      if(emitter._$meta) {
        emitter._$meta = null
      }

      if( !bound && this.__$bind__ ) {
        for(var i in this.__$bind__) {
          if(this.__$bind__[i] !== bind) {
            // console.error('exec bound')
            this.$exec( this.__$bind__[i], event, true )
          } else {
            console.error('dont exec myself twice!')
          }
        }
        this.__$bind__ = null
      }

      // if(this.__$bind__ ) {

      // }

    },
    $addListener:function( val, key, unique, event ) {

      if(!key) {
        key = generateId( this )
      }

      if( typeof val === 'function' )
      {
        add( this, '$onFn', val, key, unique, event )
      } else if( val instanceof Base ) {
        if( !add( this, '$onBase', val, key, unique || true, event ) ) {
          if(!val.$listensOnBase) {
            val.$setKeyInternal( '$listensOnBase', {}, false )
          }
          var listensOnBase =  val.$listensOnBase
          listensOnBase.$setKeyInternal( generateId( listensOnBase ) )
        }
      } else if( val instanceof Array ) {
        if( !add( this, '$onPasson', val, key, unique, event ) ) {
          if(val[2]) {
            val[2] = val.slice(1)
            val = val.slice(0,2)
          }
          if( val[1] instanceof Base ) {
            if( !val.$listensOnPasson ) {
              val[1].$setKeyInternal( '$listensOnPasson', {}, false )
            }
            var listensOnPasson =  val[1].$listensOnPasson
            listensOnPasson.$setKeyInternal( generateId( listensOnPasson ) )
          }
        }
      }
    },
    $set:function( val, event ) {
      if( util.isPlainObj( val ) && !(val instanceof Array) ) {
        if( val.$define ) {
          proto.$set.apply( this, arguments )
        } else {
          for(var key$ in val) {
            this.$addListener( val[key$], key$, void 0, event )
          }
        }
      } else {
        //uses each so $ amd _ fields get ignored (thats why val)
        this.$addListener( val, 'val', void 0, event )
      }
    },
    // $bind:{
    //   get:function( val, event ) {
    //     //double check (instances again)
    //     return this.__bind__ || this.$parent.$parent
    //   }
    // },
    $postpone: function( bind, event ) {

      if( !event ) {
        throw new Error( '$postpone does not have event! (emitter)' )
        return
      }

      // console.info('BIND IT!', bind.$path, bind.$postPonedStamp)

      if(
        !bind.hasOwnProperty('$postPonedStamp') ||
        (event.$stamp !== bind.$postPonedStamp[this.$uid])
      ) {
        // console.info('BIND IT PASS!!', bind.$path, bind.$postPonedStamp)

        if( !this.__$bind__ ) {
          this.__$bind__ = []
        }

        if( this._$parent._$parent !== bind ) {
          this.__$bind__.push( bind )
        }

        if(
          !this.hasOwnProperty( '$myPostPonedStamp' ) ||
          this.$myPostPonedStamp !== event.$stamp
        ) {
          event.$postpone( this )
        }

        if( !bind.hasOwnProperty( '$postPonedStamp' ) ) {
          bind.$postPonedStamp = {}
        }

        bind.$postPonedStamp[this.$uid] = this.$myPostPonedStamp = event.$stamp
      }
    },
    $emit:function( event, bind, force, meta ) {
      if( meta ) {
        this._$meta = meta
      }
      if( this.$lastStamp !== event.$stamp ) {
        if( event.$origin !== bind && !force ) {
          this.$postpone( bind, event )
        } else {
          this.$exec( bind, event )
        }
      }
    }
  }
}).$Constructor

//helpers -- maybe make into a seperate module 'shared'?
function exclude( property, key, base, stamp ) {
  var ignore = property._$ignoreStamp
  if( ignore ) {
    property._$ignoreStamp = null
    if( ignore === stamp ) {
      return true
    }
  }
}

function execPasson( property, bind, event, emitter ) {
  if( property[2] ) {
      property[0].apply(
      bind,
      [ event, emitter._$meta ].concat( property[2] )
    )
  } else {
    property[0].call( bind, event, emitter._$meta, property[1] )
  }
}

function generateId( base ) {
  return base._$id ? base._$id++ : (base._$id = 1)
}

function add( emitter, type, val, key, unique, event ) {
   if(!emitter[type]) {
      emitter.$setKey( type, {}, false )
   } else if( unique && emitter[type] ) {
    var isFn = typeof unique === 'function'
    if(isFn) {
       for(var i in emitter[type]) {
        if( unique.call( emitter, emitter[type][i], val) ) {
          return true
        }
      }
    } else {
      for( var i in emitter[type] ) {
        if( emitter[type][i] === val ) {
          return true
        }
      }
    }
  }

  if( emitter[type]._$parent !== emitter ) {
    emitter.$setKey( type, {}, false )
  }

  console.warn(event,'???')

  if(event) {
    val._$ignoreStamp = event.$stamp
  }

  emitter[type][key] = val
}

<commit_msg>removed log<commit_after>"use strict";

var Base = require('../base')
var proto = Base.prototype
var util = require('../util')

var Emitter = module.exports = new Base({
  $inject: require('../base/uid'),
  $define: {
    $ChildConstructor: Base,
    $executePostponed: true,
    $exec:function( bind, event, bound ) {
      var emitter = this

      var stamp = emitter.$lastStamp = event.$stamp

      // console.error('EXEC', bind.$path, emitter._$parent._$parent.$path)

      if(emitter.$onFn) {
        emitter.$onFn.each(function(property, key) {
          property.call( bind, event, emitter._$meta )
        }, exclude, stamp )
      }

      if( emitter.$onBase ) {
        emitter.$onBase.each(function(property) {
          // console.log('emit base (real) from:', emitter._$parent._$parent.$path, 'to:', property.$path)
          property.$emit('$change', event)
          //no instances nessecary ??? lets find out...
        }, exclude, stamp )
      }

      if( emitter.$onPasson ) {
        emitter.$onPasson.each(function(property) {
          execPasson( property, bind, event, emitter )
        }, exclude, stamp )
      }

      if(emitter._$meta) {
        emitter._$meta = null
      }

      if( !bound && this.__$bind__ ) {
        for(var i in this.__$bind__) {
          if(this.__$bind__[i] !== bind) {
            // console.error('exec bound')
            this.$exec( this.__$bind__[i], event, true )
          } else {
            console.error('dont exec myself twice!')
          }
        }
        this.__$bind__ = null
      }

      // if(this.__$bind__ ) {

      // }

    },
    $addListener:function( val, key, unique, event ) {

      if(!key) {
        key = generateId( this )
      }

      if( typeof val === 'function' )
      {
        add( this, '$onFn', val, key, unique, event )
      } else if( val instanceof Base ) {
        if( !add( this, '$onBase', val, key, unique || true, event ) ) {
          if(!val.$listensOnBase) {
            val.$setKeyInternal( '$listensOnBase', {}, false )
          }
          var listensOnBase =  val.$listensOnBase
          listensOnBase.$setKeyInternal( generateId( listensOnBase ) )
        }
      } else if( val instanceof Array ) {
        if( !add( this, '$onPasson', val, key, unique, event ) ) {
          if(val[2]) {
            val[2] = val.slice(1)
            val = val.slice(0,2)
          }
          if( val[1] instanceof Base ) {
            if( !val.$listensOnPasson ) {
              val[1].$setKeyInternal( '$listensOnPasson', {}, false )
            }
            var listensOnPasson =  val[1].$listensOnPasson
            listensOnPasson.$setKeyInternal( generateId( listensOnPasson ) )
          }
        }
      }
    },
    $set:function( val, event ) {
      if( util.isPlainObj( val ) && !(val instanceof Array) ) {
        if( val.$define ) {
          proto.$set.apply( this, arguments )
        } else {
          for(var key$ in val) {
            this.$addListener( val[key$], key$, void 0, event )
          }
        }
      } else {
        //uses each so $ amd _ fields get ignored (thats why val)
        this.$addListener( val, 'val', void 0, event )
      }
    },
    // $bind:{
    //   get:function( val, event ) {
    //     //double check (instances again)
    //     return this.__bind__ || this.$parent.$parent
    //   }
    // },
    $postpone: function( bind, event ) {

      if( !event ) {
        throw new Error( '$postpone does not have event! (emitter)' )
        return
      }

      // console.info('BIND IT!', bind.$path, bind.$postPonedStamp)

      if(
        !bind.hasOwnProperty('$postPonedStamp') ||
        (event.$stamp !== bind.$postPonedStamp[this.$uid])
      ) {
        // console.info('BIND IT PASS!!', bind.$path, bind.$postPonedStamp)

        if( !this.__$bind__ ) {
          this.__$bind__ = []
        }

        if( this._$parent._$parent !== bind ) {
          this.__$bind__.push( bind )
        }

        if(
          !this.hasOwnProperty( '$myPostPonedStamp' ) ||
          this.$myPostPonedStamp !== event.$stamp
        ) {
          event.$postpone( this )
        }

        if( !bind.hasOwnProperty( '$postPonedStamp' ) ) {
          bind.$postPonedStamp = {}
        }

        bind.$postPonedStamp[this.$uid] = this.$myPostPonedStamp = event.$stamp
      }
    },
    $emit:function( event, bind, force, meta ) {
      if( meta ) {
        this._$meta = meta
      }
      if( this.$lastStamp !== event.$stamp ) {
        if( event.$origin !== bind && !force ) {
          this.$postpone( bind, event )
        } else {
          this.$exec( bind, event )
        }
      }
    }
  }
}).$Constructor

//helpers -- maybe make into a seperate module 'shared'?
function exclude( property, key, base, stamp ) {
  var ignore = property._$ignoreStamp
  if( ignore ) {
    property._$ignoreStamp = null
    if( ignore === stamp ) {
      return true
    }
  }
}

function execPasson( property, bind, event, emitter ) {
  if( property[2] ) {
      property[0].apply(
      bind,
      [ event, emitter._$meta ].concat( property[2] )
    )
  } else {
    property[0].call( bind, event, emitter._$meta, property[1] )
  }
}

function generateId( base ) {
  return base._$id ? base._$id++ : (base._$id = 1)
}

function add( emitter, type, val, key, unique, event ) {
   if(!emitter[type]) {
      emitter.$setKey( type, {}, false )
   } else if( unique && emitter[type] ) {
    var isFn = typeof unique === 'function'
    if(isFn) {
       for(var i in emitter[type]) {
        if( unique.call( emitter, emitter[type][i], val) ) {
          return true
        }
      }
    } else {
      for( var i in emitter[type] ) {
        if( emitter[type][i] === val ) {
          return true
        }
      }
    }
  }

  if( emitter[type]._$parent !== emitter ) {
    emitter.$setKey( type, {}, false )
  }

  if(event) {
    val._$ignoreStamp = event.$stamp
  }

  emitter[type][key] = val
}

<|endoftext|>


<commit_before>import React from 'react';
import axios from 'axios';

class ActionControl extends React.Component {
	constructor(props){
  	super(props);
  	this.state = {
			id : props.id,
			url: props.url
		};

		this.edit = this.edit.bind(this)
		this.remove = this.remove.bind(this)
	}

	edit(){
		alert('Editing event')
	}

	remove(){
		const requestUrlWithParam = this.state.url + '/' + this.state.id;
		alert('Delete event using url ' + requestUrlWithParam)
		axios.delete(requestUrlWithParam).then(function(res) {

		});
	}

	render(){
		return (

				<button className='ActionControl-edit' onClick={this.edit}>EDIT</button>
				<button className='ActionControl-remove' onClick={this.remove}>X</button>

		)
	}
}

class Event extends React.Component {
	constructor(props){
  	super(props);
  	this.state = {
			data : props.data,
			key: props.key,
			url: props.url
		};
	}

	render(){
		const requestUrlWithParam = this.state.url + '/' + this.state.id;

		return (

{this.state.data.name}

{this.state.data.description}

{this.state.data.location}

{this.state.data.date}

				<ActionControl url={this.state.url} id={this.state.data.id}/>
				{requestUrlWithParam}

		)
	}
}

export default Event;
<commit_msg>Removed alerts after testing<commit_after>import React from 'react';
import axios from 'axios';

class ActionControl extends React.Component {
	constructor(props){
  	super(props);
  	this.state = {
			id : props.id,
			url: props.url
		};

		this.edit = this.edit.bind(this)
		this.remove = this.remove.bind(this)
	}

	edit(){

	}

	remove(){
		const requestUrlWithParam = this.state.url + '/' + this.state.id;
		axios.delete(requestUrlWithParam).then(function(res) {

		});
	}

	render(){
		return (

				<button className='ActionControl-edit' onClick={this.edit}>EDIT</button>
				<button className='ActionControl-remove' onClick={this.remove}>X</button>

		)
	}
}

class Event extends React.Component {
	constructor(props){
  	super(props);
  	this.state = {
			data : props.data,
			key: props.key,
			url: props.url
		};
	}

	render(){
		return (

{this.state.data.name}

{this.state.data.description}

{this.state.data.location}

{this.state.data.date}

				<ActionControl url={this.state.url} id={this.state.data.id}/>

		)
	}
}

export default Event;
<|endoftext|>