<commit_before>/*global defineSuite*/
defineSuite([
        'Scene/Globe',
        'Core/CesiumTerrainProvider',
        'Core/Ellipsoid',
        'Core/loadWithXhr',
        'Core/Rectangle',
        'Renderer/ClearCommand',
        'Scene/SingleTileImageryProvider',
        'Specs/createContext',
        'Specs/createFrameState',
        'Specs/destroyContext',
        'Specs/render'
    ], function(
        Globe,
        CesiumTerrainProvider,
        Ellipsoid,
        loadWithXhr,
        Rectangle,
        ClearCommand,
        SingleTileImageryProvider,
        createContext,
        createFrameState,
        destroyContext,
        render) {
    "use strict";
    /*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn,runs,waits,waitsFor*/

    describe('enableLighting', function() {
        var context;
        var frameState;
        var globe;

        beforeAll(function() {
            context = createContext();
        });

        afterAll(function() {
            destroyContext(context);
        });

        beforeEach(function() {
            frameState = createFrameState();
            globe = new Globe();
        });

        afterEach(function() {
            globe.destroy();
            loadWithXhr.load = loadWithXhr.defaultLoad;
        });

        function returnTileJson(path) {
            var oldLoad = loadWithXhr.load;
            loadWithXhr.load = function(url, responseType, method, data, headers, deferred, overrideMimeType) {
                if (url.indexOf('layer.json') >= 0) {
                    return loadWithXhr.defaultLoad(path, responseType, method, data, headers, deferred);
                } else {
                    return oldLoad(url, responseType, method, data, headers, deferred, overrideMimeType);
                }
            };
        }

        function returnVertexNormalTileJson() {
            return returnTileJson('Data/CesiumTerrainTileJson/VertexNormals.tile.json');
        }

        /**
         * Repeatedly calls update until the load queue is empty.  You must wrap any code to follow
         * this in a "runs" function.
         */
        function updateUntilDone(globe) {
            // update until the load queue is empty.
            waitsFor(function() {
                globe._surface._debug.enableDebugOutput = true;
                var commandList = [];
                globe.update(context, frameState, commandList);
                return globe._surface.tileProvider.ready && globe._surface._tileLoadQueue.length === 0 && globe._surface._debug.tilesWaitingForChildren === 0;
            }, 'updating to complete');
        }

        it('renders with enableLighting', function() {
            globe.enableLighting = true;

            var layerCollection = globe.imageryLayers;
            layerCollection.removeAll();
            layerCollection.addImageryProvider(new SingleTileImageryProvider({url : 'Data/Images/Red16x16.png'}));

            frameState.camera.viewRectangle(new Rectangle(0.0001, 0.0001, 0.0025, 0.0025), Ellipsoid.WGS84);

            updateUntilDone(globe);

            runs(function() {
                ClearCommand.ALL.execute(context);
                expect(context.readPixels()).toEqual([0, 0, 0, 0]);

                render(context, frameState, globe);
                expect(context.readPixels()).toNotEqual([0, 0, 0, 0]);
            });
        });

        it('renders terrain with enableLighting', function() {
            globe.enableLighting = true;

            var layerCollection = globe.imageryLayers;
            layerCollection.removeAll();
            layerCollection.addImageryProvider(new SingleTileImageryProvider({url : 'Data/Images/Red16x16.png'}));

            loadWithXhr.load = function(url, responseType, method, data, headers, deferred, overrideMimeType) {
                return loadWithXhr.defaultLoad('Data/CesiumTerrainTileJson/tile.vertexnormals.terrain', responseType, method, data, headers, deferred);
            };

            returnVertexNormalTileJson();

            var terrainProvider = new CesiumTerrainProvider({
                url : 'made/up/url',
                requestVertexNormals : true
            });

            globe.terrainProvider = terrainProvider;

            waitsFor(function() {
                return terrainProvider.ready;
            });

            frameState.camera.viewRectangle(new Rectangle(0.0001, 0.0001, 0.0025, 0.0025), Ellipsoid.WGS84);

            updateUntilDone(globe);

            runs(function() {
                ClearCommand.ALL.execute(context);
                expect(context.readPixels()).toEqual([0, 0, 0, 0]);

                render(context, frameState, globe);
                expect(context.readPixels()).toNotEqual([0, 0, 0, 0]);
            });
        });
    });
}, 'WebGL');<commit_msg>Revert unnecessary changes.<commit_after>/*global defineSuite*/
defineSuite([
        'Scene/Globe',
        'Core/CesiumTerrainProvider',
        'Core/defined',
        'Core/Ellipsoid',
        'Core/loadWithXhr',
        'Core/Rectangle',
        'Renderer/ClearCommand',
        'Scene/SingleTileImageryProvider',
        'Specs/createContext',
        'Specs/createFrameState',
        'Specs/destroyContext',
        'Specs/render'
    ], function(
        Globe,
        CesiumTerrainProvider,
        defined,
        Ellipsoid,
        loadWithXhr,
        Rectangle,
        ClearCommand,
        SingleTileImageryProvider,
        createContext,
        createFrameState,
        destroyContext,
        render) {
    "use strict";
    /*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn,runs,waits,waitsFor*/

    var context;
    var frameState;
    var globe;

    beforeAll(function() {
        context = createContext();
    });

    afterAll(function() {
        destroyContext(context);
    });

    beforeEach(function() {
        frameState = createFrameState();
        globe = new Globe();
    });

    afterEach(function() {
        globe.destroy();
        loadWithXhr.load = loadWithXhr.defaultLoad;
    });

    function returnTileJson(path) {
        var oldLoad = loadWithXhr.load;
        loadWithXhr.load = function(url, responseType, method, data, headers, deferred, overrideMimeType) {
            if (url.indexOf('layer.json') >= 0) {
                return loadWithXhr.defaultLoad(path, responseType, method, data, headers, deferred);
            } else {
                return oldLoad(url, responseType, method, data, headers, deferred, overrideMimeType);
            }
        };
    }

    function returnVertexNormalTileJson() {
        return returnTileJson('Data/CesiumTerrainTileJson/VertexNormals.tile.json');
    }

    /**
     * Repeatedly calls update until the load queue is empty.  You must wrap any code to follow
     * this in a "runs" function.
     */
    function updateUntilDone(globe) {
        // update until the load queue is empty.
        waitsFor(function() {
            globe._surface._debug.enableDebugOutput = true;
            var commandList = [];
            globe.update(context, frameState, commandList);
            return globe._surface.tileProvider.ready && !defined(globe._surface._tileLoadQueue.head) && globe._surface._debug.tilesWaitingForChildren === 0;
        }, 'updating to complete');
    }

    it('renders with enableLighting', function() {
        globe.enableLighting = true;

        var layerCollection = globe.imageryLayers;
        layerCollection.removeAll();
        layerCollection.addImageryProvider(new SingleTileImageryProvider({url : 'Data/Images/Red16x16.png'}));

        frameState.camera.viewRectangle(new Rectangle(0.0001, 0.0001, 0.0025, 0.0025), Ellipsoid.WGS84);

        updateUntilDone(globe);

        runs(function() {
            ClearCommand.ALL.execute(context);
            expect(context.readPixels()).toEqual([0, 0, 0, 0]);

            render(context, frameState, globe);
            expect(context.readPixels()).toNotEqual([0, 0, 0, 0]);
        });
    });

    it('renders terrain with enableLighting', function() {
        globe.enableLighting = true;

        var layerCollection = globe.imageryLayers;
        layerCollection.removeAll();
        layerCollection.addImageryProvider(new SingleTileImageryProvider({url : 'Data/Images/Red16x16.png'}));

        loadWithXhr.load = function(url, responseType, method, data, headers, deferred, overrideMimeType) {
            return loadWithXhr.defaultLoad('Data/CesiumTerrainTileJson/tile.vertexnormals.terrain', responseType, method, data, headers, deferred);
        };

        returnVertexNormalTileJson();

        var terrainProvider = new CesiumTerrainProvider({
            url : 'made/up/url',
            requestVertexNormals : true
        });

        globe.terrainProvider = terrainProvider;

        waitsFor(function() {
            return terrainProvider.ready;
        });

        frameState.camera.viewRectangle(new Rectangle(0.0001, 0.0001, 0.0025, 0.0025), Ellipsoid.WGS84);

        updateUntilDone(globe);

        runs(function() {
            ClearCommand.ALL.execute(context);
            expect(context.readPixels()).toEqual([0, 0, 0, 0]);

            render(context, frameState, globe);
            expect(context.readPixels()).toNotEqual([0, 0, 0, 0]);
        });
    });
}, 'WebGL');<|endoftext|>


<commit_before>var async = require('async');

var display = module.exports;

/**
 * The type() hook.
 */
display.type = function(types, callback) {
  var newTypes = {};

  newTypes['display'] = {
    title: 'Display',
    description: 'Displays.',
    fields: {
      name: {
        title: 'Name',
        type: 'text',
        required: true
      },
      title: {
        title: 'Title',
        type: 'text',
        required: true
      },
      layout: {
        title: 'Layout',
        type: 'reference',
        reference: {
          type: 'display-layout'
        }
      }
    },
    access: {
      'list': 'manage-displays',
      'load': true,
      'add': 'manage-displays',
      'edit': 'manage-displays',
      'delete': 'manage-displays'
    }
  };

  newTypes['display-layout'] = {
    title: 'Display layout',
    description: 'A layout to be used on displays.',
    fields: {
      name: {
        title: 'Name',
        type: 'text',
        required: true
      },
      title: {
        title: 'Title',
        type: 'text',
        required: true
      }
    },
    access: {
      'list': true,
      'load': true,
      'add': 'manage-displays',
      'edit': 'manage-displays',
      'delete': 'manage-displays'
    }
  };

  callback(null, newTypes);
};

display.display = function(displays, callback) {
  var types = this.application.types;
  // Add type display instances to display objects.
  async.each(Object.keys(types), function(typeName, next) {
    var typeSettings = types[typeName];
    if (typeSettings.displays) {
      for (var displayName in typeSettings.displays) {
        if (displayName in displays) {
          displays[displayName].instances = displays[displayName].instances || {};
          displays[displayName].instances[typeName] = typeSettings.displays[displayName];
        }
      }
    }
    next();
  }, function() {
    callback();
  });
};
<commit_msg>Reverting display layout type back to use a hyphen separated name.<commit_after>var async = require('async');

var display = module.exports;

/**
 * The type() hook.
 */
display.type = function(types, callback) {
  var newTypes = {};

  newTypes['display'] = {
    title: 'Display',
    description: 'Displays.',
    fields: {
      name: {
        title: 'Name',
        type: 'text',
        required: true
      },
      title: {
        title: 'Title',
        type: 'text',
        required: true
      },
      layout: {
        title: 'Layout',
        type: 'reference',
        reference: {
          type: 'displayLayout'
        }
      }
    },
    access: {
      'list': 'manage-displays',
      'load': true,
      'add': 'manage-displays',
      'edit': 'manage-displays',
      'delete': 'manage-displays'
    }
  };

  newTypes['displayLayout'] = {
    title: 'Display layout',
    description: 'A layout to be used on displays.',
    fields: {
      name: {
        title: 'Name',
        type: 'text',
        required: true
      },
      title: {
        title: 'Title',
        type: 'text',
        required: true
      }
    },
    access: {
      'list': true,
      'load': true,
      'add': 'manage-displays',
      'edit': 'manage-displays',
      'delete': 'manage-displays'
    }
  };

  callback(null, newTypes);
};

display.display = function(displays, callback) {
  var types = this.application.types;
  // Add type display instances to display objects.
  async.each(Object.keys(types), function(typeName, next) {
    var typeSettings = types[typeName];
    if (typeSettings.displays) {
      for (var displayName in typeSettings.displays) {
        if (displayName in displays) {
          displays[displayName].instances = displays[displayName].instances || {};
          displays[displayName].instances[typeName] = typeSettings.displays[displayName];
        }
      }
    }
    next();
  }, function() {
    callback();
  });
};
<|endoftext|>


<commit_before>charts.point = function(args) {
    this.args = args;

    this.init = function(args) {
        raw_data_transformation(args);
        process_point(args);
        init(args);
        x_axis(args);
        y_axis(args);
        return this;
    }

    this.markers = function() {
        markers(args);
        if (args.least_squares){
            add_ls(args);
        }
        // if (args.lowess){
        //     add_lowess(args);
        // }
        return this
    }

    this.mainPlot = function() {
        var svg = d3.select(args.target + ' svg');
        var g;

        // plot the points, pretty straight-forward
        g = svg.append('g')
            .classed('points', true);

        var pts = g.selectAll('circle')
            .data(args.data[0])
            .enter().append('svg:circle')
                .attr('cx', args.scalefns.xf)
                .attr('cy', args.scalefns.yf);

        if (args.color_accessor!=null){
            pts.attr('fill',   args.scalefns.color);
            pts.attr('stroke', args.scalefns.color);
        } else {
            pts.attr('fill',   '#0000ff');
            pts.attr('stroke', '#0000ff');
        }
        if (args.size_accessor!=null){
            pts.attr('r', args.scalefns.size);
        } else {
            pts.attr('r', 2);
        }
        var rug;
        if (args.x_rug){
            //var data = args.data[0].map(function(d){return d[args.x_accessor]});
            rug=g.selectAll('line.x_rug').data(args.data[0]).enter().append('svg:line')
                .attr('x1', args.scalefns.xf)
                .attr('x2', args.scalefns.xf)
                .attr('y1', args.height-args.top+args.buffer)
                .attr('y2', args.height-args.top)
                .attr('opacity', .3);
            if (args.color_accessor){
                rug.attr('stroke', args.scalefns.color);
            } else {
                rug.attr('stroke', 'black');
            }
        }
        if (args.y_rug){
            rug=g.selectAll('line.y_rug').data(args.data[0]).enter().append('svg:line')
                .attr('x1', args.left+1)
                .attr('x2', args.left+args.buffer)
                .attr('y1', args.scalefns.yf)
                .attr('y2', args.scalefns.yf)
                .attr('stroke', 'black')
                .attr('opacity', .2);
            if (args.color_accessor){
                rug.attr('stroke', args.scalefns.color);
            } else {
                rug.attr('stroke', 'black');
            }
        }

        return this;
    }

    this.rollover = function() {
        var svg = d3.select(args.target + ' svg');

        var paths = svg.append('g')
            .attr('id', 'point-paths');

        //remove rollover text if it already exists
        if($(args.target + ' svg .active_datapoint').length > 0) {
            $(args.target + ' svg .active_datapoint').remove();
        }

        //add rollover text
        svg.append('text')
            .attr('class', 'active_datapoint')
            .attr('xml:space', 'preserve')
            .attr('x', args.width - args.right)
            .attr('y', args.top / 2)
            .attr('text-anchor', 'end');

        var voronoi = d3.geom.voronoi()
            .x(args.scalefns.xf)
            .y(args.scalefns.yf)
            .clipExtent([[args.buffer, args.buffer], [args.width - args.buffer, args.height - args.buffer]]);

        paths.selectAll('path')
            .data(voronoi(args.data[0]))
            .enter().append('path')
                .attr('d', function(d) {
                    if(d == undefined) return;
                    return 'M' + d.join(',') + 'Z';
                })
                .attr('class', function(d,i) {
                    return 'path-' + i;
                })
                .attr('clip-path', function(d,i) {
                    return 'url(#clip-'+i+')';
                })
                .style('fill-opacity', 0)
                .on('mouseover', this.rolloverOn(args))
                .on('mouseout', this.rolloverOff(args));

        return this;
    }

    this.rolloverOn = function(args) {
        var svg = d3.select(args.target + ' svg');

        return function(d, i){
            svg.selectAll('.points circle')
                .classed('unselected', true);

            var fmt = d3.time.format('%b %e, %Y');

            if (args.format == 'count') {
                var num = function(d_) {
                    var is_float = d_ % 1 != 0;
                    var n = d3.format("0,000");
                    d_ = is_float ? d3.round(d_, args.decimals) : d_;
                    return n(d_);
                }
            }
            else {
                var num = function(d_) {
                    var fmt_string = (args.decimals ? '.' + args.decimals : '' ) + '%';
                    var n = d3.format(fmt_string);
                    return n(d_);
                }
            }

            //highlight active point
            var pts = svg.selectAll('.points circle')
                .filter(function(g,j){return i == j})
                .classed('unselected', false)
                .classed('selected', true);

            if (args.size_accessor){
                pts.attr('r', function(di){return args.scalefns.size(di)+1});
            } else {
                pts.attr('r', 3);
            }

            //update rollover text
            if (args.show_rollover_text) {
                svg.select('.active_datapoint')
                    .text(function() {
                        if(args.time_series) {
                            var dd = new Date(+d['point'][args.x_accessor]);
                            dd.setDate(dd.getDate());

                            return fmt(dd) + '  ' + args.yax_units
                                + num(d['point'][args.y_accessor]);
                        }
                        else {
                            return args.x_accessor + ': ' + num(d['point'][args.x_accessor])
                                + ', ' + args.y_accessor + ': ' + args.yax_units
                                + num(d['point'][args.y_accessor]);
                        }
                    });
            }

            if(args.rollover_callback) {
                args.rollover_callback(d, i);
            }
        }
    }

    this.rolloverOff = function(args) {
        var svg = d3.select(args.target + ' svg');

        return function(d,i){
            //reset active point
            var pts = svg.selectAll('.points circle')
                .classed('unselected', false)
                .classed('selected', false);

            if (args.size_accessor){
                pts.attr('r', args.scalefns.size);
            } else {
                pts.attr('r', 2);
            }

            //reset active data point text
            svg.select('.active_datapoint')
                .text('');
        }
    }

    this.update = function(args) {
        return this;
    }

    this.init(args);

    return this;
}
<commit_msg>Fix issue #157<commit_after>charts.point = function(args) {
    this.args = args;

    this.init = function(args) {
        raw_data_transformation(args);
        process_point(args);
        init(args);
        x_axis(args);
        y_axis(args);
        return this;
    }

    this.markers = function() {
        markers(args);
        if (args.least_squares){
            add_ls(args);
        }
        // if (args.lowess){
        //     add_lowess(args);
        // }
        return this
    }

    this.mainPlot = function() {
        var svg = d3.select(args.target + ' svg');
        var g;

        // plot the points, pretty straight-forward
        g = svg.append('g')
            .classed('points', true);

        var pts = g.selectAll('circle')
            .data(args.data[0])
            .enter().append('svg:circle')
                .attr('cx', args.scalefns.xf)
                .attr('cy', args.scalefns.yf);

        if (args.color_accessor!=null){
            pts.attr('fill',   args.scalefns.color);
            pts.attr('stroke', args.scalefns.color);
        } else {
            pts.attr('fill',   '#0000ff');
            pts.attr('stroke', '#0000ff');
        }
        if (args.size_accessor!=null){
            pts.attr('r', args.scalefns.size);
        } else {
            pts.attr('r', 2);
        }
        var rug;
        if (args.x_rug){
            //var data = args.data[0].map(function(d){return d[args.x_accessor]});
            rug=g.selectAll('line.x_rug').data(args.data[0]).enter().append('svg:line')
                .attr('x1', args.scalefns.xf)
                .attr('x2', args.scalefns.xf)
                .attr('y1', args.height-args.top+args.buffer)
                .attr('y2', args.height-args.top)
                .attr('opacity', .3);
            if (args.color_accessor){
                rug.attr('stroke', args.scalefns.color);
            } else {
                rug.attr('stroke', 'black');
            }
        }
        if (args.y_rug){
            rug=g.selectAll('line.y_rug').data(args.data[0]).enter().append('svg:line')
                .attr('x1', args.left+1)
                .attr('x2', args.left+args.buffer)
                .attr('y1', args.scalefns.yf)
                .attr('y2', args.scalefns.yf)
                .attr('stroke', 'black')
                .attr('opacity', .2);
            if (args.color_accessor){
                rug.attr('stroke', args.scalefns.color);
            } else {
                rug.attr('stroke', 'black');
            }
        }

        return this;
    }

    this.rollover = function() {
        var svg = d3.select(args.target + ' svg');

        var paths = svg.append('g')
            .attr('id', 'point-paths');

        //remove rollover text if it already exists
        if($(args.target + ' svg .active_datapoint').length > 0) {
            $(args.target + ' svg .active_datapoint').remove();
        }

        //add rollover text
        svg.append('text')
            .attr('class', 'active_datapoint')
            .attr('xml:space', 'preserve')
            .attr('x', args.width - args.right)
            .attr('y', args.top / 2)
            .attr('text-anchor', 'end');

        var voronoi = d3.geom.voronoi()
            .x(args.scalefns.xf)
            .y(args.scalefns.yf)
            .clipExtent([[args.buffer, args.buffer], [args.width - args.buffer, args.height - args.buffer]]);

        paths.selectAll('path')
            .data(voronoi(args.data[0]))
            .enter().append('path')
                .attr('d', function(d) {
                    if(d == undefined) return;
                    return 'M' + d.join(',') + 'Z';
                })
                .attr('class', function(d,i) {
                    return 'path-' + i;
                })
                .attr('clip-path', function(d,i) {
                    return 'url(#clip-'+i+')';
                })
                .style('fill-opacity', 0)
                .on('mouseover', this.rolloverOn(args))
                .on('mouseout', this.rolloverOff(args));

        return this;
    }

    this.rolloverOn = function(args) {
        var svg = d3.select(args.target + ' svg');

        return function(d, i){
            svg.selectAll('.points circle')
                .classed('selected', false);

            //highlight active point
            var pts = svg.selectAll('.points circle.path-' + i)
                .classed('selected', true);

            if (args.size_accessor){
                pts.attr('r', function(di){return args.scalefns.size(di)+1});
            } else {
                pts.attr('r', 3);
            }

            //trigger mouseover on all points for this class name in .linked charts
            if(args.linked && !globals.link) {
                globals.link = true;

                //trigger mouseover on matching point in .linked charts
                d3.selectAll('.voronoi .path-' + i)
                    .each(function() {
                        d3.select(this).on('mouseover')(d,i);
                })
            }

            var fmt = d3.time.format('%b %e, %Y');
            if (args.format == 'count') {
                var num = function(d_) {
                    var is_float = d_ % 1 != 0;
                    var n = d3.format("0,000");
                    d_ = is_float ? d3.round(d_, args.decimals) : d_;
                    return n(d_);
                }
            }
            else {
                var num = function(d_) {
                    var fmt_string = (args.decimals ? '.' + args.decimals : '' ) + '%';
                    var n = d3.format(fmt_string);
                    return n(d_);
                }
            }

            //update rollover text
            if (args.show_rollover_text) {
                svg.select('.active_datapoint')
                    .text(function() {
                        if(args.time_series) {
                            var dd = new Date(+d['point'][args.x_accessor]);
                            dd.setDate(dd.getDate());

                            return fmt(dd) + '  ' + args.yax_units
                                + num(d['point'][args.y_accessor]);
                        }
                        else {
                            return args.x_accessor + ': ' + num(d['point'][args.x_accessor])
                                + ', ' + args.y_accessor + ': ' + args.yax_units
                                + num(d['point'][args.y_accessor]);
                        }
                    });
            }

            if(args.rollover_callback) {
                args.rollover_callback(d, i);
            }
        }
    }

    this.rolloverOff = function(args) {
        var svg = d3.select(args.target + ' svg');

        return function(d,i){
            if(args.linked && globals.link) {
                globals.link = false;

                d3.selectAll('.voronoi .path-' + i)
                    .each(function() {
                        d3.select(this).on('mouseout')(d,i);
                })
            }

            //reset active point
            var pts = svg.selectAll('.points circle')
                .classed('unselected', false)
                .classed('selected', false);

            if (args.size_accessor){
                pts.attr('r', args.scalefns.size);
            } else {
                pts.attr('r', 3);
            }

            //reset active data point text
            svg.select('.active_datapoint')
                .text('');
        }
    }

    this.update = function(args) {
        return this;
    }

    this.init(args);

    return this;
}
<|endoftext|>


<commit_before>var enemyLayer = new Kinetic.Layer();
var mushroom;
var enemyImageObj = new Image();

enemyImageObj.onload = function () {
    mushroom = new Kinetic.Sprite({
        x: 550,
        y: 512,
        image: enemyImageObj,
        animation: 'stay',
        animations: {
            stay: [
              // x, y, width, height (2 frames)
              0, 6, 28, 29,
              52, 6, 28, 29,
            ],
            smashed: [
                103, 6, 27, 31
            ]
        },
        frameRate: 7,
        frameIndex: 0
    });

    // add the shape to the layer
    enemyLayer.add(mushroom);

    // add the layer to the stage
    stage.add(enemyLayer);

    // start sprite animation
    mushroom.start();

    mushroomMoving();

    function mushroomMoving() {
        var boundary = 670;
        var timer = 0;
        var isPassed = false;

        timer = setInterval(function () {
            if (mushroom.animation() === 'smashed') {
                clearInterval(timer);
            }
            if (mushroom.getAttr('x') < boundary) {
                mushroom.move({
                    x: 5
                })
                if (mushroom.getAttr('x') === boundary - 10) {
                    boundary = 0;
                }
                if (mushroom.getAttr('x') === mario.getAttr('x') - 10) {
                    clearInterval(timer);
                }
            } else {
                mushroom.move({
                    x: -5
                })
                if (mushroom.getAttr('x') === boundary + 10) {
                    boundary = 700;
                }
            }
            if (mushroom.getAttr('x') === mario.getAttr('x') + 40 && isPassed === false) {
                clearInterval(timer);
            }
            if (mushroom.getAttr('x') < mario.getAttr('x')) {
                isPassed = true;
            }

        }, 50)
    }
};
enemyImageObj.src = 'Images/mushroom-new.png';
<commit_msg>Added another enemy.<commit_after>var enemyLayer = new Kinetic.Layer(),
    firstMushroom,
    SecondMushroom,
    imageSrc = 'Images/mushroom-new.png';

var firstMushroomImage = new Image();
var SecondMushroomImage = new Image();

firstMushroomImage.onload = function () {
    firstMushroom = new Kinetic.Sprite({
        x: 550,
        y: 512,
        image: firstMushroomImage,
        animation: 'stay',
        animations: {
            stay: [
              // x, y, width, height (2 frames)
              0, 6, 28, 29,
              52, 6, 28, 29,
            ],
            smashed: [
                103, 6, 27, 31
            ]
        },
        frameRate: 7,
        frameIndex: 0
    });

    // add the shape to the layer
    enemyLayer.add(firstMushroom);

    // add the layer to the stage
    stage.add(enemyLayer);

    // start sprite animation
    firstMushroom.start();

    Move(firstMushroom, 0, 670);
};
firstMushroomImage.src = imageSrc;

SecondMushroomImage.onload = function () {
    SecondMushroom = new Kinetic.Sprite({
        x: 360,
        y: 512,
        image: SecondMushroomImage,
        animation: 'stay',
        animations: {
            stay: [
              // x, y, width, height (2 frames)
              0, 6, 28, 29,
              52, 6, 28, 29,
            ],
            smashed: [
                103, 6, 27, 31
            ]
        },
        frameRate: 7,
        frameIndex: 0
    });

    // add the shape to the layer
    enemyLayer.add(SecondMushroom);

    // add the layer to the stage
    stage.add(enemyLayer);

    // start sprite animation
    SecondMushroom.start();

    Move(SecondMushroom, 0, 670);
};
SecondMushroomImage.src = imageSrc;

function Move(mushroom, startBorder, endBorder) {
    var timer = 0;
    var isPassed = false;
    var boundary = endBorder;

    timer = setInterval(function () {
        if (mushroom.animation() === 'smashed') {
            clearInterval(timer);
        }
        if (mushroom.getAttr('x') < boundary) {
            mushroom.move({
                x: 5
            })
            if (mushroom.getAttr('x') === boundary - 10) {
                boundary = startBorder;
            }
            if ((mushroom.getAttr('x') === mario.getAttr('x') - 10) && (mushroom.getAttr('y') === mario.getAttr('y') + 124))  {
                clearInterval(timer);
            }
        } else {
            mushroom.move({
                x: -5
            })
            if (mushroom.getAttr('x') === startBorder + 10) {
                boundary = endBorder;
            }
        }
        if (mushroom.getAttr('x') === mario.getAttr('x') + 40 && (mushroom.getAttr('y') === mario.getAttr('y') + 124) && isPassed === false) {
            clearInterval(timer);
        }
        if (mushroom.getAttr('x') < mario.getAttr('x')) {
            isPassed = true;
        }
    }, 50)
}

var enemies = [{
    type: 'firstMushroom',
    x: 550,
    y: 512,
    widht: 28,
    height: 29
}, {
    type: 'SecondMushroom',
    x: 440,
    y: 512,
    widht: 28,
    height: 29
}]

<|endoftext|>


<commit_before>'use babel';

import { CompositeDisposable } from 'atom';
import { requirePackages } from 'atom-utils';

export default class ExtendedBase {
  constructor() {
    // Create root element
    this.element = document.createElement('div');
    this.element.classList.add('tree-view-extended');

    this.configSubs = new CompositeDisposable();
  }

  createObservers({ stickyKey }) {
    const fullStickyKey = `tree-view-extended.${stickyKey}`;

    this.configSubs.add(atom.config.observe(fullStickyKey, (isSticky) => {
      this.isSticky = isSticky;
      if (this.isShowing()) {
        this.hide();
        this.show();
      }
    }));

    this.configSubs.add(atom.config.observe('tree-view-extended.maxHeight', (maxHeight) => {
      // Only apply a max height if the view is sticky.
      if (this.isSticky) {
        this.element.style.maxHeight = maxHeight > 0 ? `${maxHeight}px` : 'none';
      }
    }));
  }

  // Tear down any state and detach
  destroy() {
    this.element.remove();
    this.configSubs.dispose();
  }

  isShowing() {
    return this.element.parentElement != null;
  }

	toggle() {
		if (this.isShowing()) {
			this.hide();
		} else {
			this.show();
		}
	}

	hide() {
		this.element.remove();
	}

	show() {
		requirePackages('tree-view').then(([treeView]) => {
      const treeViewBackground = treeView.treeView.find('.tree-view').css('background');
      treeView.treeView.find('.tree-view-scroller').css('background', treeViewBackground);

      if (this.isSticky) {
        treeView.treeView.prepend(this.element);
      } else {
        const parentElement = treeView.treeView.element.querySelector('.tree-view-scroller')
        parentElement.insertBefore(this.element, parentElement.firstChild)
      }
		});
	}
}
<commit_msg>fix(ExtendedBase): When going from sticky to non-sticky set max-height appropriately.<commit_after>'use babel';

import { CompositeDisposable } from 'atom';
import { requirePackages } from 'atom-utils';

export default class ExtendedBase {
  constructor() {
    // Create root element
    this.element = document.createElement('div');
    this.element.classList.add('tree-view-extended');

    this.configSubs = new CompositeDisposable();
  }

  createObservers({ stickyKey }) {
    const fullStickyKey = `tree-view-extended.${stickyKey}`;
    const maxHeightFullKey = 'tree-view-extended.maxHeight';

    const updateMaxHeight = (maxHeight = atom.config.get(maxHeightFullKey)) => {
      // If it's not sticky then always show all items.
      if (!this.isSticky) {
        this.element.style.maxHeight = 'none';
        return;
      }

      this.element.style.maxHeight = maxHeight > 0 ? `${maxHeight}px` : 'none';
    };

    this.configSubs.add(atom.config.observe(fullStickyKey, (isSticky) => {
      this.isSticky = isSticky;
      if (this.isShowing()) {
        this.hide();
        this.show();
      }
      updateMaxHeight();
    }));

    this.configSubs.add(atom.config.observe(maxHeightFullKey, updateMaxHeight));
  }

  // Tear down any state and detach
  destroy() {
    this.element.remove();
    this.configSubs.dispose();
  }

  isShowing() {
    return this.element.parentElement != null;
  }

	toggle() {
		if (this.isShowing()) {
			this.hide();
		} else {
			this.show();
		}
	}

	hide() {
		this.element.remove();
	}

	show() {
		requirePackages('tree-view').then(([treeView]) => {
      const treeViewBackground = treeView.treeView.find('.tree-view').css('background');
      treeView.treeView.find('.tree-view-scroller').css('background', treeViewBackground);

      if (this.isSticky) {
        treeView.treeView.prepend(this.element);
      } else {
        const parentElement = treeView.treeView.element.querySelector('.tree-view-scroller')
        parentElement.insertBefore(this.element, parentElement.firstChild)
      }
		});
	}
}
<|endoftext|>


<commit_before>var five = require('johnny-five');

var board = new five.Board({ port: '/dev/ttyS0'});
board.on('ready', function () {
  console.log('Board is ready');
});

var controllers = {};

var addController = function (path) {
  // 1. Require the controller
  var controller = require(path)(five);
  console.log('new controller added');
  console.log(controller);

  // 2. Add the controller to controller list
  controllers[controller.id] = controller;
};

var execute = function(controllerID, functionName) {
  console.log(controllerID, functionName);

  console.log(controllers[controllerID]);
  console.log(controllers[controllerID][functionName]);

  controllers[controllerID][functionName]();
};

// var listControllers = function () {

// };

module.exports = {
  addController: addController,
  execute: execute,
  board: board,
};<commit_msg>refactor all the way<commit_after>var five = require('johnny-five');

var board = new five.Board({ port: '/dev/ttyS0'});
board.on('ready', function () {
  console.log('Board is ready');
});

var controllers = {};

var addController = function (path) {
  // 1. Require the controller
  var controller = require(path)(five);
  console.log('new controller added');
  console.log(controller);

  // 2. Add the controller to controller list
  controllers[controller.id] = controller;
};

var execute = function(controllerID, functionName) {
  console.log(controllerID, functionName);

  console.log(controllers[controllerID]);
  console.log(controllers[controllerID][functionName]);

  controllers[controllerID][functionName]();
};

// var listControllers = function () {

// };

module.exports = {
  addController: addController,
  execute: execute,
  board: board,
};<|endoftext|>


<commit_before>var request = require("request"),
    crypto = require("crypto"),
    querystring = require("querystring");

var BTCE = function(apiKey, secret, nonceGenerator) {
  var self = this;
  self.url = "https://btc-e.com/tapi";
  self.publicApiUrl = "https://btc-e.com/api/2/";
  self.apiKey = apiKey;
  self.secret = secret;
  self.nonce = nonceGenerator;

  self.makeRequest = function(method, params, callback) {
    var queryString,
        sign,
        headers;

    if(!self.apiKey || !self.secret) {
      callback(new Error("Must provide API key and secret to use the trade API."));
      return;
    }

    // If the user provided a function for generating the nonce, then use it.
    if(self.nonce) {
      params.nonce = self.nonce();
    } else {
      params.nonce = Math.round((new Date()).getTime() / 1000);
    }

    params.method = method;
    queryString = querystring.stringify(params);

    sign = crypto.createHmac("sha512", self.secret).update(new Buffer(queryString)).digest('hex').toString();
    headers = {
      'Sign': sign,
      'Key': self.apiKey
    };

    request({ url: self.url, method: "POST", form: params, headers: headers, timeout: 5000, strictSSL: false }, function(err, response, body) {
      if(err || response.statusCode !== 200) {
        return callback(new Error(err ? err : response.statusCode));
      }

      var result;
      try {
        result = JSON.parse(body);
      } catch(error) {
        return callback(new Error(error));
      }

      if(result.success === 0) {
        return callback(new Error(result.error));
      }

      callback(null, result['return']);
    });
  };

  self.makePublicApiRequest = function(pair, method, callback) {
    request({ url: self.publicApiUrl + pair + '/' + method, timeout: 5000, strictSSL: false }, function(err, response, body) {
      if(err || response.statusCode !== 200) {
        return callback(new Error(err ? err : response.statusCode));
      }

      var result;
      try {
        result = JSON.parse(body);
      } catch(error) {
        return callback(new Error(error));
      }

      if(result.error) {
        return callback(new Error(result.error));
      }

      callback(null, result);
    });
  };

  self.getInfo = function(callback) {
    self.makeRequest('getInfo', {}, callback);
  };

  self.transHistory = function(params, callback) {
    self.makeRequest('TransHistory', params, callback);
  };

  self.tradeHistory = function(params, callback) {
    self.makeRequest('TradeHistory', params, callback);
  };

  self.orderList = function(params, callback) {
    self.makeRequest('OrderList', params, callback);
  };

  self.activeOrders = function(pair, callback) {
    if (!callback) {
      callback = pair;
      pair = null;
    }

    self.makeRequest('ActiveOrders', {pair: pair}, callback);
  };

  self.trade = function(pair, type, rate, amount, callback) {
    self.makeRequest('Trade', {
      'pair': pair,
      'type': type,
      'rate': rate,
      'amount': amount
    }, callback);
  };

  self.cancelOrder = function(orderId, callback) {
    self.makeRequest('CancelOrder', {'order_id': orderId}, callback);
  };

  self.ticker = function(pair, callback) {
    self.makePublicApiRequest(pair, 'ticker', callback);
  };

  self.trades = function(pair, callback) {
    self.makePublicApiRequest(pair, 'trades', callback);
  };

  self.depth = function(pair, callback) {
    self.makePublicApiRequest(pair, 'depth', callback);
  };

  self.fee = function(pair, callback) {
    self.makePublicApiRequest(pair, 'fee', callback);
  };
};

module.exports = BTCE;
<commit_msg>switch from defining functions directly on BTCE object in constructor to doing that on the prototype<commit_after>var request = require("request"),
    crypto = require("crypto"),
    querystring = require("querystring");

var BTCE = function(apiKey, secret, nonceGenerator) {
  this.url = "https://btc-e.com/tapi";
  this.publicApiUrl = "https://btc-e.com/api/2/";
  this.apiKey = apiKey;
  this.secret = secret;
  this.nonce = nonceGenerator;
};

BTCE.prototype.makeRequest = function(method, params, callback) {
  var queryString,
      sign,
      headers,
      self = this;

  if(!self.apiKey || !self.secret) {
    callback(new Error("Must provide API key and secret to use the trade API."));
    return;
  }

  // If the user provided a function for generating the nonce, then use it.
  if(self.nonce) {
    params.nonce = self.nonce();
  } else {
    params.nonce = Math.round((new Date()).getTime() / 1000);
  }

  params.method = method;
  queryString = querystring.stringify(params);

  sign = crypto.createHmac("sha512", self.secret).update(new Buffer(queryString)).digest('hex').toString();
  headers = {
    'Sign': sign,
    'Key': self.apiKey
  };

  request({ url: self.url, method: "POST", form: params, headers: headers, timeout: 5000, strictSSL: false }, function(err, response, body) {
    if(err || response.statusCode !== 200) {
      return callback(new Error(err ? err : response.statusCode));
    }

    var result;
    try {
      result = JSON.parse(body);
    } catch(error) {
      return callback(new Error(error));
    }

    if(result.success === 0) {
      return callback(new Error(result.error));
    }

    callback(null, result['return']);
  });
};

BTCE.prototype.makePublicApiRequest = function(pair, method, callback) {
  var self = this;
  request({ url: self.publicApiUrl + pair + '/' + method, timeout: 5000, strictSSL: false }, function(err, response, body) {
    if(err || response.statusCode !== 200) {
      return callback(new Error(err ? err : response.statusCode));
    }

    var result;
    try {
      result = JSON.parse(body);
    } catch(error) {
      return callback(new Error(error));
    }

    if(result.error) {
      return callback(new Error(result.error));
    }

    callback(null, result);
  });
};

BTCE.prototype.getInfo = function(callback) {
  this.makeRequest('getInfo', {}, callback);
};

BTCE.prototype.transHistory = function(params, callback) {
  this.makeRequest('TransHistory', params, callback);
};

BTCE.prototype.tradeHistory = function(params, callback) {
  this.makeRequest('TradeHistory', params, callback);
};

BTCE.prototype.orderList = function(params, callback) {
  this.makeRequest('OrderList', params, callback);
};

BTCE.prototype.activeOrders = function(pair, callback) {
  if (!callback) {
    callback = pair;
    pair = null;
  }

  this.makeRequest('ActiveOrders', {pair: pair}, callback);
};

BTCE.prototype.trade = function(pair, type, rate, amount, callback) {
  this.makeRequest('Trade', {
    'pair': pair,
    'type': type,
    'rate': rate,
    'amount': amount
  }, callback);
};

BTCE.prototype.cancelOrder = function(orderId, callback) {
  this.makeRequest('CancelOrder', {'order_id': orderId}, callback);
};

BTCE.prototype.ticker = function(pair, callback) {
  this.makePublicApiRequest(pair, 'ticker', callback);
};

BTCE.prototype.trades = function(pair, callback) {
  this.makePublicApiRequest(pair, 'trades', callback);
};

BTCE.prototype.depth = function(pair, callback) {
  this.makePublicApiRequest(pair, 'depth', callback);
};

BTCE.prototype.fee = function(pair, callback) {
  this.makePublicApiRequest(pair, 'fee', callback);
};

module.exports = BTCE;
<|endoftext|>


<commit_before>/**
 * easy-sketch.js
 *
 * @link https://github.com/brian978/easy-sketch.js
 * @copyright Copyright (c) 2013
 * @license Creative Commons Attribution-ShareAlike 3.0
 */

var EasySketch = EasySketch || {};

EasySketch.EventManager = function (binding) {
    "use strict";
    var $this = this;

    this.manager = $(binding);

    return {
        /**
         *
         * @param {String} eventType
         * @param {Array|Object=null} params
         */
        trigger: function (eventType, params) {
            $this.manager.trigger(eventType, params || null);
        },
        /**
         *
         * @param {String} eventType
         * @param {Function} handler
         * @param {Array=null} data Some data that can be passed to the function call
         */
        attach: function (eventType, handler, data) {
            $this.manager.on(eventType, data || null, handler);
        },
        /**
         *
         * @param {String} eventType
         * @param {Function} handler
         */
        detach: function (eventType, handler) {
            $this.manager.unbind(eventType, handler);
        }
    };
};

/**
 *
 * @param {*} element
 * @param {Object=null} options
 * @constructor
 */
EasySketch.Sketch = function (element, options) {
    "use strict";

    this.lastMouse = {x: 0, y: 0};
    this.disabled = false;
    this.binded = false;
    this.drawing = false;
    this.events = new EasySketch.EventManager(this);
    this.eraser = false;
    this.canvas = this.__createCanvas(element);
    this.context = this.canvas.get(0).getContext("2d");

    this.options = {
        color: "#000000",
        width: 5,
        bindingObject: null,
        autoBind: true
    };

    this.listeners = {
        start: this.__startDrawing.bind(this),
        draw: this.__draw.bind(this),
        stop: this.__stopDrawing.bind(this)
    };

    if (options) {
        this.setOptions(options);
    }

    if (this.options.autoBind === true) {
        this.attachListeners();
    }
};

// Listened events
EasySketch.Sketch.START_PAINTING_EVENT = 'sketch.start';
EasySketch.Sketch.PAINT_EVENT = 'sketch.paint';
EasySketch.Sketch.STOP_PAINTING_EVENT = 'sketch.stop';

// Triggered events
EasySketch.Sketch.NOTIFY_START_EVENT = 'notify.start';
EasySketch.Sketch.NOTIFY_PAINT_EVENT = 'notify.paint';
EasySketch.Sketch.NOTIFY_STOP_EVENT = 'notify.stop';

/**
 *
 * @param options
 * @returns {EasySketch.Sketch}
 */
EasySketch.Sketch.prototype.setOptions = function (options) {
    "use strict";

    this.options = $.extend(this.options, options || {});

    return this;
};

/**
 * Returns the value of an option if it exists and null (if this isn't changed) if it doesn't
 *
 * @param {String} name
 * @param {*=null} defaultValue
 * @returns {*}
 */
EasySketch.Sketch.prototype.getOption = function (name, defaultValue) {
    defaultValue = defaultValue || null;

    if (this.options.hasOwnProperty(name)) {
        return this.options[name];
    }

    return defaultValue;
};

/**
 *
 * @returns {EventManager|*}
 */
EasySketch.Sketch.prototype.getEventManager = function () {
    "use strict";
    return this.events;
};

/**
 *
 * @param {*} element
 * @returns {*}
 * @private
 */
EasySketch.Sketch.prototype.__createCanvas = function (element) {
    "use strict";
    var canvas;
    var elementType = typeof element;

    switch (elementType) {
        case "string":
            if (element.indexOf('#') === 0) {
                canvas = $(element);
            } else if (element.indexOf('.') === -1) {
                canvas = $("#" + element);
            }
            break;

        case "object":
            if (element instanceof jQuery) {
                canvas = element;
            } else {
                canvas = $(element);
            }
            break;
    }

    return canvas;
};

/**
 *
 * @returns {EasySketch.Sketch}
 */
EasySketch.Sketch.prototype.attachListeners = function () {
    "use strict";

    if (this.binded === true) {
        return this;
    }

    this.binded = true;

    // Selecting the object to bind on
    var bindingObject;
    if (this.getOption("bindingObject") !== null) {
        bindingObject = this.options["bindingObject"];
    } else {
        bindingObject = this.canvas;
    }

    // Canvas listeners
    bindingObject.on('mousedown touchstart', this.listeners.start);
    bindingObject.on('mousemove touchmove', this.listeners.draw);
    bindingObject.on('mouseup mouseleave mouseout touchend touchcancel', this.listeners.stop);

    // Event manager listeners
    this.events.attach(EasySketch.Sketch.START_PAINTING_EVENT, this.listeners.start);
    this.events.attach(EasySketch.Sketch.PAINT_EVENT, this.listeners.draw);
    this.events.attach(EasySketch.Sketch.STOP_PAINTING_EVENT, this.listeners.stop);

    return this;
};

/**
 * Listeners can also be detached if this is required
 *
 * @returns {EasySketch.Sketch}
 */
EasySketch.Sketch.prototype.detachListeners = function () {
    "use strict";

    if (this.binded === false) {
        return this;
    }

    this.binded = false;

    // Selecting the object to bind on
    var bindingObject;
    if (this.getOption("bindingObject") !== null) {
        bindingObject = this.options["bindingObject"];
    } else {
        bindingObject = this.canvas;
    }

    // Canvas listeners
    bindingObject.off('mousedown touchstart', this.listeners.start);
    bindingObject.off('mousemove touchmove', this.listeners.draw);
    bindingObject.off('mouseup mouseleave mouseout touchend touchcancel', this.listeners.stop);

    // Event manager listeners
    this.events.detach(EasySketch.Sketch.START_PAINTING_EVENT, this.listeners.start);
    this.events.detach(EasySketch.Sketch.PAINT_EVENT, this.listeners.draw);
    this.events.detach(EasySketch.Sketch.STOP_PAINTING_EVENT, this.listeners.stop);

    return this;
};

/**
 *
 * @returns {number}
 */
EasySketch.Sketch.prototype.getScale = function () {
    var prefixes = ["-moz", "-webkit", "-o", "-ms"];
    var property = null;
    var propertyName = "";
    var canvasStyle = this.canvas[0].style;
    var scale = 1;

    // Determining the property to use
    for (var i = 0; i < prefixes.length; i++) {
        propertyName = prefixes[i] + "-transform";
        if (propertyName in canvasStyle) {
            property = propertyName;
            break;
        }
    }

    var matrix = String(this.canvas.css(property));
    if (matrix != "none") {
        var regex = new RegExp("([0-9.-]+)", "g");
        var matches = matrix.match(regex);
        scale = matches[0];
    }

    return scale;
};

/**
 *
 * @param {Event} e
 * @returns {{x: Number, y: Number}}
 */
EasySketch.Sketch.prototype.getPointerPosition = function (e) {
    "use strict";

    var $this = this;
    var scale = this.getScale();

    return {
        x: Math.ceil((e.pageX - $this.canvas.offset().left) / scale),
        y: Math.ceil((e.pageY - $this.canvas.offset().top) / scale)
    }
};

/**
 *
 * @param {Boolean} value
 * @returns {EasySketch.Sketch}
 */
EasySketch.Sketch.prototype.enableEraser = function (value) {
    "use strict";
    this.eraser = value;

    return this;
};

/**
 *
 * @returns {EasySketch.Sketch}
 * @private
 */
EasySketch.Sketch.prototype.__contextSetup = function () {
    // Saving first to avoid changing other stuff
    this.context.save();

    // Applying our requirements
    this.context.strokeStyle = this.options.color;
    this.context.lineWidth = this.options.width;
    this.context.lineCap = "round";
    this.context.lineJoin = "round";

    return this;
};

/**
 *
 * @returns {EasySketch.Sketch}
 * @private
 */
EasySketch.Sketch.prototype.__contextRestore = function () {
    this.context.restore();

    return this;
};

/**
 *
 * @param {Event=null} e
 * @param {Object=null} pos This is like a virtual mouse position when triggering this using the event manager
 * @returns {EasySketch.Sketch}
 * @private
 */
EasySketch.Sketch.prototype.__startDrawing = function (e, pos) {
    "use strict";

    if (this.drawing === true || this.disabled === true) {
        return this;
    }

    // Adding some CSS in the mix
    this.canvas.css('cursor', 'pointer');

    // Getting to information
    var mouse = pos || this.getPointerPosition(e);

    this.getEventManager().trigger(EasySketch.Sketch.NOTIFY_START_EVENT, [mouse]);

    // Setting the flag first
    this.drawing = true;

    // Setting up the context with our requirements
    this.__contextSetup();

    // Storing the current mouse position so we can draw later
    this.lastMouse = mouse;

    return this;
};

/**
 *
 * @param {Event=null} e
 * @param {Object=null} pos This is like a virtual mouse position when triggering this using the event manager
 * @returns {EasySketch.Sketch}
 * @private
 */
EasySketch.Sketch.prototype.__draw = function (e, pos) {
    "use strict";

    if (this.drawing === false || this.disabled === true) {
        return this;
    }

    var mouse = pos || this.getPointerPosition(e);

    this.getEventManager().trigger(EasySketch.Sketch.NOTIFY_PAINT_EVENT, [mouse]);

    // Configuring the pen
    if (this.eraser) {
        // We do a save first to keep the previous globalCompositionOperation
        this.context.save();
        this.context.strokeStyle = "rgba(0,0,0,1)";
        this.context.globalCompositeOperation = "destination-out";
    }

    // Adding a new point to the path
    this.context.beginPath();
    this.context.moveTo(this.lastMouse.x, this.lastMouse.y);
    this.context.lineTo(mouse.x, mouse.y);
    this.context.closePath();
    this.context.stroke();

    // Restoring the globalCompositeOperation
    if (this.eraser) {
        this.context.restore();
    }

    // Updating the last mouse position
    this.lastMouse = mouse;

    return this;
};

/**
 *
 * @returns {EasySketch.Sketch}
 * @private
 */
EasySketch.Sketch.prototype.__stopDrawing = function () {
    "use strict";
    if (this.drawing === false) {
        return this;
    }

    this.drawing = false;

    // Adding some CSS in the mix
    this.canvas.css('cursor', 'auto');

    // Restoring
    this.__contextRestore();

    this.getEventManager().trigger(EasySketch.Sketch.NOTIFY_STOP_EVENT);

    return this;
};

/**
 *
 * @param {Array} pointsArray
 * @returns {EasySketch.Sketch}
 */
EasySketch.Sketch.prototype.drawLine = function (pointsArray) {
    "use strict";

    var points = pointsArray.slice();
    var coordinates = points.shift();

    // Executing the drawing operations
    this.__contextSetup();

    // Configuring the pen
    if (this.eraser) {
        // We do a save first to keep the previous globalCompositionOperation
        this.context.save();
        this.context.strokeStyle = "rgba(0,0,0,1)";
        this.context.globalCompositeOperation = "destination-out";
    }

    this.context.beginPath();
    this.context.moveTo(coordinates.x, coordinates.y);
    while (points.length > 0) {
        coordinates = points.shift();
        this.context.lineTo(coordinates.x, coordinates.y);
    }
    this.context.stroke();

    // Restoring the globalCompositeOperation
    if (this.eraser) {
        this.context.restore();
    }

    this.__contextRestore();

    return this;
};
<commit_msg>Implemented the touch functionality (not tested yet)<commit_after>/**
 * easy-sketch.js
 *
 * @link https://github.com/brian978/easy-sketch.js
 * @copyright Copyright (c) 2013
 * @license Creative Commons Attribution-ShareAlike 3.0
 */

var EasySketch = EasySketch || {};

EasySketch.EventManager = function (binding) {
    "use strict";
    var $this = this;

    this.manager = $(binding);

    return {
        /**
         *
         * @param {String} eventType
         * @param {Array|Object=null} params
         */
        trigger: function (eventType, params) {
            $this.manager.trigger(eventType, params || null);
        },
        /**
         *
         * @param {String} eventType
         * @param {Function} handler
         * @param {Array=null} data Some data that can be passed to the function call
         */
        attach: function (eventType, handler, data) {
            $this.manager.on(eventType, data || null, handler);
        },
        /**
         *
         * @param {String} eventType
         * @param {Function} handler
         */
        detach: function (eventType, handler) {
            $this.manager.unbind(eventType, handler);
        }
    };
};

/**
 *
 * @param {*} element
 * @param {Object=null} options
 * @constructor
 */
EasySketch.Sketch = function (element, options) {
    "use strict";

    this.lastMouse = {x: 0, y: 0};
    this.disabled = false;
    this.binded = false;
    this.drawing = false;
    this.events = new EasySketch.EventManager(this);
    this.eraser = false;
    this.canvas = this.__createCanvas(element);
    this.context = this.canvas.get(0).getContext("2d");

    this.options = {
        color: "#000000",
        width: 5,
        bindingObject: null,
        autoBind: true
    };

    this.listeners = {
        start: this.__startDrawing.bind(this),
        draw: this.__draw.bind(this),
        stop: this.__stopDrawing.bind(this)
    };

    if (options) {
        this.setOptions(options);
    }

    if (this.options.autoBind === true) {
        this.attachListeners();
    }
};

// Listened events
EasySketch.Sketch.START_PAINTING_EVENT = 'sketch.start';
EasySketch.Sketch.PAINT_EVENT = 'sketch.paint';
EasySketch.Sketch.STOP_PAINTING_EVENT = 'sketch.stop';

// Triggered events
EasySketch.Sketch.NOTIFY_START_EVENT = 'notify.start';
EasySketch.Sketch.NOTIFY_PAINT_EVENT = 'notify.paint';
EasySketch.Sketch.NOTIFY_STOP_EVENT = 'notify.stop';

/**
 *
 * @param options
 * @returns {EasySketch.Sketch}
 */
EasySketch.Sketch.prototype.setOptions = function (options) {
    "use strict";

    this.options = $.extend(this.options, options || {});

    return this;
};

/**
 * Returns the value of an option if it exists and null (if this isn't changed) if it doesn't
 *
 * @param {String} name
 * @param {*=null} defaultValue
 * @returns {*}
 */
EasySketch.Sketch.prototype.getOption = function (name, defaultValue) {
    defaultValue = defaultValue || null;

    if (this.options.hasOwnProperty(name)) {
        return this.options[name];
    }

    return defaultValue;
};

/**
 *
 * @returns {EventManager|*}
 */
EasySketch.Sketch.prototype.getEventManager = function () {
    "use strict";
    return this.events;
};

/**
 *
 * @param {*} element
 * @returns {*}
 * @private
 */
EasySketch.Sketch.prototype.__createCanvas = function (element) {
    "use strict";
    var canvas;
    var elementType = typeof element;

    switch (elementType) {
        case "string":
            if (element.indexOf('#') === 0) {
                canvas = $(element);
            } else if (element.indexOf('.') === -1) {
                canvas = $("#" + element);
            }
            break;

        case "object":
            if (element instanceof jQuery) {
                canvas = element;
            } else {
                canvas = $(element);
            }
            break;
    }

    return canvas;
};

/**
 *
 * @returns {EasySketch.Sketch}
 */
EasySketch.Sketch.prototype.attachListeners = function () {
    "use strict";

    if (this.binded === true) {
        return this;
    }

    this.binded = true;

    // Selecting the object to bind on
    var bindingObject;
    if (this.getOption("bindingObject") !== null) {
        bindingObject = this.options["bindingObject"];
    } else {
        bindingObject = this.canvas;
    }

    // Canvas listeners
    bindingObject.on('mousedown touchstart', this.listeners.start);
    bindingObject.on('mousemove touchmove', this.listeners.draw);
    bindingObject.on('mouseup mouseleave mouseout touchend touchcancel', this.listeners.stop);

    // Event manager listeners
    this.events.attach(EasySketch.Sketch.START_PAINTING_EVENT, this.listeners.start);
    this.events.attach(EasySketch.Sketch.PAINT_EVENT, this.listeners.draw);
    this.events.attach(EasySketch.Sketch.STOP_PAINTING_EVENT, this.listeners.stop);

    return this;
};

/**
 * Listeners can also be detached if this is required
 *
 * @returns {EasySketch.Sketch}
 */
EasySketch.Sketch.prototype.detachListeners = function () {
    "use strict";

    if (this.binded === false) {
        return this;
    }

    this.binded = false;

    // Selecting the object to bind on
    var bindingObject;
    if (this.getOption("bindingObject") !== null) {
        bindingObject = this.options["bindingObject"];
    } else {
        bindingObject = this.canvas;
    }

    // Canvas listeners
    bindingObject.off('mousedown touchstart', this.listeners.start);
    bindingObject.off('mousemove touchmove', this.listeners.draw);
    bindingObject.off('mouseup mouseleave mouseout touchend touchcancel', this.listeners.stop);

    // Event manager listeners
    this.events.detach(EasySketch.Sketch.START_PAINTING_EVENT, this.listeners.start);
    this.events.detach(EasySketch.Sketch.PAINT_EVENT, this.listeners.draw);
    this.events.detach(EasySketch.Sketch.STOP_PAINTING_EVENT, this.listeners.stop);

    return this;
};

/**
 *
 * @returns {number}
 */
EasySketch.Sketch.prototype.getScale = function () {
    var prefixes = ["-moz", "-webkit", "-o", "-ms"];
    var property = null;
    var propertyName = "";
    var canvasStyle = this.canvas[0].style;
    var scale = 1;

    // Determining the property to use
    for (var i = 0; i < prefixes.length; i++) {
        propertyName = prefixes[i] + "-transform";
        if (propertyName in canvasStyle) {
            property = propertyName;
            break;
        }
    }

    var matrix = String(this.canvas.css(property));
    if (matrix != "none") {
        var regex = new RegExp("([0-9.-]+)", "g");
        var matches = matrix.match(regex);
        scale = matches[0];
    }

    return scale;
};

/**
 *
 * @param {Event} e
 * @returns {{x: Number, y: Number}}
 */
EasySketch.Sketch.prototype.getPointerPosition = function (e) {
    "use strict";

    var $this = this;
    var scale = this.getScale();

    if (e.hasOwnProperty("originalEvent") && e.originalEvent.hasOwnProperty("targetTouches")) {
        e.pageX = e.originalEvent.targetTouches[0].pageX;
        e.pageY = e.originalEvent.targetTouches[0].pageY;
    }

    return {
        x: Math.ceil((e.pageX - $this.canvas.offset().left) / scale),
        y: Math.ceil((e.pageY - $this.canvas.offset().top) / scale)
    }
};

/**
 *
 * @param {Boolean} value
 * @returns {EasySketch.Sketch}
 */
EasySketch.Sketch.prototype.enableEraser = function (value) {
    "use strict";
    this.eraser = value;

    return this;
};

/**
 *
 * @returns {EasySketch.Sketch}
 * @private
 */
EasySketch.Sketch.prototype.__contextSetup = function () {
    // Saving first to avoid changing other stuff
    this.context.save();

    // Applying our requirements
    this.context.strokeStyle = this.options.color;
    this.context.lineWidth = this.options.width;
    this.context.lineCap = "round";
    this.context.lineJoin = "round";

    return this;
};

/**
 *
 * @returns {EasySketch.Sketch}
 * @private
 */
EasySketch.Sketch.prototype.__contextRestore = function () {
    this.context.restore();

    return this;
};

/**
 *
 * @param {Event=null} e
 * @param {Object=null} pos This is like a virtual mouse position when triggering this using the event manager
 * @returns {EasySketch.Sketch}
 * @private
 */
EasySketch.Sketch.prototype.__startDrawing = function (e, pos) {
    "use strict";

    if (this.drawing === true || this.disabled === true) {
        return this;
    }

    // Adding some CSS in the mix
    this.canvas.css('cursor', 'pointer');

    // Getting to information
    var mouse = pos || this.getPointerPosition(e);

    this.getEventManager().trigger(EasySketch.Sketch.NOTIFY_START_EVENT, [mouse]);

    // Setting the flag first
    this.drawing = true;

    // Setting up the context with our requirements
    this.__contextSetup();

    // Storing the current mouse position so we can draw later
    this.lastMouse = mouse;

    return this;
};

/**
 *
 * @param {Event=null} e
 * @param {Object=null} pos This is like a virtual mouse position when triggering this using the event manager
 * @returns {EasySketch.Sketch}
 * @private
 */
EasySketch.Sketch.prototype.__draw = function (e, pos) {
    "use strict";

    if (this.drawing === false || this.disabled === true) {
        return this;
    }

    var mouse = pos || this.getPointerPosition(e);

    this.getEventManager().trigger(EasySketch.Sketch.NOTIFY_PAINT_EVENT, [mouse]);

    // Configuring the pen
    if (this.eraser) {
        // We do a save first to keep the previous globalCompositionOperation
        this.context.save();
        this.context.strokeStyle = "rgba(0,0,0,1)";
        this.context.globalCompositeOperation = "destination-out";
    }

    // Adding a new point to the path
    this.context.beginPath();
    this.context.moveTo(this.lastMouse.x, this.lastMouse.y);
    this.context.lineTo(mouse.x, mouse.y);
    this.context.closePath();
    this.context.stroke();

    // Restoring the globalCompositeOperation
    if (this.eraser) {
        this.context.restore();
    }

    // Updating the last mouse position
    this.lastMouse = mouse;

    return this;
};

/**
 *
 * @returns {EasySketch.Sketch}
 * @private
 */
EasySketch.Sketch.prototype.__stopDrawing = function () {
    "use strict";
    if (this.drawing === false) {
        return this;
    }

    this.drawing = false;

    // Adding some CSS in the mix
    this.canvas.css('cursor', 'auto');

    // Restoring
    this.__contextRestore();

    this.getEventManager().trigger(EasySketch.Sketch.NOTIFY_STOP_EVENT);

    return this;
};

/**
 *
 * @param {Array} pointsArray
 * @returns {EasySketch.Sketch}
 */
EasySketch.Sketch.prototype.drawLine = function (pointsArray) {
    "use strict";

    var points = pointsArray.slice();
    var coordinates = points.shift();

    // Executing the drawing operations
    this.__contextSetup();

    // Configuring the pen
    if (this.eraser) {
        // We do a save first to keep the previous globalCompositionOperation
        this.context.save();
        this.context.strokeStyle = "rgba(0,0,0,1)";
        this.context.globalCompositeOperation = "destination-out";
    }

    this.context.beginPath();
    this.context.moveTo(coordinates.x, coordinates.y);
    while (points.length > 0) {
        coordinates = points.shift();
        this.context.lineTo(coordinates.x, coordinates.y);
    }
    this.context.stroke();

    // Restoring the globalCompositeOperation
    if (this.eraser) {
        this.context.restore();
    }

    this.__contextRestore();

    return this;
};
<|endoftext|>


<commit_before>;( function() {

	'use strict';

	// validation util functions
	const _assert = {

		'is': function(methods, type) {
			return Object.prototype.toString.call(methods).slice(8, -1) === type;
		},

		// apply type checking to a collection
		'areAll': function(items, type) {

			for(var item in items) {

				if(!this.is(items[item], type)) {
					return false;
				}
			}

			return true;
		},
	},

	// extend an object with another objects properties/state
	// returns a new object, leaving both source & destination untouched
	_extend = function(methods, parent) {

		var Builder = function() {

			if(!(this instanceof Builder)) {

				return new Builder(arguments);
			}

			this._super.apply(this, arguments);
			this._init.apply(this, arguments);
		};

		// attach pub, sub & unsub
		Builder.prototype = parent.prototype;

		// handle to object parent's constructor
		Builder.prototype._super = parent;

		// attach all custom methods to the Bugle object
		for(var method in methods) {
			Builder.prototype[method] = methods[method];
		}

		// when no init found, assume an empty constructor
		if(!Builder.prototype._init) {
			Builder.prototype._init = function() { };
		}

		return Builder;
	},

	// ensures the we get 'true' sync behaviour
	_async = function(fn) {
		setTimeout(fn, 0);
	},

	// convenience object for throwing helpful errors
	_error = {

		'sub': function() {
			return 'USAGE [ topic:String, object:Object, toCall:String ]';
		},

		'pub': function() {
			return 'UASGE [ topic:String, data:Array[Any...] ]';
		},

		'unsub': function() {
			return 'USAGE [topic:String, oId:Number]';
		},

		'pubError': function(topic, error) {
			return 'Failed to publish to instance on topic "' +
				topic + '" [' + error.message + ']';
		},

		'notAnObject': function() {
			return 'argument to Bugle must be a literal object';
		}
	},

	_publish = function(topic) {

		// get user arguments to the function call
		var args = Array.prototype.slice.call(arguments, 1),

		self = this,

		// apply current sub object and pub args to sub function
		publishTo = (subscriber) => {

			try {
				subscriber.fn.apply(subscriber.instance, args.concat(topic));
			} catch(e) {

				_async(function() {
					throw _error.pubError(topic, e);
				});
			}

		};

		if(_assert.is(topic, 'String')) {

			// publish args to each subscriber on topic
			_async(function() {

				if(self.topics[topic]) {

					var topicLine = self.topics[topic];
					topicLine.forEach(publishTo);
				}
			});

			return true;

		} else {

			throw _error.pub();
		}
	},

	_subscribe = function(topic, instance, toCall) {

		// verify that param #1 & #3 are of type String
		var areString = _assert.areAll([topic, toCall], 'String'),

		// verify instance is an Object
		isObject = _assert.is(instance, 'Object');

		if(areString && isObject) {

			if(!this.topics[topic]) {
				this.topics[topic] = [];
			}

			this.topics[topic].push({
				'oId': (++this.oId),
				'instance': instance,
				'fn': instance[toCall]
			});

			return this.oId;

		} else {

			throw _error.sub();
		}
	},

	_unsubscribe = function(topic, oId) {

		var unsub = () => {

			if(this.topics[topic]) {

				var topicLine = this.topics[topic];

				// loop for specified oId until we get a match
				for(var index in topicLine) {

					if(topicLine[index].oId === oId) {
						topicLine.splice(index, 1);
						return;
					};
				}
			}
		};

		if(_assert.is(topic, 'String')) {

			_async(function() { unsub(); });

		} else {

			throw _error.unsub();
		}
	};

	function Bugle() {

		// if no 'new' keyword specified by user
		if(!(this instanceof Bugle)) {

			return new Bugle();
		}

		// holds each topic along with its subscribers
		this.topics = [];
		// tracks the location of an object instance on a topic
		this.oId = 0;
	}

	Bugle.prototype = {

		// notify all objects subscribed to the given topic with the data received
		pub: _publish,

		// subscribe an object instance to a topic, execute with the 'toCall' function
		sub: _subscribe,

		// remove an object from the subscriptions list on a topic with its assigned oId
		unsub: _unsubscribe
	};

	window.Bugle = function(methods) {

		// check for option arg
		if(arguments.length) {

			// verify stateful & of type Object
			if(_assert.is(methods, 'Object')) {
				return _extend(methods, Bugle);

			} else {

				throw _error.notAnObject();
			}
		}

		return Bugle();
	};

} )();<commit_msg>moved 'publishTo' outside of _publish method<commit_after>;( function() {

	'use strict';

	// validation util functions
	const _assert = {

		'is': function(methods, type) {
			return Object.prototype.toString.call(methods).slice(8, -1) === type;
		},

		// apply type checking to a collection
		'areAll': function(items, type) {

			for(var item in items) {

				if(!this.is(items[item], type)) {
					return false;
				}
			}

			return true;
		},
	},

	// extend an object with another objects properties/state
	// returns a new object, leaving both source & destination untouched
	_extend = function(methods, parent) {

		var Builder = function() {

			if(!(this instanceof Builder)) {

				return new Builder(arguments);
			}

			this._super.apply(this, arguments);
			this._init.apply(this, arguments);
		};

		// attach pub, sub & unsub
		Builder.prototype = parent.prototype;

		// handle to object parent's constructor
		Builder.prototype._super = parent;

		// attach all custom methods to the Bugle object
		for(var method in methods) {
			Builder.prototype[method] = methods[method];
		}

		// when no init found, assume an empty constructor
		if(!Builder.prototype._init) {
			Builder.prototype._init = function() { };
		}

		return Builder;
	},

	// ensures the we get 'true' sync behaviour
	_async = function(fn) {
		setTimeout(fn, 0);
	},

	// convenience object for throwing helpful errors
	_error = {

		'sub': function() {
			return 'USAGE [ topic:String, object:Object, toCall:String ]';
		},

		'pub': function() {
			return 'UASGE [ topic:String, data:Array[Any...] ]';
		},

		'unsub': function() {
			return 'USAGE [topic:String, oId:Number]';
		},

		'pubError': function(topic, error) {
			return 'Failed to publish to instance on topic "' +
				topic + '" [' + error.message + ']';
		},

		'notAnObject': function() {
			return 'argument to Bugle must be a literal object';
		}
	},

	// apply current sub object and pub args to sub function
	_publishTo = function(topic, data) {

		return function(subscriber) {

			try {
				subscriber
					.fn.apply(subscriber.instance, data.concat(topic));

			} catch(e) {

				_async(function() {
					throw _error.pubError(topic, e);
				});
			}
		}
	},

	// notify all objects subscribed to the given topic with the data received
	_publish = function(topic) {

		var self = this;

		if(_assert.is(topic, 'String')) {

			var args = Array.prototype.slice.call(arguments, 1);

			// publish args to each subscriber on topic
			_async(function() {

				if(self.topics[topic]) {

					var topicLine = self.topics[topic];
					topicLine.forEach(_publishTo(topic, args));
				}
			});

		} else {

			throw _error.pub();
		}
	},

	// subscribe an object instance to a topic, execute with the 'toCall' function
	_subscribe = function(topic, instance, toCall) {

		// verify that param #1 & #3 are of type String
		var areString = _assert.areAll([topic, toCall], 'String'),

		// instance should be of type Object
		isObject = _assert.is(instance, 'Object');

		if(areString && isObject) {

			if(!this.topics[topic]) {
				this.topics[topic] = [];
			}

			this.topics[topic].push({
				'oId': (++this.oId),
				'instance': instance,
				'fn': instance[toCall]
			});

			return this.oId;

		} else {

			throw _error.sub();
		}
	},

	// remove an object from the subscriptions list on a topic with its assigned oId
	_unsubscribe = function(topic, oId) {

		var self = this;

		if(_assert.is(topic, 'String')) {

			_async(function() {

				var topicLine = self.topics[topic];

				if(topicLine) {

					// loop for specified oId until we get a match
					for(var index in topicLine) {

						if(topicLine[index].oId === oId) {
							topicLine.splice(index, 1);
							return;
						};
					}
				}
			});

		} else {

			throw _error.unsub();
		}
	};

	function Bugle() {

		// if no 'new' keyword specified by user
		if(!(this instanceof Bugle)) {

			return new Bugle();
		}

		// holds each topic along with its subscribers
		this.topics = [];

		// tracks the location of an object instance on a topic
		this.oId = 0;
	}

	Bugle.prototype = {

		pub: _publish,

		sub: _subscribe,

		unsub: _unsubscribe
	};

	window.Bugle = function(methods) {

		// check for option arg
		if(arguments.length) {

			// verify stateful & of type Object
			if(_assert.is(methods, 'Object')) {
				return _extend(methods, Bugle);

			} else {

				throw _error.notAnObject();
			}
		}

		return Bugle();
	};

} )();<|endoftext|>


<commit_before>TC.control = TC.control || {};

if (!TC.control.TabContainer) {
    TC.syncLoadJS(TC.apiLocation + 'TC/control/TabContainer');
}

TC.control.DataLoader = function () {
    const self = this;

    TC.control.TabContainer.apply(self, arguments);

    self.controlOptions = [
        {
            name: 'externalWMS',
            title: 'addWMS',
            options: {
                suggestions: self.options.wmsSuggestions
            }
        },
        {
            name: 'fileImport',
            options: {
                enableDragAndDrop: self.options.enableDragAndDrop
            }
        }
    ];
    self.defaultSelection = 0;
};

TC.inherit(TC.control.DataLoader, TC.control.TabContainer);

(function () {
    const ctlProto = TC.control.DataLoader.prototype;

    ctlProto.register = function (map) {
        const self = this;
        self.title = self.getLocaleString('addMaps');
        return new Promise(function (resolve, reject) {
            TC.control.TabContainer.prototype.register.call(self, map).then(ctl => {
                ctl.div.classList.add(self.CLASS + '-datldr');
                resolve(ctl);
            });
        })
    };

})();
<commit_msg>Set new configuration structure<commit_after>TC.control = TC.control || {};

if (!TC.control.TabContainer) {
    TC.syncLoadJS(TC.apiLocation + 'TC/control/TabContainer');
}

TC.control.DataLoader = function () {
    const self = this;

    TC.control.TabContainer.apply(self, arguments);

    self.controlOptions = [
        {
            title: 'addWMS',
            externalWMS: { suggestions: self.options.wmsSuggestions }
        },
        {
            fileImport: {
                enableDragAndDrop: self.options.enableDragAndDrop
            }
        }
    ];
    self.defaultSelection = 0;
};

TC.inherit(TC.control.DataLoader, TC.control.TabContainer);

(function () {
    const ctlProto = TC.control.DataLoader.prototype;

    ctlProto.register = function (map) {
        const self = this;
        self.map = map;
        self.title = self.getLocaleString('addMaps');
        return new Promise(function (resolve, reject) {
            TC.control.TabContainer.prototype.register.call(self, map).then(ctl => {
                ctl.div.classList.add(self.CLASS + '-datldr');
                resolve(ctl);
            });
        })
    };

})();
<|endoftext|>


<commit_before>L.Control.Locate = L.Control.extend({
    options: {
        position: 'topleft',
        drawCircle: true,
        follow: false,  // follow with zoom and pan the user's location
        stopFollowingOnDrag: false, // if follow is true, stop following when map is dragged
        // range circle
        circleStyle: {
            color: '#136AEC',
            fillColor: '#136AEC',
            fillOpacity: 0.15,
            weight: 2,
            opacity: 0.5
        },
        // inner marker
        markerStyle: {
            color: '#136AEC',
            fillColor: '#2A93EE',
            fillOpacity: 0.7,
            weight: 2,
            opacity: 0.9,
            radius: 5
        },
        // changes to range circle and inner marker while following
        // it is only necessary to provide the things that should change
        followCircleStyle: {},
        followMarkerStyle: {
            //color: '#FFA500',
            //fillColor: '#FFB000'
        },
        metric: true,
        onLocationError: function(err) {
            // this event is called in case of any location error
            // that is not a time out error.
            alert(err.message);
        },
        onLocationOutsideMapBounds: function(context) {
            // this event is repeatedly called when the location changes
            alert(context.options.strings.outsideMapBoundsMsg);
        },
        setView: true, // automatically sets the map view to the user's location
        strings: {
            title: "Show me where I am",
            popup: "You are within {distance} {unit} from this point",
            outsideMapBoundsMsg: "You seem located outside the boundaries of the map"
        },
        locateOptions: {}
    },

    onAdd: function (map) {
        var className = 'leaflet-control-locate',
            classNames = className + ' leaflet-bar leaflet-control',
            container = L.DomUtil.create('div', classNames);

        var self = this;
        this._layer = new L.LayerGroup();
        this._layer.addTo(map);
        this._event = undefined;

        this._locateOptions = {
            watch: true  // if you overwrite this, visualization cannot be updated
        };
        L.extend(this._locateOptions, this.options.locateOptions);
        L.extend(this._locateOptions, {
            setView: false // have to set this to false because we have to
                           // do setView manually
        });

        // extend the follow marker style and circle from the normal style
        var tmp = {};
        L.extend(tmp, this.options.markerStyle, this.options.followMarkerStyle);
        this.options.followMarkerStyle = tmp;
        tmp = {};
        L.extend(tmp, this.options.circleStyle, this.options.followCircleStyle);
        this.options.followCircleStyle = tmp;

        var link = L.DomUtil.create('a', 'leaflet-bar-part leaflet-bar-part-single', container);
        link.href = '#';
        link.title = this.options.strings.title;

        L.DomEvent
            .on(link, 'click', L.DomEvent.stopPropagation)
            .on(link, 'click', L.DomEvent.preventDefault)
            .on(link, 'click', function() {
                if (self._active && (map.getBounds().contains(self._event.latlng) || !self.options.setView ||
                    isOutsideMapBounds())) {
                    stopLocate();
                } else {
                    if (self.options.setView) {
                        self._locateOnNextLocationFound = true;
                    }
                    if(!self._active) {
                        map.locate(self._locateOptions);
                    }
                    self._active = true;
                    if (self.options.follow) {
                        startFollowing();
                    }
                    if (!self._event) {
                        self._container.className = classNames + " requesting";
                    } else {
                        visualizeLocation();
                    }
                }
            })
            .on(link, 'dblclick', L.DomEvent.stopPropagation);

        var onLocationFound = function (e) {
            // no need to do anything if the location has not changed
            if (self._event &&
                (self._event.latlng.lat == e.latlng.lat &&
                 self._event.latlng.lng == e.latlng.lng)) {
                return;
            }

            self._event = e;

            if (self.options.follow && self._following) {
                self._locateOnNextLocationFound = true;
            }

            visualizeLocation();
        };

        var startFollowing = function() {
            self._following = true;
            if (self.options.stopFollowingOnDrag) {
                map.on('dragstart', stopFollowing);
            }
        };

        var stopFollowing = function() {
            self._following = false;
            if (self.options.stopFollowingOnDrag) {
                map.off('dragstart', stopFollowing);
            }
            visualizeLocation();
        };

        var isOutsideMapBounds = function () {
            if (self._event === undefined)
                return false;
            return map.options.maxBounds &&
                !map.options.maxBounds.contains(self._event.latlng);
        };

        var visualizeLocation = function() {
            if (self._event.accuracy === undefined)
                self._event.accuracy = 0;

            self._layer.clearLayers();

            var radius = self._event.accuracy / 2;
            if (self._locateOnNextLocationFound) {
                if (isOutsideMapBounds()) {
                    self.options.onLocationOutsideMapBounds(self);
                } else {
                    map.fitBounds(self._event.bounds);
                }
                self._locateOnNextLocationFound = false;
            }

            // circle with the radius of the location's accuracy
            var style;
            if (self.options.drawCircle) {
                if (self._following) {
                    style = self.options.followCircleStyle;
                } else {
                    style = self.options.circleStyle;
                }

                L.circle(self._event.latlng, radius, style)
                    .addTo(self._layer);
            }

            var distance, unit;
            if (self.options.metric) {
                distance = radius.toFixed(0);
                unit = "meters";
            } else {
                distance = (radius * 3.2808399).toFixed(0);
                unit = "feet";
            }

            // small inner marker
            var m;
            if (self._following) {
                m = self.options.followMarkerStyle;
            } else {
                m = self.options.markerStyle;
            }

            var t = self.options.strings.popup;
            L.circleMarker(self._event.latlng, m)
                .bindPopup(L.Util.template(t, {distance: distance, unit: unit}))
                .addTo(self._layer);

            if (!self._container)
                return;
            if (self._following) {
                self._container.className = classNames + " active following";
            } else {
                self._container.className = classNames + " active";
            }
        };

        var resetVariables = function() {
            self._active = false;
            self._locateOnNextLocationFound = self.options.setView;
            self._following = false;
        };

        resetVariables();

        var stopLocate = function() {
            map.stopLocate();
            map.off('dragstart', stopFollowing);

            self._container.className = classNames;
            resetVariables();

            self._layer.clearLayers();
        };

        var onLocationError = function (err) {
            // ignore time out error if the location is watched
            if (err.code == 3 && this._locateOptions.watch) {
                return;
            }

            stopLocate();
            self.options.onLocationError(err);
        };

        // event hooks
        map.on('locationfound', onLocationFound, self);
        map.on('locationerror', onLocationError, self);

        return container;
    }
});

L.Map.addInitHook(function () {
    if (this.options.locateControl) {
        this.locateControl = L.control.locate();
        this.addControl(this.locateControl);
    }
});

L.control.locate = function (options) {
    return new L.Control.Locate(options);
};
<commit_msg>Add notice about origin to main js file<commit_after>/*
Copyright (c) 2013 Dominik Moritz

This file is part of the leaflet locate control. It is licensed under the MIT license.
You can find the project at: https://github.com/domoritz/leaflet-locatecontrol
*/
L.Control.Locate = L.Control.extend({
    options: {
        position: 'topleft',
        drawCircle: true,
        follow: false,  // follow with zoom and pan the user's location
        stopFollowingOnDrag: false, // if follow is true, stop following when map is dragged
        // range circle
        circleStyle: {
            color: '#136AEC',
            fillColor: '#136AEC',
            fillOpacity: 0.15,
            weight: 2,
            opacity: 0.5
        },
        // inner marker
        markerStyle: {
            color: '#136AEC',
            fillColor: '#2A93EE',
            fillOpacity: 0.7,
            weight: 2,
            opacity: 0.9,
            radius: 5
        },
        // changes to range circle and inner marker while following
        // it is only necessary to provide the things that should change
        followCircleStyle: {},
        followMarkerStyle: {
            //color: '#FFA500',
            //fillColor: '#FFB000'
        },
        metric: true,
        onLocationError: function(err) {
            // this event is called in case of any location error
            // that is not a time out error.
            alert(err.message);
        },
        onLocationOutsideMapBounds: function(context) {
            // this event is repeatedly called when the location changes
            alert(context.options.strings.outsideMapBoundsMsg);
        },
        setView: true, // automatically sets the map view to the user's location
        strings: {
            title: "Show me where I am",
            popup: "You are within {distance} {unit} from this point",
            outsideMapBoundsMsg: "You seem located outside the boundaries of the map"
        },
        locateOptions: {}
    },

    onAdd: function (map) {
        var className = 'leaflet-control-locate',
            classNames = className + ' leaflet-bar leaflet-control',
            container = L.DomUtil.create('div', classNames);

        var self = this;
        this._layer = new L.LayerGroup();
        this._layer.addTo(map);
        this._event = undefined;

        this._locateOptions = {
            watch: true  // if you overwrite this, visualization cannot be updated
        };
        L.extend(this._locateOptions, this.options.locateOptions);
        L.extend(this._locateOptions, {
            setView: false // have to set this to false because we have to
                           // do setView manually
        });

        // extend the follow marker style and circle from the normal style
        var tmp = {};
        L.extend(tmp, this.options.markerStyle, this.options.followMarkerStyle);
        this.options.followMarkerStyle = tmp;
        tmp = {};
        L.extend(tmp, this.options.circleStyle, this.options.followCircleStyle);
        this.options.followCircleStyle = tmp;

        var link = L.DomUtil.create('a', 'leaflet-bar-part leaflet-bar-part-single', container);
        link.href = '#';
        link.title = this.options.strings.title;

        L.DomEvent
            .on(link, 'click', L.DomEvent.stopPropagation)
            .on(link, 'click', L.DomEvent.preventDefault)
            .on(link, 'click', function() {
                if (self._active && (map.getBounds().contains(self._event.latlng) || !self.options.setView ||
                    isOutsideMapBounds())) {
                    stopLocate();
                } else {
                    if (self.options.setView) {
                        self._locateOnNextLocationFound = true;
                    }
                    if(!self._active) {
                        map.locate(self._locateOptions);
                    }
                    self._active = true;
                    if (self.options.follow) {
                        startFollowing();
                    }
                    if (!self._event) {
                        self._container.className = classNames + " requesting";
                    } else {
                        visualizeLocation();
                    }
                }
            })
            .on(link, 'dblclick', L.DomEvent.stopPropagation);

        var onLocationFound = function (e) {
            // no need to do anything if the location has not changed
            if (self._event &&
                (self._event.latlng.lat == e.latlng.lat &&
                 self._event.latlng.lng == e.latlng.lng)) {
                return;
            }

            self._event = e;

            if (self.options.follow && self._following) {
                self._locateOnNextLocationFound = true;
            }

            visualizeLocation();
        };

        var startFollowing = function() {
            self._following = true;
            if (self.options.stopFollowingOnDrag) {
                map.on('dragstart', stopFollowing);
            }
        };

        var stopFollowing = function() {
            self._following = false;
            if (self.options.stopFollowingOnDrag) {
                map.off('dragstart', stopFollowing);
            }
            visualizeLocation();
        };

        var isOutsideMapBounds = function () {
            if (self._event === undefined)
                return false;
            return map.options.maxBounds &&
                !map.options.maxBounds.contains(self._event.latlng);
        };

        var visualizeLocation = function() {
            if (self._event.accuracy === undefined)
                self._event.accuracy = 0;

            self._layer.clearLayers();

            var radius = self._event.accuracy / 2;
            if (self._locateOnNextLocationFound) {
                if (isOutsideMapBounds()) {
                    self.options.onLocationOutsideMapBounds(self);
                } else {
                    map.fitBounds(self._event.bounds);
                }
                self._locateOnNextLocationFound = false;
            }

            // circle with the radius of the location's accuracy
            var style;
            if (self.options.drawCircle) {
                if (self._following) {
                    style = self.options.followCircleStyle;
                } else {
                    style = self.options.circleStyle;
                }

                L.circle(self._event.latlng, radius, style)
                    .addTo(self._layer);
            }

            var distance, unit;
            if (self.options.metric) {
                distance = radius.toFixed(0);
                unit = "meters";
            } else {
                distance = (radius * 3.2808399).toFixed(0);
                unit = "feet";
            }

            // small inner marker
            var m;
            if (self._following) {
                m = self.options.followMarkerStyle;
            } else {
                m = self.options.markerStyle;
            }

            var t = self.options.strings.popup;
            L.circleMarker(self._event.latlng, m)
                .bindPopup(L.Util.template(t, {distance: distance, unit: unit}))
                .addTo(self._layer);

            if (!self._container)
                return;
            if (self._following) {
                self._container.className = classNames + " active following";
            } else {
                self._container.className = classNames + " active";
            }
        };

        var resetVariables = function() {
            self._active = false;
            self._locateOnNextLocationFound = self.options.setView;
            self._following = false;
        };

        resetVariables();

        var stopLocate = function() {
            map.stopLocate();
            map.off('dragstart', stopFollowing);

            self._container.className = classNames;
            resetVariables();

            self._layer.clearLayers();
        };

        var onLocationError = function (err) {
            // ignore time out error if the location is watched
            if (err.code == 3 && this._locateOptions.watch) {
                return;
            }

            stopLocate();
            self.options.onLocationError(err);
        };

        // event hooks
        map.on('locationfound', onLocationFound, self);
        map.on('locationerror', onLocationError, self);

        return container;
    }
});

L.Map.addInitHook(function () {
    if (this.options.locateControl) {
        this.locateControl = L.control.locate();
        this.addControl(this.locateControl);
    }
});

L.control.locate = function (options) {
    return new L.Control.Locate(options);
};
<|endoftext|>


<commit_before>import RemoteModel from './remote-model';
import Log from 'debug';

const log = new Log('democracyos:forums');

class Forums extends RemoteModel {

  constructor () {
    super();
    this.loadFromParamsMiddleware = this.loadFromParamsMiddleware.bind(this);
  }

  name () {
    return 'forums';
  }

  url (id) {
    return `/api/forum/${id}`;
  }

  parse (forum) {
    forum.url = '/' + forum.name;
    return forum;
  }

  /**
   * Get the Forum of the current user
   *
   * @return {Promise} fetch
   * @api public
   */
  getUserForum () {
    return this.get('mine');
  }

  unloadUserForum () {
    return this.unload('mine');
  }

  deleteUserForum () {
    return this.delete('mine');
  }

  /**
   * Middleware to load forum from current page url, gets it from '/:forum'.
   *
   * @return {Middleware}
   * @api public
   */
  loadFromParamsMiddleware (ctx, next) {
    const name = ctx.params.forum;

    this.get(name)
      .then(function(forum){
        ctx.forum = forum;
        next();
      })
      .catch(function(err){
        log('Found error %s', err);
      });
  }
}

const forums = new Forums();

export default forums;
<commit_msg>fix unload user forum when logout occurs<commit_after>import bus from 'bus';
import RemoteModel from './remote-model';
import Log from 'debug';

const log = new Log('democracyos:forums');

class Forums extends RemoteModel {

  constructor () {
    super();
    this.loadFromParamsMiddleware = this.loadFromParamsMiddleware.bind(this);

    bus.on('logout', this.unloadUserForum.bind(this));
  }

  name () {
    return 'forums';
  }

  url (id) {
    return `/api/forum/${id}`;
  }

  parse (forum) {
    forum.url = '/' + forum.name;
    return forum;
  }

  /**
   * Get the Forum of the current user
   *
   * @return {Promise} fetch
   * @api public
   */
  getUserForum () {
    return this.get('mine');
  }

  unloadUserForum () {
    return this.unload('mine');
  }

  deleteUserForum () {
    return this.delete('mine');
  }

  /**
   * Middleware to load forum from current page url, gets it from '/:forum'.
   *
   * @return {Middleware}
   * @api public
   */
  loadFromParamsMiddleware (ctx, next) {
    const name = ctx.params.forum;

    this.get(name)
      .then(function(forum){
        ctx.forum = forum;
        next();
      })
      .catch(function(err){
        log('Found error %s', err);
      });
  }
}

const forums = new Forums();

export default forums;
<|endoftext|>