<commit_before>"use strict";

var Q = require("q");
var xhrLocal = require("./xhr");
var version = require("../package.json").version;

module.exports = function (origin, options) {

    var locationOrigin = location.protocol + "//" + location.host;
    options = options || {};

    function destroy() {
        if (iframe) {
            window.removeEventListener("message", responseMessageHandler);
            iframe.parentNode.removeChild(iframe);
        }
    }

    function xhrProxy(request) {
        var deferred = Q.defer();
        if (typeof request === "string") {
            request = { url: request };
        }
        queue[id] = { deferred: deferred };
        iframeWindow.postMessage(JSON.stringify({ id: id, request: request }), origin); // Post to the xhr proxy.
        id = (id + 1) % 65536; // Recycle ids (eventually).
        return deferred.promise;
    }
    xhrProxy.destroy = destroy;

    function reject(err) {
        clearTimeout(iframeTimer);
        window.removeEventListener("message", readyMessageHandler);
        iframe.parentNode.removeChild(iframe);
        xcopReadyDeferred.reject(err);
    }

    function xcopTimeout() {
        reject(new Error("XCOP is unavailable from origin " + origin));
    }

    function getMessageIfTrustedSender(e) {
        if (e.source === iframeWindow && e.origin === origin) {
            return JSON.parse(e.data);
        } else {
            return null;
        }
    }

    function readyMessageHandler(e) {
        var message = getMessageIfTrustedSender(e);
        if (message && message.type === "XCOP-READY") {
            clearTimeout(iframeTimer);
            window.removeEventListener("message", readyMessageHandler);
            window.addEventListener("message", responseMessageHandler);
            xcopReadyDeferred.resolve(xhrProxy);
        } else if (message && message.type === "XCOP-ERROR") {
            reject(new Error(message.message));
        }
    }

    function responseMessageHandler(e) {
        var message = getMessageIfTrustedSender(e);
        if (message && message.type === "XCOP-RESPONSE") {
            var response = message.response;
            var deferred = queue[message.id].deferred;
            delete queue[message.id];
            deferred.resolve(response);
        } else if (message && message.type === "XCOP-RESPONSE-ERROR") {
            var deferred = queue[message.id].deferred;
            delete queue[message.id];
            deferred.reject(new Error("XCOP XMLHttpRequest Error"));
        }
    }

    if (!origin || origin === locationOrigin || options.useCors) {
        return Q.resolve(xhrLocal); // No need to proxy so use native/local XHR.
    } else {
        var id = 0;
        var queue = {};
        var xcopReadyDeferred = Q.defer();

        window.addEventListener("message", readyMessageHandler); // Setup reverse listener.

        var iframe = document.createElement("iframe");
        iframe.style.display = "none";
        document.body.appendChild(iframe);
        var iframeWindow = iframe.contentWindow;
        var iframeTimer = setTimeout(xcopTimeout, (options.proxyTimeout || 15) * 1000);
        iframe.src = origin + (options.xcopDocument || "/xcop.html") +
            "?origin=" + encodeURIComponent(locationOrigin) +
            "&ver=" + encodeURIComponent(version);

        return xcopReadyDeferred.promise;
    }
};
<commit_msg>Don't JSON.parse if not a string.<commit_after>"use strict";

var Q = require("q");
var xhrLocal = require("./xhr");
var version = require("../package.json").version;

module.exports = function (origin, options) {

    var locationOrigin = location.protocol + "//" + location.host;
    options = options || {};

    function destroy() {
        if (iframe) {
            window.removeEventListener("message", responseMessageHandler);
            iframe.parentNode.removeChild(iframe);
        }
    }

    function xhrProxy(request) {
        var deferred = Q.defer();
        if (typeof request === "string") {
            request = { url: request };
        }
        queue[id] = { deferred: deferred };
        iframeWindow.postMessage(JSON.stringify({ id: id, request: request }), origin); // Post to the xhr proxy.
        id = (id + 1) % 65536; // Recycle ids (eventually).
        return deferred.promise;
    }
    xhrProxy.destroy = destroy;

    function reject(err) {
        clearTimeout(iframeTimer);
        window.removeEventListener("message", readyMessageHandler);
        iframe.parentNode.removeChild(iframe);
        xcopReadyDeferred.reject(err);
    }

    function xcopTimeout() {
        reject(new Error("XCOP is unavailable from origin " + origin));
    }

    function getMessageIfTrustedSender(e) {
        var parsedData = null;
        if (e.source === iframeWindow && e.origin === origin) {
            try {
                parsedData = typeof e.data === "string" ? JSON.parse(e.data) : e.data;
            }
            catch(ex) {}
        }
        return parsedData;
    }

    function readyMessageHandler(e) {
        var message = getMessageIfTrustedSender(e);
        if (message && message.type === "XCOP-READY") {
            clearTimeout(iframeTimer);
            window.removeEventListener("message", readyMessageHandler);
            window.addEventListener("message", responseMessageHandler);
            xcopReadyDeferred.resolve(xhrProxy);
        } else if (message && message.type === "XCOP-ERROR") {
            reject(new Error(message.message));
        }
    }

    function responseMessageHandler(e) {
        var message = getMessageIfTrustedSender(e);
        if (message && message.type === "XCOP-RESPONSE") {
            var response = message.response;
            var deferred = queue[message.id].deferred;
            delete queue[message.id];
            deferred.resolve(response);
        } else if (message && message.type === "XCOP-RESPONSE-ERROR") {
            var deferred = queue[message.id].deferred;
            delete queue[message.id];
            deferred.reject(new Error("XCOP XMLHttpRequest Error"));
        }
    }

    if (!origin || origin === locationOrigin || options.useCors) {
        return Q.resolve(xhrLocal); // No need to proxy so use native/local XHR.
    } else {
        var id = 0;
        var queue = {};
        var xcopReadyDeferred = Q.defer();

        window.addEventListener("message", readyMessageHandler); // Setup reverse listener.

        var iframe = document.createElement("iframe");
        iframe.style.display = "none";
        document.body.appendChild(iframe);
        var iframeWindow = iframe.contentWindow;
        var iframeTimer = setTimeout(xcopTimeout, (options.proxyTimeout || 15) * 1000);
        iframe.src = origin + (options.xcopDocument || "/xcop.html") +
            "?origin=" + encodeURIComponent(locationOrigin) +
            "&ver=" + encodeURIComponent(version);

        return xcopReadyDeferred.promise;
    }
};
<|endoftext|>


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

module.exports = function (grunt) {
	'use strict';

	// Create a SpriteMaker function
	function SpriteMaker() {
		var data = this.data,
			options = this.options({});

		grunt.verbose.writeflags(options, 'Options');
		grunt.verbose.writeflags(data, 'Data');

		this.files.forEach(function(filePair) {
grunt.verbose.writeln(filePair.dest);
		});
	}

	// Export the SpriteMaker function
	grunt.registerMultiTask('sprite', 'Spritesheet making utility', SpriteMaker);
};
<commit_msg>Get to the point of writing out sprite images. No testing as of yet, but soon.<commit_after>var spritesmith = require('spritesmith'),
	_ = require('underscore'),
	fs = require('fs'),
	path = require('path');

function ExtFormat() {
  this.formatObj = {};
}
ExtFormat.prototype = {
  'add': function (name, val) {
    this.formatObj[name] = val;
  },
  'get': function (filepath) {
    // Grab the extension from the filepath
    var ext = path.extname(filepath),
        lowerExt = ext.toLowerCase();

    // Look up the file extenion from our format object
    var formatObj = this.formatObj,
        format = formatObj[lowerExt];
    return format;
  }
};

// Create img and css formats
var imgFormats = new ExtFormat(),
    cssFormats = new ExtFormat();

// Add our img formats
imgFormats.add('.png', 'png');
imgFormats.add('.jpg', 'jpeg');
imgFormats.add('.jpeg', 'jpeg');

// Add our css formats
cssFormats.add('.styl', 'stylus');
cssFormats.add('.stylus', 'stylus');
cssFormats.add('.sass', 'sass');
cssFormats.add('.scss', 'scss');
cssFormats.add('.less', 'less');
cssFormats.add('.json', 'json');

module.exports = function (grunt) {
	'use strict';

	// Create a SpriteMaker function
	function SpriteMaker() {
		var data = this.data,
			that = this,
			options = this.options({
				engine: 'auto',
				algorithm: 'top-down',
			});

		grunt.verbose.writeflags(options, 'Options');
		grunt.verbose.writeflags(data, 'Data');

		// Create an async callback
		var cb = this.async(),
			spriteCount = 0;

		this.files.forEach(function(sprite) {
			var exportOpts = sprite.imgOpts || {};
			_.defaults(exportOpts, data.imgOpts);
			_.defaults(exportOpts, {'format': imgFormats.get(sprite.dest) || 'png'});

			var spritesmithParams = {
				src: sprite.src,
				engine: options.engine,
				algorithm: options.algorithm,
				exportOpts: exportOpts
			};
			spritesmith(spritesmithParams, function (err, result) {
				// If an error occurred, callback with it
				if (err) {
					grunt.fatal(err);
					return cb(err);
				}

				// Otherwise, write out the result to destImg
				var destDir = path.dirname(sprite.dest);
				grunt.file.mkdir(destDir);
				fs.writeFileSync(sprite.dest, result.image, 'binary');

				// Otherwise, print a success message.
				grunt.log.writeln('Files "' + sprite.dest + '" created.');

				// Callback
				spriteCount++;
				if (spriteCount == that.files.length) {
					cb(true);
				}
			});
		});
	}

	// Export the SpriteMaker function
	grunt.registerMultiTask('sprite', 'Spritesheet making utility', SpriteMaker);
};
<|endoftext|>


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

    //// JavaScript Code ////

    //// Angular Code ////
    angular.module('codeine').constant('Constants', {
        CODEINE_NODES_PROJECT_NAME : 'Codeine_Internal_Nodes_Project',
        CODEINE_WEB_SERVER : location.hostname.indexOf('127.0.0.1') === -1  ? '' : 'http://icsl2356.iil.intel.com:12377',
        CODEINE_API_PREFIX : location.hostname.indexOf('127.0.0.1') === -1  ? '/api' : '/api-with-token',
        //CODEINE_WEB_SERVER : location.hostname.indexOf('127.0.0.1') === -1  ? '' : 'http://localhost:12347',
        EVENTS : {
            TAGS_CHANGED : 'tagsChanged',
            BREADCRUMB_CLICKED : 'breadcrumbClicked'
        }
    });

})(angular);<commit_msg>Update constants.js<commit_after>(function (angular) {
    'use strict';

    //// JavaScript Code ////

    //// Angular Code ////
    angular.module('codeine').constant('Constants', {
        CODEINE_NODES_PROJECT_NAME : 'Codeine_Internal_Nodes_Project',
        CODEINE_WEB_SERVER : (location.port === '9000' && location.hostname === '127.0.0.1')  ? 'http://icsl2356.iil.intel.com:12377' : '',
        CODEINE_API_PREFIX : (location.port === '9000' && location.hostname === '127.0.0.1')  ? '/api-with-token' : '/api',
        //CODEINE_WEB_SERVER : location.hostname.indexOf('127.0.0.1') === -1  ? '' : 'http://localhost:12347',
        EVENTS : {
            TAGS_CHANGED : 'tagsChanged',
            BREADCRUMB_CLICKED : 'breadcrumbClicked'
        }
    });

})(angular);
<|endoftext|>


<commit_before>/// <reference path="../typings/jquery/jquery.d.ts"/>
/// <reference path="../typings/d3/d3.d.ts"/>

//Inheritance from base ojbect
//make sure this is called before any additions to Method_Simple.prototype
Method_Simple.prototype = Object.create(Base_Method.prototype);
// Important object globals
Method_Simple.prototype.default_radius = 6;
Method_Simple.prototype.prev_currentDateMin;
Method_Simple.prototype.prev_currentDateMax;
Method_Simple.prototype.filteredLinks;
Method_Simple.prototype.svg;
Method_Simple.prototype.svgContainer;
Method_Simple.prototype.svgTranslation;
Method_Simple.prototype.forceLayout;
//Method_Simple.prototype.graphLink;
//Method_Simple.prototype.graphNode;

//Method constructor
function Method_Simple() {
  this.name = "simple";
  this.parameters = [
    //{ name: "Test Slider", ptype: "slider", minval: 0, maxval: 10, step: 1, pval: 0 },
    //{ name: "Test TextBox", ptype: "textbox", pval: "" },
    { name: "Disable rest", ptype: "checkbox", pval: false },
    { name: "Cumulative Links", ptype: "checkbox", pval: true, func: function () { this.filteredLinks = undefined; this.filteredNodes = undefined; } },
    { name: "Cumulative Nodes", ptype: "checkbox", pval: true, func: function () { this.filteredLinks = undefined; this.filteredNodes = undefined; } }
  ];
  this.nodeChannels = [
    { name: "Node Colour", ctype: "catagory", inUse: false, dataParam: "" },
    { name: "Gravity Point", ctype: "catagory", inUse: false, dataParam: "" },
    { name: "Node Size", ctype: "numeric", inUse: false, dataParam: "" },
  ];
  this.linkChannels = [
    { name: "Link Colour", ctype: "catagory", inUse: false, dataParam: "" },
    { name: "Link Length", ctype: "numeric", inUse: false, dataParam: "" },
    { name: "Link Width", ctype: "numeric", inUse: false, dataParam: "" },
  ];
}

Method_Simple.prototype.Load = function () { };

Method_Simple.prototype.Unload = function () {
  if (this.svg != undefined) {
    this.svg.selectAll("*").remove();
    this.svg.remove();
  }
  this.svg = undefined;
  if (this.forceLayout != undefined) {
    this.forceLayout.stop();
  }
  this.forceLayout = undefined;
  this.svgContainer = undefined;
  this.svgTranslation = undefined;
 // this.graphLink = undefined;
 //this.graphNode = undefined;
};

Method_Simple.prototype.foci = [
  { x: 400, y: 0 },
  { x: 200, y: - 346 },
  { x: - 200, y: - 346 },
  { x: - 400, y: 0 },
  { x: 200, y: 346 }
];

Method_Simple.prototype.SetData = function (d) {
  this.data = d;
  this.filteredLinks = undefined;
  this.filteredNodes = undefined;
  this.RedoNodes();
  this.RedoLinks();
};

//######################################################################
//########    Main Update
//######################################################################

Method_Simple.prototype.Update = function () {
  Base_Method.prototype.Update.call(this);
  if (this.data == null) { return; }
  //force a tick
  this.forceLayout.resume();
  //restart simulation
  //force.stop();
  //console.log("staring force %o, nodes: %o, links:%o",this.forceLayout,this.data.nodes,this.filteredLinks);
  var n = this.data.nodes.filter($.proxy(this.StandardNodeFilter, this));
  var l = this.data.links.filter($.proxy(this.QuickLinkFilter, this));
  this.forceLayout.nodes(n).links(l).on("tick", this.Tick.bind(this)).start();

  //Update Vis
  this.ShowLocalLayout("", null, n, l);
  this.RedoNodes();
  this.RedoLinks();
};

//######################################################################
//########    Redraw
//######################################################################

// The page has been resized or some other event that requires a redraw
Method_Simple.prototype.Redraw = function (w, h) {
  if (w !== undefined && h !== undefined) {
    this.width = w;
    this.height = h;
    this.halfWidth = w * 0.5;
    this.halfHeight = h * 0.5;
  }

  console.log("Redrawing");
  // force = customLayout()
  this.forceLayout = d3.layout.force()
    .gravity(.25)
    .charge(-840)
    .friction(0.3)
    .linkDistance(this.LinkLength.bind(this))
    .size([this.width, this.height]);

  var zoom = d3.behavior.zoom().scaleExtent([0.5, 10]).on("zoom", this.zoomed.bind(this));

  if (this.svg === undefined) {
    this.svg = d3.select("#chart").append("svg");
    this.svgContainer = this.svg.append("g");
  }
  this.svg.attr("width", this.width)
    .attr("height", this.height)
    .call(zoom);

};

Method_Simple.prototype.zoomed = function () {
  this.svgTranslation = d3.event.translate;
  this.scalefactor = d3.event.scale;
  this.svgContainer.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
};

//######################################################################
//########    Force layout tick
//######################################################################

Method_Simple.prototype.Wind = function () {
  this.data.nodes.forEach(function (o) {
    o.y += (20.0 * Math.random()) - 10.0;
    o.x += (20.0 * Math.random()) - 10.0;
  });
}

Method_Simple.prototype.Tick = function (e) {
  if (this.getParam("Disable rest").pval) {
    this.forceLayout.alpha(Math.max(this.forceLayout.alpha(), 0.1));
    this.forceLayout.resume();
  }
  var channel = this.getNodeChannel("Gravity Point");
  if (channel.inUse) {
    var k = .1 * e.alpha;
    this.data.nodes.forEach($.proxy(function (o, i, array) {
      var point = Math.round((this.foci.length - 1) * getAttributeAsPercentage(this.data, o, channel.dataParam, this.currentDateMin, this.currentDateMax));
      o.y += ((this.halfHeight + this.foci[point].y) - o.y) * k;
      o.x += ((this.halfWidth + this.foci[point].x) - o.x) * k;
    }, this));
  }
  this.UpdateLocalLayout("", null);
};

//######################################################################
//########    Channel Mapping Functions
//######################################################################

Method_Simple.prototype.RedoLinks = function () {
  if (this.visLinks === undefined) { return; }
  this.UpdateLocalLayout("", null);
  this.visLinks.style("stroke-width", this.LinkWidth.bind(this))
    .style("stroke-width", this.LinkWidth.bind(this))
    .style("stroke-dasharray", this.LinkDash.bind(this));
  this.forceLayout.alpha(Math.max(this.forceLayout.alpha(), 0.1));
};

Method_Simple.prototype.RedoNodes = function () {
  if (this.visNodes === undefined) { return; }
  this.UpdateLocalLayout("", null);
  this.visNodes
    .attr("r", this.NodeSize.bind(this))
    .style("fill", this.NodeColour.bind(this))
    .style("stroke", function (d) { return d3.rgb(fill(d.group)).darker(); });
};

var fill = d3.scale.category20().domain(d3.range(0, 20));

//------------------ Link Channels ----------------
Method_Simple.prototype.Linkcolour = function (d) {
  var channel = this.getLinkChannel("Link Colour");
  if (channel.inUse) {
    return d3.rgb(fill(Math.round(20.0 * getAttributeAsPercentage(this.data, d, channel.dataParam, this.currentDateMin, this.currentDateMax)))).darker();
  } else {
    return "black";
  }
};

Method_Simple.prototype.LinkWidth = function (d) {
  var channel = this.getLinkChannel("Link Width");
  if (channel.inUse) {
    var q = (3.5 * getAttributeAsPercentage(this.data, d, channel.dataParam, this.currentDateMin, this.currentDateMax))
    if (q == 0) {
      q = "0.5";
    }
    return q + "px";
  } else {
    return "1.5px";
  }
};

Method_Simple.prototype.LinkDash = function (d) {
  var channel = this.getLinkChannel("Link Width");
  if (channel.inUse) {
    var q = getAttributeAsPercentage(this.data, d, channel.dataParam, this.currentDateMin, this.currentDateMax);
    if (q == 0) {
      return "10";
    }
  }
  return "0";
};

Method_Simple.prototype.LinkLength = function (d) {
  var channel = this.getLinkChannel("Link Length");
  if (channel.inUse) {
    return 100 * getAttributeAsPercentage(this.data, d, channel.dataParam, this.currentDateMin, this.currentDateMax);
  } else {
    return 50;
  }
};
//------------------ Node Channels ----------------
Method_Simple.prototype.NodeColour = function (d) {
  var channel = this.getNodeChannel("Node Colour");
  if (channel.inUse) {
    return d3.rgb(fill(Math.round(20.0 * getAttributeAsPercentage(this.data, d, channel.dataParam, this.currentDateMin, this.currentDateMax)))).darker();
  } else {
    return "black";
  }
};

Method_Simple.prototype.NodeSize = function (d) {
  var channel = this.getNodeChannel("Node Size");
  if (channel.inUse) {
    return (this.default_radius - .75) + this.default_radius * getAttributeAsPercentage(this.data, d, channel.dataParam, this.currentDateMin, this.currentDateMax);
  } else {
    return this.default_radius - .75;
  }
};

Method_Simple.prototype.GravityPoint = function (d) {
  var channel = this.getNodeChannel("Gravity Point");
  if (channel.inUse) {
    return 1;
  } else {
    return 0;
  }
};<commit_msg>method_Simple tidy<commit_after>/// <reference path="../typings/jquery/jquery.d.ts"/>
/// <reference path="../typings/d3/d3.d.ts"/>

//Inheritance from base ojbect
//make sure this is called before any additions to Method_Simple.prototype
Method_Simple.prototype = Object.create(Base_Method.prototype);
// Important object globals
Method_Simple.prototype.default_radius = 6;
Method_Simple.prototype.prev_currentDateMin;
Method_Simple.prototype.prev_currentDateMax;
Method_Simple.prototype.svg;
Method_Simple.prototype.svgContainer;
Method_Simple.prototype.svgTranslation;
Method_Simple.prototype.forceLayout;

//Method constructor
function Method_Simple() {
  this.name = "simple";
  this.parameters = [
    //{ name: "Test Slider", ptype: "slider", minval: 0, maxval: 10, step: 1, pval: 0 },
    //{ name: "Test TextBox", ptype: "textbox", pval: "" },
    { name: "Disable rest", ptype: "checkbox", pval: false },
    { name: "Cumulative Links", ptype: "checkbox", pval: true, func: function () {/*Todo: refilter*/ } },
    { name: "Cumulative Nodes", ptype: "checkbox", pval: true, func: function () {/*Todo: refilter*/ } }
  ];
  this.nodeChannels = [
    { name: "Node Colour", ctype: "catagory", inUse: false, dataParam: "" },
    { name: "Gravity Point", ctype: "catagory", inUse: false, dataParam: "" },
    { name: "Node Size", ctype: "numeric", inUse: false, dataParam: "" },
  ];
  this.linkChannels = [
    { name: "Link Colour", ctype: "catagory", inUse: false, dataParam: "" },
    { name: "Link Length", ctype: "numeric", inUse: false, dataParam: "" },
    { name: "Link Width", ctype: "numeric", inUse: false, dataParam: "" },
  ];
}

Method_Simple.prototype.Load = function () { };

Method_Simple.prototype.Unload = function () {
  if (this.svg != undefined) {
    this.svg.selectAll("*").remove();
    this.svg.remove();
  }
  this.svg = undefined;
  if (this.forceLayout != undefined) {
    this.forceLayout.stop();
  }
  this.forceLayout = undefined;
};

Method_Simple.prototype.foci = [
  { x: 400, y: 0 },
  { x: 200, y: - 346 },
  { x: - 200, y: - 346 },
  { x: - 400, y: 0 },
  { x: 200, y: 346 }
];

Method_Simple.prototype.SetData = function (d) {
  this.data = d;
  this.filteredLinks = undefined;
  this.filteredNodes = undefined;
  this.RedoNodes();
  this.RedoLinks();
};

//######################################################################
//########    Main Update
//######################################################################

Method_Simple.prototype.Update = function () {
  Base_Method.prototype.Update.call(this);
  if (this.data == null) { return; }
  //force a tick
  this.forceLayout.resume();
  //restart simulation
  //force.stop();
  //console.log("staring force %o, nodes: %o, links:%o",this.forceLayout,this.data.nodes,this.filteredLinks);
  var n = this.data.nodes.filter($.proxy(this.StandardNodeFilter, this));
  var l = this.data.links.filter($.proxy(this.QuickLinkFilter, this));
  this.forceLayout.nodes(n).links(l).on("tick", this.Tick.bind(this)).start();

  //Update Vis
  this.ShowLocalLayout("", null, n, l);
  this.RedoNodes();
  this.RedoLinks();
};

//######################################################################

// The page has been resized or some other event that requires a redraw
Method_Simple.prototype.Redraw = function (w, h) {
  if (w !== undefined && h !== undefined) {
    this.width = w;
    this.height = h;
    this.halfWidth = w * 0.5;
    this.halfHeight = h * 0.5;
  }

  console.log("Redrawing");
  // force = customLayout()
  this.forceLayout = d3.layout.force()
    .gravity(.25)
    .charge(-840)
    .friction(0.3)
    .linkDistance(this.LinkLength.bind(this))
    .size([this.width, this.height]);

  var zoom = d3.behavior.zoom().scaleExtent([0.5, 10]).on("zoom", this.zoomed.bind(this));

  if (this.svg === undefined) {
    this.svg = d3.select("#chart").append("svg");
    this.svgContainer = this.svg.append("g");
  }
  this.svg.attr("width", this.width).attr("height", this.height).call(zoom);
};

//######################################################################

Method_Simple.prototype.zoomed = function () {
  this.svgTranslation = d3.event.translate;
  this.scalefactor = d3.event.scale;
  this.svgContainer.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
};

//######################################################################
//########    Force layout tick
//######################################################################

Method_Simple.prototype.Wind = function () {
  this.data.nodes.forEach(function (o) {
    o.y += (20.0 * Math.random()) - 10.0;
    o.x += (20.0 * Math.random()) - 10.0;
  });
}

Method_Simple.prototype.Tick = function (e) {
  if (this.getParam("Disable rest").pval) {
    this.forceLayout.alpha(Math.max(this.forceLayout.alpha(), 0.1));
    this.forceLayout.resume();
  }
  var channel = this.getNodeChannel("Gravity Point");
  if (channel.inUse) {
    var k = .1 * e.alpha;
    this.data.nodes.forEach($.proxy(function (o, i, array) {
      var point = Math.round((this.foci.length - 1) * getAttributeAsPercentage(this.data, o, channel.dataParam, this.currentDateMin, this.currentDateMax));
      o.y += ((this.halfHeight + this.foci[point].y) - o.y) * k;
      o.x += ((this.halfWidth + this.foci[point].x) - o.x) * k;
    }, this));
  }
  this.UpdateLocalLayout("", null);
};<|endoftext|>


<commit_before>define(['app', "text!views/forms/view/view-authority.directive.html",
'views/forms/view/view-contact-reference.directive',
'views/directives/record-options',
'views/directives/party-status'], function (app, template) {

app.directive("viewAuthority", [function () {
	return {
		restrict   : "EAC",
		template: template ,
		replace    : true,
		transclude : false,
		scope: {
			document: "=ngModel",
			target  : "@linkTarget",
			locale      : "=",
			allowDrafts : "@",
			hide : "@"
		},
		link : function ($scope)
		{
			$scope.contacts = undefined;
		},
		controller : ["$scope", "IStorage", function ($scope, storage)
		{
			$scope.locale = 'en' //set from record option directive
			//====================
			//
			//====================
			$scope.display = function(field) {

				if(!$scope.hide) return true; //show all fields

				return( $scope.hide.indexOf(field) >= 0 ? false : true);
			}

			//====================
			//
			//====================
			$scope.$watch("document.contacts", function(_new)
			{
				$scope.contacts = angular.fromJson(angular.toJson(_new||[]));

				if($scope.contacts)
					$scope.loadReferences($scope.contacts);
			});

			// $scope.$watch("document.absPolicyBasisForCompetencyRef", function(_new)
			// {
			// 	if ($scope.document && $scope.document.absPolicyBasisForCompetencyRef) {
			// 		$scope.absPolicyBasisForCompetencyRef = angular.fromJson(angular.toJson($scope.document.absPolicyBasisForCompetencyRef));
			//
			// 		if ($scope.absPolicyBasisForCompetencyRef)
			// 			$scope.loadReferences($scope.absPolicyBasisForCompetencyRef, true);
			// 	}
			// });

			//====================
			//
			//====================
			$scope.loadReferences = function(targets) {

				angular.forEach(targets, function(ref){

					storage.documents.get(ref.identifier, { info : true, body:true})
						.success(function(data){
							ref.document = data;
						})
						.error(function(error, code){
							if (code == 404 && $scope.allowDrafts == "true") {

								storage.drafts.get(ref.identifier, { cache : true})
									.success(function(data){
										ref.document = data;
									})
									.error(function(){
										ref.document  = undefined;
										ref.error     = error;
										ref.errorCode = code;
									});
							}

							ref.document  = undefined;
							ref.error     = error;
							ref.errorCode = code;

						});
				});
			};
		}]
	};
}]);
});
<commit_msg>remove hardcoded locale<commit_after>define(['app', "text!views/forms/view/view-authority.directive.html",
'views/forms/view/view-contact-reference.directive',
'views/directives/record-options',
'views/directives/party-status'], function (app, template) {

app.directive("viewAuthority", [function () {
	return {
		restrict   : "EAC",
		template: template ,
		replace    : true,
		transclude : false,
		scope: {
			document: "=ngModel",
			target  : "@linkTarget",
			locale      : "=",
			allowDrafts : "@",
			hide : "@"
		},
		link : function ($scope)
		{
			$scope.contacts = undefined;
		},
		controller : ["$scope", "IStorage", function ($scope, storage)
		{
			//====================
			//
			//====================
			$scope.display = function(field) {

				if(!$scope.hide) return true; //show all fields

				return( $scope.hide.indexOf(field) >= 0 ? false : true);
			}

			//====================
			//
			//====================
			$scope.$watch("document.contacts", function(_new)
			{
				$scope.contacts = angular.fromJson(angular.toJson(_new||[]));

				if($scope.contacts)
					$scope.loadReferences($scope.contacts);
			});

			// $scope.$watch("document.absPolicyBasisForCompetencyRef", function(_new)
			// {
			// 	if ($scope.document && $scope.document.absPolicyBasisForCompetencyRef) {
			// 		$scope.absPolicyBasisForCompetencyRef = angular.fromJson(angular.toJson($scope.document.absPolicyBasisForCompetencyRef));
			//
			// 		if ($scope.absPolicyBasisForCompetencyRef)
			// 			$scope.loadReferences($scope.absPolicyBasisForCompetencyRef, true);
			// 	}
			// });

			//====================
			//
			//====================
			$scope.loadReferences = function(targets) {

				angular.forEach(targets, function(ref){

					storage.documents.get(ref.identifier, { info : true, body:true})
						.success(function(data){
							ref.document = data;
						})
						.error(function(error, code){
							if (code == 404 && $scope.allowDrafts == "true") {

								storage.drafts.get(ref.identifier, { cache : true})
									.success(function(data){
										ref.document = data;
									})
									.error(function(){
										ref.document  = undefined;
										ref.error     = error;
										ref.errorCode = code;
									});
							}

							ref.document  = undefined;
							ref.error     = error;
							ref.errorCode = code;

						});
				});
			};
		}]
	};
}]);
});
<|endoftext|>


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

var assert = require('../support/assert');

var _ = require('underscore');

var LayergroupToken = require('../../lib/cartodb/models/layergroup_token');

var PgQueryRunner = require('../../lib/cartodb/backends/pg_query_runner');
var CartodbWindshaft = require('../../lib/cartodb/server');
var serverOptions = require('../../lib/cartodb/server_options');
var server = new CartodbWindshaft(serverOptions);
server.setMaxListeners(0);

describe('tests from old api translated to multilayer', function() {

    var layergroupUrl = '/api/v1/map';

    var keysToDelete;

    beforeEach(function() {
        keysToDelete = {};
    });

    afterEach(function(done) {
        testHelper.deleteRedisKeys(keysToDelete, done);
    });

    var wadusSql = 'select 1 as cartodb_id, null::geometry as the_geom_webmercator';
    var pointSql = "SELECT 'SRID=3857;POINT(0 0)'::geometry as the_geom_webmercator, 1::int as cartodb_id";

    function singleLayergroupConfig(sql, cartocss) {
        return {
            version: '1.0.0',
            layers: [
                {
                    type: 'mapnik',
                    options: {
                        sql: sql,
                        cartocss: cartocss,
                        cartocss_version: '2.0.1'
                    }
                }
            ]
        };
    }

    function createRequest(layergroup, userHost, apiKey) {
        var url = layergroupUrl;
        if (apiKey) {
            url += '?api_key=' + apiKey;
        }
        return {
            url: url,
            method: 'POST',
            headers: {
                host: userHost || 'localhost',
                'Content-Type': 'application/json'
            },
            data: JSON.stringify(layergroup)
        };
    }

    it("layergroup creation fails if CartoCSS is bogus", function(done) {
        var layergroup = singleLayergroupConfig(wadusSql, '#my_table3{');
        assert.response(server,
            createRequest(layergroup),
            {
                status: 400
            },
            function(res) {
                var parsed = JSON.parse(res.body);
                assert.ok(parsed.errors[0].match(/^style0/));
                assert.ok(parsed.errors[0].match(/missing closing/));
                done();
            }
        );
    });

    it("multiple bad styles returns 400 with all errors", function(done) {
        var layergroup = singleLayergroupConfig(wadusSql, '#my_table4{backgxxxxxround-color:#fff;foo:bar}');
        assert.response(server,
            createRequest(layergroup),
            {
                status: 400
            },
            function(res) {
                var parsed = JSON.parse(res.body);
                assert.equal(parsed.errors.length, 1);
                assert.ok(parsed.errors[0].match(/^style0/));
                assert.ok(parsed.errors[0].match(/Unrecognized rule: backgxxxxxround-color/));
                assert.ok(parsed.errors[0].match(/Unrecognized rule: foo/));
                done();
            }
        );
    });

    // Zoom is a special variable
    it("Specifying zoom level in CartoCSS does not need a 'zoom' variable in SQL output", function(done) {
        var layergroup = singleLayergroupConfig(pointSql, '#gadm4 [ zoom>=3] { marker-fill:red; }');

        assert.response(server,
            createRequest(layergroup),
            {
                status: 200
            },
            function(res) {
                var parsed = JSON.parse(res.body);
                assert.ok(parsed.layergroupid);
                assert.equal(res.headers['x-layergroup-id'], parsed.layergroupid);

                keysToDelete['map_cfg|' + LayergroupToken.parse(parsed.layergroupid).token] = 0;
                keysToDelete['user:localhost:mapviews:global'] = 5;

                done();
            }
        );
    });

    // See https://github.com/CartoDB/Windshaft-cartodb/issues/88
    it("getting a tile from a user-specific database should return an expected tile", function(done) {
        var layergroup = singleLayergroupConfig(pointSql, '#layer { marker-fill:red; }');

        var backupDBHost = global.environment.postgres.host;
        global.environment.postgres.host = '6.6.6.6';

        assert.response(server,
            createRequest(layergroup, 'cartodb250user'),
            {
                status: 200
            },
            function(res) {
                var parsed = JSON.parse(res.body);
                assert.ok(parsed.layergroupid);
                assert.equal(res.headers['x-layergroup-id'], parsed.layergroupid);

                keysToDelete['map_cfg|' + LayergroupToken.parse(parsed.layergroupid).token] = 0;
                keysToDelete['user:cartodb250user:mapviews:global'] = 5;

                global.environment.postgres.host = backupDBHost;
                done();
            }
        );
    });

    // See https://github.com/CartoDB/Windshaft-cartodb/issues/89
    it("getting a tile with a user-specific database password", function(done) {
        var layergroup = singleLayergroupConfig(pointSql, '#layer { marker-fill:red; }');

        var backupDBPass = global.environment.postgres_auth_pass;
        global.environment.postgres_auth_pass = '<%= user_password %>';

        assert.response(server,
            createRequest(layergroup, 'cartodb250user', '4321'),
            {
                status: 200
            },
            function(res) {
                var parsed = JSON.parse(res.body);
                assert.ok(parsed.layergroupid);
                assert.equal(res.headers['x-layergroup-id'], parsed.layergroupid);

                keysToDelete['map_cfg|' + LayergroupToken.parse(parsed.layergroupid).token] = 0;
                keysToDelete['user:cartodb250user:mapviews:global'] = 5;

                global.environment.postgres_auth_pass = backupDBPass;
                done();
            }
        );
    });

    it("creating a layergroup from lzma param",  function(done){
        var params = {
            config: JSON.stringify(singleLayergroupConfig(pointSql, '#layer { marker-fill:red; }'))
        };

        testHelper.lzma_compress_to_base64(JSON.stringify(params), 1, function(err, lzma) {
            if (err) {
                return done(err);
            }
            assert.response(server,
                {
                    url: layergroupUrl + '?lzma=' + encodeURIComponent(lzma),
                    method: 'GET',
                    headers: {
                        host: 'localhost'
                    },
                    encoding: 'binary'
                },
                {
                    status: 200
                },
                function(res) {
                    var parsed = JSON.parse(res.body);
                    assert.ok(parsed.layergroupid);

                    keysToDelete['map_cfg|' + LayergroupToken.parse(parsed.layergroupid).token] = 0;
                    keysToDelete['user:localhost:mapviews:global'] = 5;

                    done();
                }
            );
        });
    });

    it("creating a layergroup from lzma param, invalid json input",  function(done) {
        var params = {
            config: 'WADUS'
        };

        testHelper.lzma_compress_to_base64(JSON.stringify(params), 1, function(err, lzma) {
            if (err) {
                return done(err);
            }
            assert.response(server,
                {
                    url: layergroupUrl + '?lzma=' + encodeURIComponent(lzma),
                    method: 'GET',
                    headers: {
                        host: 'localhost'
                    },
                    encoding: 'binary'
                },
                {
                    status: 400
                },
                function(res) {
                    var parsed = JSON.parse(res.body);
                    assert.deepEqual(parsed, { errors: [ 'Unexpected token W' ] });

                    done();
                }
            );
        });
    });

    it("uses queries postgresql to figure affected tables in query",  function(done) {
        var tableName = 'gadm4';
        var expectedCacheChannel = _.template('<%= databaseName %>:public.<%= tableName %>', {
            databaseName: _.template(global.environment.postgres_auth_user, {user_id:1}) + '_db',
            tableName: tableName
        });

        var layergroup =  singleLayergroupConfig('select * from ' + tableName, '#gadm4 { marker-fill: red; }');

        assert.response(server,
            {
                url: layergroupUrl + '?config=' + encodeURIComponent(JSON.stringify(layergroup)),
                method: 'GET',
                headers: {
                    host: 'localhost'
                }
            },
            {
                status: 200
            },
            function(res) {
                var parsed = JSON.parse(res.body);
                assert.ok(parsed.layergroupid);

                assert.ok(res.headers.hasOwnProperty('x-cache-channel'));
                assert.equal(res.headers['x-cache-channel'], expectedCacheChannel);

                assert.equal(res.headers['x-layergroup-id'], parsed.layergroupid);

                keysToDelete['map_cfg|' + LayergroupToken.parse(parsed.layergroupid).token] = 0;
                keysToDelete['user:localhost:mapviews:global'] = 5;

                done();
            }
        );
    });

    // https://github.com/CartoDB/cartodb-postgresql/issues/86
    it.skip("should not fail with long table names because table name length limit",  function(done) {
        var tableName = 'long_table_name_with_enough_chars_to_break_querytables_function';
        var expectedCacheChannel = _.template('<%= databaseName %>:public.<%= tableName %>', {
            databaseName: _.template(global.environment.postgres_auth_user, {user_id:1}) + '_db',
            tableName: tableName
        });

        var layergroup =  singleLayergroupConfig('select * from ' + tableName, '#layer { marker-fill: red; }');

        assert.response(server,
            {
                url: layergroupUrl + '?config=' + encodeURIComponent(JSON.stringify(layergroup)),
                method: 'GET',
                headers: {
                    host: 'localhost'
                }
            },
            {
                status: 200
            },
            function(res) {
                var parsed = JSON.parse(res.body);
                assert.ok(parsed.layergroupid);

                assert.ok(res.headers.hasOwnProperty('x-cache-channel'));
                assert.equal(res.headers['x-cache-channel'], expectedCacheChannel);

                assert.equal(res.headers['x-layergroup-id'], parsed.layergroupid);

                done();
            }
        );
    });

    it("creates layergroup fails when postgresql queries fail to figure affected tables in query",  function(done) {

        var runQueryFn = PgQueryRunner.prototype.run;
        PgQueryRunner.prototype.run = function(username, query, queryHandler, callback) {
            return queryHandler(new Error('fake error message'), [], callback);
        };

        var layergroup =  singleLayergroupConfig('select * from gadm4', '#gadm4 { marker-fill: red; }');

        assert.response(server,
            {
                url: layergroupUrl + '?config=' + encodeURIComponent(JSON.stringify(layergroup)),
                method: 'GET',
                headers: {
                    host: 'localhost'
                }
            },
            {
                status: 400
            },
            function(res) {
                PgQueryRunner.prototype.run = runQueryFn;

                assert.ok(!res.headers.hasOwnProperty('x-cache-channel'));

                // TODO when affected tables query makes the request to fail layergroup should be removed
                keysToDelete['map_cfg|f14693f2d7b6dcf4629724b3d1efe22d'] = 0;
                keysToDelete['user:localhost:mapviews:global'] = 5;

                var parsed = JSON.parse(res.body);
                assert.deepEqual(parsed, {
                    errors: ["Error: could not fetch affected tables or last updated time: fake error message"]
                });

                done();
            }
        );
    });

    it("tile requests works when postgresql queries fail to figure affected tables in query",  function(done) {
        var layergroup =  singleLayergroupConfig('select * from gadm4', '#gadm4 { marker-fill: red; }');
        assert.response(server,
            {
                url: layergroupUrl + '?config=' + encodeURIComponent(JSON.stringify(layergroup)),
                method: 'GET',
                headers: {
                    host: 'localhost'
                }
            },
            {
                status: 200
            },
            function(res) {

                keysToDelete['map_cfg|' + LayergroupToken.parse(JSON.parse(res.body).layergroupid).token] = 0;
                keysToDelete['user:localhost:mapviews:global'] = 5;

                var runQueryFn = PgQueryRunner.prototype.run;
                PgQueryRunner.prototype.run = function(username, query, queryHandler, callback) {
                    return queryHandler(new Error('failed to query database for affected tables'), [], callback);
                };

                // reset internal cacheChannel cache
                server.layergroupAffectedTablesCache.cache.reset();

                assert.response(server,
                    {
                        url: layergroupUrl + _.template('/<%= layergroupId %>/<%= z %>/<%= x %>/<%= y %>.png', {
                            layergroupId: JSON.parse(res.body).layergroupid,
                            z: 0,
                            x: 0,
                            y: 0
                        }),
                        method: 'GET',
                        headers: {
                            host: 'localhost'
                        },
                        encoding: 'binary'
                    },
                    {
                        status: 200
                    },
                    function(res) {
                        assert.ok(!res.headers.hasOwnProperty('x-cache-channel'));
                        PgQueryRunner.prototype.run = runQueryFn;
                        done();
                    }
                );
            }
        );
    });

});
<commit_msg>Fix tests after upgrading windshaft, which includes a fix for layergroupid<commit_after>var testHelper = require('../support/test_helper');

var assert = require('../support/assert');

var _ = require('underscore');

var LayergroupToken = require('../../lib/cartodb/models/layergroup_token');

var PgQueryRunner = require('../../lib/cartodb/backends/pg_query_runner');
var CartodbWindshaft = require('../../lib/cartodb/server');
var serverOptions = require('../../lib/cartodb/server_options');
var server = new CartodbWindshaft(serverOptions);
server.setMaxListeners(0);

describe('tests from old api translated to multilayer', function() {

    var layergroupUrl = '/api/v1/map';

    var keysToDelete;

    beforeEach(function() {
        keysToDelete = {};
    });

    afterEach(function(done) {
        testHelper.deleteRedisKeys(keysToDelete, done);
    });

    var wadusSql = 'select 1 as cartodb_id, null::geometry as the_geom_webmercator';
    var pointSql = "SELECT 'SRID=3857;POINT(0 0)'::geometry as the_geom_webmercator, 1::int as cartodb_id";

    function singleLayergroupConfig(sql, cartocss) {
        return {
            version: '1.0.0',
            layers: [
                {
                    type: 'mapnik',
                    options: {
                        sql: sql,
                        cartocss: cartocss,
                        cartocss_version: '2.0.1'
                    }
                }
            ]
        };
    }

    function createRequest(layergroup, userHost, apiKey) {
        var url = layergroupUrl;
        if (apiKey) {
            url += '?api_key=' + apiKey;
        }
        return {
            url: url,
            method: 'POST',
            headers: {
                host: userHost || 'localhost',
                'Content-Type': 'application/json'
            },
            data: JSON.stringify(layergroup)
        };
    }

    it("layergroup creation fails if CartoCSS is bogus", function(done) {
        var layergroup = singleLayergroupConfig(wadusSql, '#my_table3{');
        assert.response(server,
            createRequest(layergroup),
            {
                status: 400
            },
            function(res) {
                var parsed = JSON.parse(res.body);
                assert.ok(parsed.errors[0].match(/^style0/));
                assert.ok(parsed.errors[0].match(/missing closing/));
                done();
            }
        );
    });

    it("multiple bad styles returns 400 with all errors", function(done) {
        var layergroup = singleLayergroupConfig(wadusSql, '#my_table4{backgxxxxxround-color:#fff;foo:bar}');
        assert.response(server,
            createRequest(layergroup),
            {
                status: 400
            },
            function(res) {
                var parsed = JSON.parse(res.body);
                assert.equal(parsed.errors.length, 1);
                assert.ok(parsed.errors[0].match(/^style0/));
                assert.ok(parsed.errors[0].match(/Unrecognized rule: backgxxxxxround-color/));
                assert.ok(parsed.errors[0].match(/Unrecognized rule: foo/));
                done();
            }
        );
    });

    // Zoom is a special variable
    it("Specifying zoom level in CartoCSS does not need a 'zoom' variable in SQL output", function(done) {
        var layergroup = singleLayergroupConfig(pointSql, '#gadm4 [ zoom>=3] { marker-fill:red; }');

        assert.response(server,
            createRequest(layergroup),
            {
                status: 200
            },
            function(res) {
                var parsed = JSON.parse(res.body);
                assert.ok(parsed.layergroupid);
                assert.equal(res.headers['x-layergroup-id'], parsed.layergroupid);

                keysToDelete['map_cfg|' + LayergroupToken.parse(parsed.layergroupid).token] = 0;
                keysToDelete['user:localhost:mapviews:global'] = 5;

                done();
            }
        );
    });

    // See https://github.com/CartoDB/Windshaft-cartodb/issues/88
    it("getting a tile from a user-specific database should return an expected tile", function(done) {
        var layergroup = singleLayergroupConfig(pointSql, '#layer { marker-fill:red; }');

        var backupDBHost = global.environment.postgres.host;
        global.environment.postgres.host = '6.6.6.6';

        assert.response(server,
            createRequest(layergroup, 'cartodb250user'),
            {
                status: 200
            },
            function(res) {
                var parsed = JSON.parse(res.body);
                assert.ok(parsed.layergroupid);
                assert.equal(res.headers['x-layergroup-id'], parsed.layergroupid);

                keysToDelete['map_cfg|' + LayergroupToken.parse(parsed.layergroupid).token] = 0;
                keysToDelete['user:cartodb250user:mapviews:global'] = 5;

                global.environment.postgres.host = backupDBHost;
                done();
            }
        );
    });

    // See https://github.com/CartoDB/Windshaft-cartodb/issues/89
    it("getting a tile with a user-specific database password", function(done) {
        var layergroup = singleLayergroupConfig(pointSql, '#layer { marker-fill:red; }');

        var backupDBPass = global.environment.postgres_auth_pass;
        global.environment.postgres_auth_pass = '<%= user_password %>';

        assert.response(server,
            createRequest(layergroup, 'cartodb250user', '4321'),
            {
                status: 200
            },
            function(res) {
                var parsed = JSON.parse(res.body);
                assert.ok(parsed.layergroupid);
                assert.equal(res.headers['x-layergroup-id'], parsed.layergroupid);

                keysToDelete['map_cfg|' + LayergroupToken.parse(parsed.layergroupid).token] = 0;
                keysToDelete['user:cartodb250user:mapviews:global'] = 5;

                global.environment.postgres_auth_pass = backupDBPass;
                done();
            }
        );
    });

    it("creating a layergroup from lzma param",  function(done){
        var params = {
            config: JSON.stringify(singleLayergroupConfig(pointSql, '#layer { marker-fill:red; }'))
        };

        testHelper.lzma_compress_to_base64(JSON.stringify(params), 1, function(err, lzma) {
            if (err) {
                return done(err);
            }
            assert.response(server,
                {
                    url: layergroupUrl + '?lzma=' + encodeURIComponent(lzma),
                    method: 'GET',
                    headers: {
                        host: 'localhost'
                    },
                    encoding: 'binary'
                },
                {
                    status: 200
                },
                function(res) {
                    var parsed = JSON.parse(res.body);
                    assert.ok(parsed.layergroupid);

                    keysToDelete['map_cfg|' + LayergroupToken.parse(parsed.layergroupid).token] = 0;
                    keysToDelete['user:localhost:mapviews:global'] = 5;

                    done();
                }
            );
        });
    });

    it("creating a layergroup from lzma param, invalid json input",  function(done) {
        var params = {
            config: 'WADUS'
        };

        testHelper.lzma_compress_to_base64(JSON.stringify(params), 1, function(err, lzma) {
            if (err) {
                return done(err);
            }
            assert.response(server,
                {
                    url: layergroupUrl + '?lzma=' + encodeURIComponent(lzma),
                    method: 'GET',
                    headers: {
                        host: 'localhost'
                    },
                    encoding: 'binary'
                },
                {
                    status: 400
                },
                function(res) {
                    var parsed = JSON.parse(res.body);
                    assert.deepEqual(parsed, { errors: [ 'Unexpected token W' ] });

                    done();
                }
            );
        });
    });

    it("uses queries postgresql to figure affected tables in query",  function(done) {
        var tableName = 'gadm4';
        var expectedCacheChannel = _.template('<%= databaseName %>:public.<%= tableName %>', {
            databaseName: _.template(global.environment.postgres_auth_user, {user_id:1}) + '_db',
            tableName: tableName
        });

        var layergroup =  singleLayergroupConfig('select * from ' + tableName, '#gadm4 { marker-fill: red; }');

        assert.response(server,
            {
                url: layergroupUrl + '?config=' + encodeURIComponent(JSON.stringify(layergroup)),
                method: 'GET',
                headers: {
                    host: 'localhost'
                }
            },
            {
                status: 200
            },
            function(res) {
                var parsed = JSON.parse(res.body);
                assert.ok(parsed.layergroupid);

                assert.ok(res.headers.hasOwnProperty('x-cache-channel'));
                assert.equal(res.headers['x-cache-channel'], expectedCacheChannel);

                assert.equal(res.headers['x-layergroup-id'], parsed.layergroupid);

                keysToDelete['map_cfg|' + LayergroupToken.parse(parsed.layergroupid).token] = 0;
                keysToDelete['user:localhost:mapviews:global'] = 5;

                done();
            }
        );
    });

    // https://github.com/CartoDB/cartodb-postgresql/issues/86
    it.skip("should not fail with long table names because table name length limit",  function(done) {
        var tableName = 'long_table_name_with_enough_chars_to_break_querytables_function';
        var expectedCacheChannel = _.template('<%= databaseName %>:public.<%= tableName %>', {
            databaseName: _.template(global.environment.postgres_auth_user, {user_id:1}) + '_db',
            tableName: tableName
        });

        var layergroup =  singleLayergroupConfig('select * from ' + tableName, '#layer { marker-fill: red; }');

        assert.response(server,
            {
                url: layergroupUrl + '?config=' + encodeURIComponent(JSON.stringify(layergroup)),
                method: 'GET',
                headers: {
                    host: 'localhost'
                }
            },
            {
                status: 200
            },
            function(res) {
                var parsed = JSON.parse(res.body);
                assert.ok(parsed.layergroupid);

                assert.ok(res.headers.hasOwnProperty('x-cache-channel'));
                assert.equal(res.headers['x-cache-channel'], expectedCacheChannel);

                assert.equal(res.headers['x-layergroup-id'], parsed.layergroupid);

                done();
            }
        );
    });

    it("creates layergroup fails when postgresql queries fail to figure affected tables in query",  function(done) {

        var runQueryFn = PgQueryRunner.prototype.run;
        PgQueryRunner.prototype.run = function(username, query, queryHandler, callback) {
            return queryHandler(new Error('fake error message'), [], callback);
        };

        var layergroup =  singleLayergroupConfig('select * from gadm4', '#gadm4 { marker-fill: red; }');

        assert.response(server,
            {
                url: layergroupUrl + '?config=' + encodeURIComponent(JSON.stringify(layergroup)),
                method: 'GET',
                headers: {
                    host: 'localhost'
                }
            },
            {
                status: 400
            },
            function(res) {
                PgQueryRunner.prototype.run = runQueryFn;

                assert.ok(!res.headers.hasOwnProperty('x-cache-channel'));

                // TODO when affected tables query makes the request to fail layergroup should be removed
                keysToDelete['map_cfg|4fb7bd7008322ce66f22d20aebba1ab0'] = 0;
                keysToDelete['user:localhost:mapviews:global'] = 5;

                var parsed = JSON.parse(res.body);
                assert.deepEqual(parsed, {
                    errors: ["Error: could not fetch affected tables or last updated time: fake error message"]
                });

                done();
            }
        );
    });

    it("tile requests works when postgresql queries fail to figure affected tables in query",  function(done) {
        var layergroup =  singleLayergroupConfig('select * from gadm4', '#gadm4 { marker-fill: red; }');
        assert.response(server,
            {
                url: layergroupUrl + '?config=' + encodeURIComponent(JSON.stringify(layergroup)),
                method: 'GET',
                headers: {
                    host: 'localhost'
                }
            },
            {
                status: 200
            },
            function(res) {

                keysToDelete['map_cfg|' + LayergroupToken.parse(JSON.parse(res.body).layergroupid).token] = 0;
                keysToDelete['user:localhost:mapviews:global'] = 5;

                var runQueryFn = PgQueryRunner.prototype.run;
                PgQueryRunner.prototype.run = function(username, query, queryHandler, callback) {
                    return queryHandler(new Error('failed to query database for affected tables'), [], callback);
                };

                // reset internal cacheChannel cache
                server.layergroupAffectedTablesCache.cache.reset();

                assert.response(server,
                    {
                        url: layergroupUrl + _.template('/<%= layergroupId %>/<%= z %>/<%= x %>/<%= y %>.png', {
                            layergroupId: JSON.parse(res.body).layergroupid,
                            z: 0,
                            x: 0,
                            y: 0
                        }),
                        method: 'GET',
                        headers: {
                            host: 'localhost'
                        },
                        encoding: 'binary'
                    },
                    {
                        status: 200
                    },
                    function(res) {
                        assert.ok(!res.headers.hasOwnProperty('x-cache-channel'));
                        PgQueryRunner.prototype.run = runQueryFn;
                        done();
                    }
                );
            }
        );
    });

});
<|endoftext|>


<commit_before>/**
 * [bakDb 数据库备份/恢复]
 */

function bakDb(power){
  return function*(next){
    if(this.session.userInfo.group.power === 'root' || JSON.parse(this.session.userInfo.group.power)[power]){
      yield next;
    }else{
      if(this.request.method === 'GET'){
        this.redirect('./disAllow')
      }else{
        this.body = {
          status: 'FAIL::当前用户不具备操作权限'
        }
      }
    }
  }
}

export default bakDb;
<commit_msg>删除多余文件<commit_after><|endoftext|>


<commit_before>import React, { Component } from 'react';
import AutoComplete from 'material-ui/AutoComplete';
import TextField from 'material-ui/TextField';
import FlatButton from 'material-ui/FlatButton';
import { FormattedMessage, injectIntl, defineMessages } from 'react-intl';
import { Map, Marker, TileLayer } from 'react-leaflet';
import config from 'config'; // eslint-disable-line require-path-exists/exists
import { black54, caption } from '../../styles/js/shared';
import { stringHelper } from '../../customHelpers';

const messages = defineMessages({
  searching: {
    id: 'geoLocationRespondTask.searching',
    defaultMessage: 'Searching...',
  },
  notFound: {
    id: 'geoLocationRespondTask.notFound',
    defaultMessage: 'Sorry, this place was not found. Please try another search.',
  },
  error: {
    id: 'geoLocationRespondTask.error',
    defaultMessage: 'Sorry, an error occurred while updating the task. Please try again and contact {supportEmail} if the condition persists.',
  },
});

class GeolocationRespondTask extends Component {
  static canSubmit() {
    // TODO Use React ref
    const { value } = document.getElementById('task__response-geolocation-name');
    return value && value.length;
  }

  constructor(props) {
    super(props);

    const { response } = this.props;
    let name = '';
    let coordinatesString = '';
    let lat = 0;
    let lng = 0;
    if (response) {
      const geoJSON = JSON.parse(this.props.response);
      ({ name } = geoJSON.properties);
      const { coordinates } = geoJSON.geometry;
      if (coordinates[0] || coordinates[1]) {
        lat = parseFloat(coordinates[0]).toFixed(7);
        lng = parseFloat(coordinates[1]).toFixed(7);
        coordinatesString = `${lat}, ${lng}`;
      }
    }

    this.state = {
      taskAnswerDisabled: true,
      zoom: 5,
      draggable: true,
      lat,
      lng,
      name,
      coordinatesString,
      original: {
        lat,
        lng,
        name,
        coordinatesString,
      },
      searchResult: [],
    };

    this.timer = null;
  }

  componentDidMount() {
    this.reloadMap();
  }

  componentDidUpdate() {
    this.reloadMap();
  }

  getCoordinates() {
    let coordinates = [0, 0];
    try {
      const { coordinatesString } = this.state;
      if (coordinatesString && coordinatesString !== '') {
        const pair = coordinatesString.split(/, ?/);
        coordinates = [parseFloat(pair[0]), parseFloat(pair[1])];
      }
    } catch (e) {
      coordinates = [0, 0];
    }
    return coordinates;
  }

  toggleDraggable() {
    this.setState({ draggable: !this.state.draggable });
  }

  updatePosition() {
    const { lat, lng } = this.marker.leafletElement.getLatLng();
    // eslint-disable-next-line no-underscore-dangle
    const zoom = this.marker.leafletElement._map.getZoom();
    const coordinatesString = `${parseFloat(lat).toFixed(7)}, ${parseFloat(lng).toFixed(7)}`;
    this.setState({
      lat, lng, zoom, coordinatesString, focus: true,
    });
  }

  updatePositionOnClick(e) {
    const { lat, lng } = e.latlng;
    // eslint-disable-next-line no-underscore-dangle
    const zoom = this.marker.leafletElement._map.getZoom();
    const coordinatesString = `${parseFloat(lat).toFixed(7)}, ${parseFloat(lng).toFixed(7)}`;
    this.setState({
      lat, lng, zoom, coordinatesString, focus: true, message: '',
    });
    this.autoComplete.setState({ searchText: '' });
  }

  handlePressButton() {
    if (GeolocationRespondTask.canSubmit()) {
      this.handleSubmit();
    }
  }

  handleChange(e) {
    this.setState({
      taskAnswerDisabled: !GeolocationRespondTask.canSubmit(),
      name: e.target.value,
      message: '',
    });
  }

  handleSearchText(query) {
    const keystrokeWait = 1000;

    this.setState({ message: '' });

    clearTimeout(this.timer);

    if (query) {
      this.setState({ message: this.props.intl.formatMessage(messages.searching) });
      this.timer = setTimeout(() => this.geoCodeQueryOpenCage(query), keystrokeWait);
    }
  }

  handleChangeCoordinates(e) {
    this.setState({
      taskAnswerDisabled: !GeolocationRespondTask.canSubmit(),
      coordinatesString: e.target.value,
    });

    const keystrokeWait = 1000;

    this.setState({ message: '' });

    clearTimeout(this.timer);

    if (e.target.value) {
      this.autoComplete.setState({ searchText: '' });
      this.timer = setTimeout(() => this.handleBlur(), keystrokeWait);
    }
  }

  handleBlur() {
    const coordinates = this.getCoordinates();
    this.setState({
      taskAnswerDisabled: !GeolocationRespondTask.canSubmit(),
      lat: coordinates[0],
      lng: coordinates[1],
    });
    this.autoComplete.setState({ searchText: '' });
  }

  handleSubmit() {
    if (!this.state.taskAnswerDisabled) {
      const name = document.getElementById('task__response-geolocation-name').value;
      const coordinates = this.getCoordinates();

      const response = JSON.stringify({
        type: 'Feature',
        geometry: {
          type: 'Point',
          coordinates,
        },
        properties: {
          name,
        },
      });

      this.setState({ taskAnswerDisabled: true });
      this.props.onSubmit(response, false);
    }
  }

  reloadMap() {
    if (this.marker && this.marker.leafletElement) {
      // eslint-disable-next-line no-underscore-dangle
      this.marker.leafletElement._map.invalidateSize();
    }
  }

  handleCancel() {
    const ori = this.state.original;
    this.setState({
      focus: false,
      name: ori.name,
      lat: ori.lat,
      lng: ori.lng,
      coordinatesString: ori.coordinatesString,
      message: '',
    });
    if (this.props.onDismiss) {
      this.props.onDismiss();
    }
    this.autoComplete.setState({ searchText: '' });
  }

  // eslint-disable-next-line class-methods-use-this
  handleKeyPress(e) {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
    }
  }

  geoCodeQueryOpenCage = (query) => {
    const apiKey = config.opencageApiKey;
    const providerUrl = `https://api.opencagedata.com/geocode/v1/json?key=${apiKey}&q=${query}&no_annotations=1`;

    fetch(providerUrl)
      .then((response) => {
        if (!response.ok) {
          throw Error(this.props.intl.formatMessage(messages.error, { supportEmail: stringHelper('SUPPORT_EMAIL') }));
        }
        return response.json();
      })
      .then((response) => {
        const searchResult = response.results || [];
        let message = '';
        if (!searchResult.length) {
          message = this.props.intl.formatMessage(messages.notFound);
        }
        this.setState({ searchResult, message });
      })
      .catch(error => this.setState({ message: error.message }));
  };

  render() {
    const position = [this.state.lat, this.state.lng];

    const actionBtns = (

        <FlatButton
          className="task__cancel"
          label={
            <FormattedMessage id="geolocationRespondTask.cancelTask" defaultMessage="Cancel" />
          }
          onClick={this.handleCancel.bind(this)}
        />
        <FlatButton
          disabled={this.state.taskAnswerDisabled}
          className="task__save"
          label={
            <FormattedMessage
              id="geolocationRespondTask.answerTask"
              defaultMessage="Answer task"
            />
          }
          primary
          onClick={this.handlePressButton.bind(this)}
        />

    );

    const selectCallback = (obj) => {
      if (typeof obj === 'object') {
        const { lat, lng } = obj.geometry;
        this.setState(
          {
            name: obj.formatted,
            coordinatesString: `${lat}, ${lng}`,
          },
          this.handleBlur,
        );
      }
    };

    const dataSourceConfig = {
      text: 'formatted',
      value: 'geometry',
    };

    return (

        <AutoComplete
          id="geolocationsearch"
          floatingLabelText={
            <FormattedMessage
              id="geolocationRespondTask.searchMap"
              defaultMessage="Search the map"
            />
          }
          name="geolocationsearch"
          dataSource={this.state.searchResult}
          dataSourceConfig={dataSourceConfig}
          filter={AutoComplete.noFilter}
          onFocus={() => { this.setState({ focus: true }); }}
          onKeyPress={this.handleKeyPress.bind(this)}
          onNewRequest={selectCallback}
          ref={(a) => { this.autoComplete = a; }}
          onUpdateInput={this.handleSearchText.bind(this)}
          fullWidth
        />

          {this.state.message }

        <TextField
          id="task__response-geolocation-name"
          className="task__response-input"
          floatingLabelText={
            <FormattedMessage
              id="geolocationRespondTask.placeName"
              defaultMessage="Customize place name"
            />
          }
          name="response"
          value={this.state.name}
          onChange={this.handleChange.bind(this)}
          onFocus={() => { this.setState({ focus: true }); }}
          fullWidth
          multiLine
        />
        <TextField
          id="task__response-geolocation-coordinates"
          className="task__response-coordinates-input"
          floatingLabelText={
            <FormattedMessage
              id="geolocationRespondTask.coordinates"
              defaultMessage="Latitude, Longitude"
            />
          }
          name="coordinates"
          onChange={this.handleChangeCoordinates.bind(this)}
          onFocus={() => { this.setState({ focus: true }); }}
          onBlur={this.handleBlur.bind(this)}
          value={this.state.coordinatesString}
          fullWidth
        />

          <Map
            style={{ height: '400px' }}
            center={position}
            zoom={this.state.zoom}
            onClick={this.updatePositionOnClick.bind(this)}
          >
            <TileLayer
              attribution="2017 OpenStreetMap"
              url="http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png"
            />
            <Marker
              draggable={this.state.draggable}
              onDragend={this.updatePosition.bind(this)}
              position={position}
              ref={(m) => { this.marker = m; }}
            />
          </Map>

        { this.state.focus || this.props.response ? actionBtns : null }

    );
  }
}

export default injectIntl(GeolocationRespondTask);
<commit_msg>Add class name to geolocation search options div<commit_after>import React, { Component } from 'react';
import AutoComplete from 'material-ui/AutoComplete';
import TextField from 'material-ui/TextField';
import FlatButton from 'material-ui/FlatButton';
import { FormattedMessage, injectIntl, defineMessages } from 'react-intl';
import { Map, Marker, TileLayer } from 'react-leaflet';
import config from 'config'; // eslint-disable-line require-path-exists/exists
import { black54, caption } from '../../styles/js/shared';
import { stringHelper } from '../../customHelpers';

const messages = defineMessages({
  searching: {
    id: 'geoLocationRespondTask.searching',
    defaultMessage: 'Searching...',
  },
  notFound: {
    id: 'geoLocationRespondTask.notFound',
    defaultMessage: 'Sorry, this place was not found. Please try another search.',
  },
  error: {
    id: 'geoLocationRespondTask.error',
    defaultMessage: 'Sorry, an error occurred while updating the task. Please try again and contact {supportEmail} if the condition persists.',
  },
});

class GeolocationRespondTask extends Component {
  static canSubmit() {
    // TODO Use React ref
    const { value } = document.getElementById('task__response-geolocation-name');
    return value && value.length;
  }

  constructor(props) {
    super(props);

    const { response } = this.props;
    let name = '';
    let coordinatesString = '';
    let lat = 0;
    let lng = 0;
    if (response) {
      const geoJSON = JSON.parse(this.props.response);
      ({ name } = geoJSON.properties);
      const { coordinates } = geoJSON.geometry;
      if (coordinates[0] || coordinates[1]) {
        lat = parseFloat(coordinates[0]).toFixed(7);
        lng = parseFloat(coordinates[1]).toFixed(7);
        coordinatesString = `${lat}, ${lng}`;
      }
    }

    this.state = {
      taskAnswerDisabled: true,
      zoom: 5,
      draggable: true,
      lat,
      lng,
      name,
      coordinatesString,
      original: {
        lat,
        lng,
        name,
        coordinatesString,
      },
      searchResult: [],
    };

    this.timer = null;
  }

  componentDidMount() {
    this.reloadMap();
  }

  componentDidUpdate() {
    this.reloadMap();
  }

  getCoordinates() {
    let coordinates = [0, 0];
    try {
      const { coordinatesString } = this.state;
      if (coordinatesString && coordinatesString !== '') {
        const pair = coordinatesString.split(/, ?/);
        coordinates = [parseFloat(pair[0]), parseFloat(pair[1])];
      }
    } catch (e) {
      coordinates = [0, 0];
    }
    return coordinates;
  }

  toggleDraggable() {
    this.setState({ draggable: !this.state.draggable });
  }

  updatePosition() {
    const { lat, lng } = this.marker.leafletElement.getLatLng();
    // eslint-disable-next-line no-underscore-dangle
    const zoom = this.marker.leafletElement._map.getZoom();
    const coordinatesString = `${parseFloat(lat).toFixed(7)}, ${parseFloat(lng).toFixed(7)}`;
    this.setState({
      lat, lng, zoom, coordinatesString, focus: true,
    });
  }

  updatePositionOnClick(e) {
    const { lat, lng } = e.latlng;
    // eslint-disable-next-line no-underscore-dangle
    const zoom = this.marker.leafletElement._map.getZoom();
    const coordinatesString = `${parseFloat(lat).toFixed(7)}, ${parseFloat(lng).toFixed(7)}`;
    this.setState({
      lat, lng, zoom, coordinatesString, focus: true, message: '',
    });
    this.autoComplete.setState({ searchText: '' });
  }

  handlePressButton() {
    if (GeolocationRespondTask.canSubmit()) {
      this.handleSubmit();
    }
  }

  handleChange(e) {
    this.setState({
      taskAnswerDisabled: !GeolocationRespondTask.canSubmit(),
      name: e.target.value,
      message: '',
    });
  }

  handleSearchText(query) {
    const keystrokeWait = 1000;

    this.setState({ message: '' });

    clearTimeout(this.timer);

    if (query) {
      this.setState({ message: this.props.intl.formatMessage(messages.searching) });
      this.timer = setTimeout(() => this.geoCodeQueryOpenCage(query), keystrokeWait);
    }
  }

  handleChangeCoordinates(e) {
    this.setState({
      taskAnswerDisabled: !GeolocationRespondTask.canSubmit(),
      coordinatesString: e.target.value,
    });

    const keystrokeWait = 1000;

    this.setState({ message: '' });

    clearTimeout(this.timer);

    if (e.target.value) {
      this.autoComplete.setState({ searchText: '' });
      this.timer = setTimeout(() => this.handleBlur(), keystrokeWait);
    }
  }

  handleBlur() {
    const coordinates = this.getCoordinates();
    this.setState({
      taskAnswerDisabled: !GeolocationRespondTask.canSubmit(),
      lat: coordinates[0],
      lng: coordinates[1],
    });
    this.autoComplete.setState({ searchText: '' });
  }

  handleSubmit() {
    if (!this.state.taskAnswerDisabled) {
      const name = document.getElementById('task__response-geolocation-name').value;
      const coordinates = this.getCoordinates();

      const response = JSON.stringify({
        type: 'Feature',
        geometry: {
          type: 'Point',
          coordinates,
        },
        properties: {
          name,
        },
      });

      this.setState({ taskAnswerDisabled: true });
      this.props.onSubmit(response, false);
    }
  }

  reloadMap() {
    if (this.marker && this.marker.leafletElement) {
      // eslint-disable-next-line no-underscore-dangle
      this.marker.leafletElement._map.invalidateSize();
    }
  }

  handleCancel() {
    const ori = this.state.original;
    this.setState({
      focus: false,
      name: ori.name,
      lat: ori.lat,
      lng: ori.lng,
      coordinatesString: ori.coordinatesString,
      message: '',
    });
    if (this.props.onDismiss) {
      this.props.onDismiss();
    }
    this.autoComplete.setState({ searchText: '' });
  }

  // eslint-disable-next-line class-methods-use-this
  handleKeyPress(e) {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
    }
  }

  geoCodeQueryOpenCage = (query) => {
    const apiKey = config.opencageApiKey;
    const providerUrl = `https://api.opencagedata.com/geocode/v1/json?key=${apiKey}&q=${query}&no_annotations=1`;

    fetch(providerUrl)
      .then((response) => {
        if (!response.ok) {
          throw Error(this.props.intl.formatMessage(messages.error, { supportEmail: stringHelper('SUPPORT_EMAIL') }));
        }
        return response.json();
      })
      .then((response) => {
        const searchResult = response.results || [];
        let message = '';
        if (!searchResult.length) {
          message = this.props.intl.formatMessage(messages.notFound);
        }
        this.setState({ searchResult, message });
      })
      .catch(error => this.setState({ message: error.message }));
  };

  render() {
    const position = [this.state.lat, this.state.lng];

    const actionBtns = (

        <FlatButton
          className="task__cancel"
          label={
            <FormattedMessage id="geolocationRespondTask.cancelTask" defaultMessage="Cancel" />
          }
          onClick={this.handleCancel.bind(this)}
        />
        <FlatButton
          disabled={this.state.taskAnswerDisabled}
          className="task__save"
          label={
            <FormattedMessage
              id="geolocationRespondTask.answerTask"
              defaultMessage="Answer task"
            />
          }
          primary
          onClick={this.handlePressButton.bind(this)}
        />

    );

    const selectCallback = (obj) => {
      if (typeof obj === 'object') {
        const { lat, lng } = obj.geometry;
        this.setState(
          {
            name: obj.formatted,
            coordinatesString: `${lat}, ${lng}`,
          },
          this.handleBlur,
        );
      }
    };

    const dataSourceConfig = {
      text: 'formatted',
      value: 'geometry',
    };

    return (

        <AutoComplete
          id="geolocationsearch"
          floatingLabelText={
            <FormattedMessage
              id="geolocationRespondTask.searchMap"
              defaultMessage="Search the map"
            />
          }
          name="geolocationsearch"
          dataSource={this.state.searchResult}
          dataSourceConfig={dataSourceConfig}
          filter={AutoComplete.noFilter}
          onFocus={() => { this.setState({ focus: true }); }}
          onKeyPress={this.handleKeyPress.bind(this)}
          onNewRequest={selectCallback}
          ref={(a) => { this.autoComplete = a; }}
          onUpdateInput={this.handleSearchText.bind(this)}
          menuProps={{ className: 'task__response-geolocation-search-options' }}
          fullWidth
        />

          {this.state.message }

        <TextField
          id="task__response-geolocation-name"
          className="task__response-input"
          floatingLabelText={
            <FormattedMessage
              id="geolocationRespondTask.placeName"
              defaultMessage="Customize place name"
            />
          }
          name="response"
          value={this.state.name}
          onChange={this.handleChange.bind(this)}
          onFocus={() => { this.setState({ focus: true }); }}
          fullWidth
          multiLine
        />
        <TextField
          id="task__response-geolocation-coordinates"
          className="task__response-coordinates-input"
          floatingLabelText={
            <FormattedMessage
              id="geolocationRespondTask.coordinates"
              defaultMessage="Latitude, Longitude"
            />
          }
          name="coordinates"
          onChange={this.handleChangeCoordinates.bind(this)}
          onFocus={() => { this.setState({ focus: true }); }}
          onBlur={this.handleBlur.bind(this)}
          value={this.state.coordinatesString}
          fullWidth
        />

          <Map
            style={{ height: '400px' }}
            center={position}
            zoom={this.state.zoom}
            onClick={this.updatePositionOnClick.bind(this)}
          >
            <TileLayer
              attribution="2017 OpenStreetMap"
              url="http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png"
            />
            <Marker
              draggable={this.state.draggable}
              onDragend={this.updatePosition.bind(this)}
              position={position}
              ref={(m) => { this.marker = m; }}
            />
          </Map>

        { this.state.focus || this.props.response ? actionBtns : null }

    );
  }
}

export default injectIntl(GeolocationRespondTask);
<|endoftext|>


<commit_before>const fs = require('fs');
const spawn = require('child_process').spawn;

/**
 * Helper function to determine if a git repo is already present in the directory.
 *
 * @param dir String - Directory to check.
 * @param callback Function (Object) - Callback returning an object with the origin git remote
 *										url at origin (May be empty).
 *										{ initialized: Boolean, url: String }
 *
 */
function exists(dir, callback) {
	fs.access(dir, fs.constants.F_OK, (err) => {
		const git = {
			initialised: false,
			remoteUrl: ''
		};

		if (err) {
			callback(git);
		}
		else {
			git.initialised = true;
			const gitConfig = spawn('git', ['config', '--get', 'remote.origin.url']);

			gitConfig.stdout.on('data', (data) => {
				git.url = data.toString('utf8').replace('\n', '');
			});

			gitConfig.on('close', () => {
				callback(git);
			});
		}
	});
}

function create(callback) {
	const gitInit = spawn('git', ['init']);

	gitInit.on('close', () => {
		callback();
	});
}

function addRemote(remote, url, callback) {
	const gitRemote = spawn('git', ['remote', 'add', remote, url]);

	gitRemote.on('close', () => {
		callback();
	});
}

module.exports = {
	exists: exists,
	create: create,
	addRemote: addRemote
};
<commit_msg>Change fs.access to fs.stat for backwards compatibility.<commit_after>const fs = require('fs');
const spawn = require('child_process').spawn;

/**
 * Helper function to determine if a git repo is already present in the directory.
 *
 * @param dir String - Directory to check.
 * @param callback Function (Object) - Callback returning an object with the origin git remote
 *										url at origin (May be empty).
 *										{ initialized: Boolean, url: String }
 *
 */
function exists(dir, callback) {
	fs.stat(dir, (err, stats) => {
		const git = {
			initialised: false,
			remoteUrl: ''
		};

		// Err implies that the directory does not exist.
		// !stats.isDirectory() ensures that .git is not a directory.
		if (err || !stats.isDirectory()) {
			callback(git);
		}
		else {
			git.initialised = true;
			const gitConfig = spawn('git', ['config', '--get', 'remote.origin.url']);

			gitConfig.stdout.on('data', (data) => {
				git.url = data.toString('utf8').replace('\n', '');
			});

			gitConfig.on('close', () => {
				callback(git);
			});
		}
	});
}

function create(callback) {
	const gitInit = spawn('git', ['init']);

	gitInit.on('close', () => {
		callback();
	});
}

function addRemote(remote, url, callback) {
	const gitRemote = spawn('git', ['remote', 'add', remote, url]);

	gitRemote.on('close', () => {
		callback();
	});
}

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


<commit_before>
( function() {
  var DOMParser_proto = thymol.thDomParser.prototype, real_parseFromString = DOMParser_proto.parseFromString;
  try {
    if( ( new thymol.thDomParser() ).parseFromString( "", "text/html" ) ) {
      return;
    }
  }
  catch( ignore ) {
    // Do nothing
  }
  DOMParser_proto.parseFromString = function( markup, type ) {
    var res, doc;
    if( /^\s*text\/html\s*(?:;|$)/i.test( type ) ) {
      doc = thymol.thDocument.implementation.createHTMLDocument( "" );
      if( markup.toLowerCase().indexOf( '<!doctype' ) > -1 ) {
        doc.documentElement.innerHTML = markup;
      }
      else {
        doc.body.innerHTML = markup;
      }
      res = doc;
    }
    else {
      res = real_parseFromString.apply( this, arguments );
    }
    return res;
  };
}() );

if( !Array.indexOf ) {
  Array.prototype.indexOf = function( obj, start ) {
    for( var i = ( start || 0 ); i < this.length; i++ ) {
      if( this[ i ] === obj ) {
        return i;
      }
    }
    return -1;
  };
};
<commit_msg>Unified access to DOM parser, prepare for domino.<commit_after>
( function() {
  var DOMParser_proto = thymol, real_thDomParse = DOMParser_proto.thDomParse;
  try {
    if( thymol.thDomParse( "", "text/html" ) ) {
      return;
    }
  }
  catch( ignore ) {
    // Do nothing
  }
  DOMParser_proto.thDomParse = function( markup, type ) {
    var res, doc;
    if( /^\s*text\/html\s*(?:;|$)/i.test( type ) ) {
      doc = thymol.thDocument.implementation.createHTMLDocument( "" );
      if( markup.toLowerCase().indexOf( '<!doctype' ) > -1 ) {
        doc.documentElement.innerHTML = markup;
      }
      else {
        doc.body.innerHTML = markup;
      }
      res = doc;
    }
    else {
      res = real_thDomParse.apply( this, arguments );
    }
    return res;
  };
}() );

if( !Array.indexOf ) {
  Array.prototype.indexOf = function( obj, start ) {
    for( var i = ( start || 0 ); i < this.length; i++ ) {
      if( this[ i ] === obj ) {
        return i;
      }
    }
    return -1;
  };
};
<|endoftext|>