<commit_before>

Task = function(){
    this.name;
    this.priority;
    this.dueDate;
    this.project;
    this.projectName;
    this.done;
    this.spot = 0;
}

TaskList = function () {
    var tasks = [];
    var _this = this;
    _this.name;
    _this.rank;
    _this.finished;

    this.getTasks = function () {
        return tasks;
    }

    this.addTask = function (newTask) {
        tasks.push(newTask);
        newTask.spot = tasks.length - 1;

    }

    this.removeTask = function (task) {
        tasks.splice(task.spot, 1);
        for (var i = 0; i < tasks.length; i++) {
            tasks[i].spot = i;
        }
    }

    this.display = function () {

        table = document.getElementById(_this.name);

        if (table.rows.length > 0) {
            for (i = 0; i < tasks.length; i++) {
                table.deleteRow();
            }
        }

        //headerRow = document.createElement('tr');
        pBox = document.createElement('input');
        pBox.type = 'checkbox';
        pBox.id = _this.rank;
        pBox.onclick = projectDone;
        header = document.createElement('th');
        header.innerHTML = _this.name;

        //table.appendChild(headerRow);
        //headerRow.appendChild(pBox);
        //headerRow.appendChild(header);

        table.appendChild(pBox);
        table.appendChild(header);

        header.onclick = function () {
            rows = table.rows;
           if (rows.style.display == 'none') {
                rows.style.display = 'block';
            } else {
                rows.style.display = 'none';
            }
        }

        for (i = 0; i < tasks.length; i++) {

            row = document.createElement('tr');
            row.className = _this.name;
            row.style.display = 'none';
            taskPlace = document.createElement('td');
            date = document.createElement('td');

            task = tasks[i];
            checkBox = document.createElement('input');
            checkBox.type = 'checkbox';
            checkBox.id = task.spot.toString();
            checkBox.onclick = taskDone;
            checkBox.className = _this.rank;
            taskPlace.innerHTML = task.name;
            taskPlace.className = task.priority;
            date.innerHTML = task.dueDate;

            table.appendChild(row);
            row.appendChild(checkBox);
            row.appendChild(taskPlace);
            row.appendChild(date);
        }

    }

}

saveAll = function () {
    res = [];
    var i;
    var j;
    for (j = 0; j < projectList.length; j++) {
        tasks = projectList[j].getTasks();
        for (i = 0; i < tasks.length; i++) {
            if (!tasks[i].done) {
                res.push(tasks[i]);
            }
        }
    }

    localStorage.setItem("todoDatabase", JSON.stringify(res));
}

restoreAll = function () {
    projectList = [];
    oldList = JSON.parse(localStorage.getItem("todoDatabase"));

    var current;
    var project;

    for (i = 0; i < oldList.length; i++) {
        current = oldList[i];
        if (current.spot == 0) {

            project = new TaskList();
            project.name = current.projectName;
            project.addTask(current);
            newTable = document.createElement('table');
            newTable.id = project.name;

            listSection = document.querySelector('article');
            listSection.appendChild(newTable);

            project.rank = projectList.length;
            project.finished = false;
            projectList.push(project);

            document.querySelector('#newProject').value = "";

            newOption = document.createElement('option');
            newOption.value = project.name;
            newOption.innerHTML = project.name;

            dropMenu = document.querySelector('#project');
            dropMenu.appendChild(newOption);

            project.display();
        } else {
            project = projectList[projectList.length - 1];
            project.addTask(current);
            project.display();
        }
    }
}

taskDone = function () {
    var place = parseInt(this.id);
    var project = projectList[this.className];
    var task = project.getTasks()[place];
    var name = this.nextSibling;
    var date = name.nextSibling;

    if (!task.done) {
        name.style.textDecoration = 'line-through';
        date.style.textDecoration = 'line-through';
        task.done = true;

    } else {
        name.style.textDecoration = 'none';
        date.style.textDecoration = 'none';
        task.done = false;
    }
    saveAll();
}

projectDone = function () {
    var place = this.id;
    var thisProject = projectList[place];
    var text = this.nextSibling;

    if (!thisProject.finished) {
        text.style.textDecoration = 'line-through';
        thisProject.finished = true;

    } else {
        text.style.textDecoration = 'none';
        thisProject.finished = false;
    }
    saveAll();
}

addProject = function () {
    project = new TaskList();
    project.name = document.querySelector("#newProject").value;
    newTable = document.createElement('table');
    newTable.id = project.name;

    listSection = document.querySelector('article');
    listSection.appendChild(newTable);

    project.rank = projectList.length;
    project.finished = false;
    projectList.push(project);

    project.display();
    document.querySelector('#newProject').value = "";

    newOption = document.createElement('option');
    newOption.value = project.name;
    newOption.innerHTML = project.name;

    dropMenu = document.querySelector('#project');
    dropMenu.appendChild(newOption);

    saveAll();
}

addTask = function () {

    newTask = new Task();

    projectName = document.querySelector('#project').value;

    for (var i = 0; i < projectList.length; i++) {
        if (projectList[i].name == projectName) {
            project = projectList[i];
        }
    }

    newTask.name = document.querySelector('#newTask').value;

    newTask.projectName = project.name;

    newTask.priority = document.querySelector('#priority').value;

    newTask.dueDate = document.querySelector('#date').value;

    newTask.done = false;

    newTask.project = project;

    table = document.querySelector('#' + projectName);

    project.addTask(newTask);

    project.display();

    document.querySelector('#newTask').value = "";
    saveAll();
}

<commit_msg>header may disappear onclick<commit_after>

Task = function(){
    this.name;
    this.priority;
    this.dueDate;
    this.project;
    this.projectName;
    this.done;
    this.spot = 0;
}

TaskList = function () {
    var tasks = [];
    var _this = this;
    _this.name;
    _this.rank;
    _this.finished;

    this.getTasks = function () {
        return tasks;
    }

    this.addTask = function (newTask) {
        tasks.push(newTask);
        newTask.spot = tasks.length - 1;

    }

    this.removeTask = function (task) {
        tasks.splice(task.spot, 1);
        for (var i = 0; i < tasks.length; i++) {
            tasks[i].spot = i;
        }
    }

    this.display = function () {

        table = document.getElementById(_this.name);

        if (table.rows.length > 0) {
            for (i = 0; i < tasks.length; i++) {
                table.deleteRow();
            }
        }

        headerRow = document.createElement('tr');
        pBox = document.createElement('input');
        pBox.type = 'checkbox';
        pBox.id = _this.rank;
        pBox.onclick = projectDone;
        header = document.createElement('th');
        header.innerHTML = _this.name;

        table.appendChild(headerRow);
        headerRow.appendChild(pBox);
        headerRow.appendChild(header);

        //table.appendChild(pBox);
        //table.appendChild(header);

        header.onclick = function () {
            alert('clicked')
            rows = table.rows;
           if (rows.style.display == 'none') {
                rows.style.display = 'block';
            } else {
                rows.style.display = 'none';
            }
        }

        for (i = 0; i < tasks.length; i++) {

            row = document.createElement('tr');
            row.className = _this.name;
            row.style.display = 'none';
            taskPlace = document.createElement('td');
            date = document.createElement('td');

            task = tasks[i];
            checkBox = document.createElement('input');
            checkBox.type = 'checkbox';
            checkBox.id = task.spot.toString();
            checkBox.onclick = taskDone;
            checkBox.className = _this.rank;
            taskPlace.innerHTML = task.name;
            taskPlace.className = task.priority;
            date.innerHTML = task.dueDate;

            table.appendChild(row);
            row.appendChild(checkBox);
            row.appendChild(taskPlace);
            row.appendChild(date);
        }

    }

}

saveAll = function () {
    res = [];
    var i;
    var j;
    for (j = 0; j < projectList.length; j++) {
        tasks = projectList[j].getTasks();
        for (i = 0; i < tasks.length; i++) {
            if (!tasks[i].done) {
                res.push(tasks[i]);
            }
        }
    }

    localStorage.setItem("todoDatabase", JSON.stringify(res));
}

restoreAll = function () {
    projectList = [];
    oldList = JSON.parse(localStorage.getItem("todoDatabase"));

    var current;
    var project;

    for (i = 0; i < oldList.length; i++) {
        current = oldList[i];
        if (current.spot == 0) {

            project = new TaskList();
            project.name = current.projectName;
            project.addTask(current);
            newTable = document.createElement('table');
            newTable.id = project.name;

            listSection = document.querySelector('article');
            listSection.appendChild(newTable);

            project.rank = projectList.length;
            project.finished = false;
            projectList.push(project);

            document.querySelector('#newProject').value = "";

            newOption = document.createElement('option');
            newOption.value = project.name;
            newOption.innerHTML = project.name;

            dropMenu = document.querySelector('#project');
            dropMenu.appendChild(newOption);

            project.display();
        } else {
            project = projectList[projectList.length - 1];
            project.addTask(current);
            project.display();
        }
    }
}

taskDone = function () {
    var place = parseInt(this.id);
    var project = projectList[this.className];
    var task = project.getTasks()[place];
    var name = this.nextSibling;
    var date = name.nextSibling;

    if (!task.done) {
        name.style.textDecoration = 'line-through';
        date.style.textDecoration = 'line-through';
        task.done = true;

    } else {
        name.style.textDecoration = 'none';
        date.style.textDecoration = 'none';
        task.done = false;
    }
    saveAll();
}

projectDone = function () {
    var place = this.id;
    var thisProject = projectList[place];
    var text = this.nextSibling;

    if (!thisProject.finished) {
        text.style.textDecoration = 'line-through';
        thisProject.finished = true;

    } else {
        text.style.textDecoration = 'none';
        thisProject.finished = false;
    }
    saveAll();
}

addProject = function () {
    project = new TaskList();
    project.name = document.querySelector("#newProject").value;
    newTable = document.createElement('table');
    newTable.id = project.name;

    listSection = document.querySelector('article');
    listSection.appendChild(newTable);

    project.rank = projectList.length;
    project.finished = false;
    projectList.push(project);

    project.display();
    document.querySelector('#newProject').value = "";

    newOption = document.createElement('option');
    newOption.value = project.name;
    newOption.innerHTML = project.name;

    dropMenu = document.querySelector('#project');
    dropMenu.appendChild(newOption);

    saveAll();
}

addTask = function () {

    newTask = new Task();

    projectName = document.querySelector('#project').value;

    for (var i = 0; i < projectList.length; i++) {
        if (projectList[i].name == projectName) {
            project = projectList[i];
        }
    }

    newTask.name = document.querySelector('#newTask').value;

    newTask.projectName = project.name;

    newTask.priority = document.querySelector('#priority').value;

    newTask.dueDate = document.querySelector('#date').value;

    newTask.done = false;

    newTask.project = project;

    table = document.querySelector('#' + projectName);

    project.addTask(newTask);

    project.display();

    document.querySelector('#newTask').value = "";
    saveAll();
}

<|endoftext|>


<commit_before>var log = require("npmlog");
var d3 = require("d3");

module.exports.peaks = function(data) {
	//peaks
	data.forEach(function(d) {
		d.peaks = {}
		var peak;
		d3.entries(d.values).forEach(function(year) {
			if (!peak || peak.value < year.value) {
				peak = {
					year: parseInt(year.key, 10),
					value: year.value
				};
			}
		});
		d.peaks.values = peak;
	});

	data.forEach(function(d) {
		var peak;
		d3.entries(d.percents).forEach(function(year) {
			if (!peak || peak.value < year.value) {
				peak = {
					year: parseInt(year.key, 10),
					value: year.value
				};
			}
		});
		d.peaks.percents = peak;
	});
}

module.exports.normalize = function(data) {
	// normalized data from percents
	data.forEach(function(d) {
		d.normalized = {};
		d3.entries(d.percents).forEach(function(year) {
			d.normalized[year.key] = year.value / d.peaks.percents.value
		});
	});
}

module.exports.pronunciation = function(data) {
	var CMUDict = require('cmudict').CMUDict;
	var cmudict = new CMUDict();

	data.forEach(function(d) {
		var stressed = cmudict.get(d.name);
		d.stressed = stressed || null;
		d.pronunciation = stressed ? stressed.replace(/[0-9]/g, "") : null;
		if (!stressed) {
			log.verbose("CMU doesn't know how to pronounce " + d.name);
		}
	});
	log.info("(Found pronunciations for " + data.filter(function(d) { return d.stressed; }).length + " of those.)");
}

module.exports.dense = function(data) {
	// fill in zero for names not present in given year if desired
	data.forEach(function(d) {
		years.forEach(function(year) {
			if (typeof d.values[year] == "undefined") {
				d.values[year] = 0;
				d.percents[year] = 0;
			}
		});
	});
}

module.exports.maxima = function(data, opts) {
	data.forEach(function(d) {
		d.maxima = maxima(d, opts);
	});
}

function maxima(name, opts) {
	// years to look in either direction before declaring it's a local maximum
	var window_size = 5,
		maxima = [];

	for (var year = opts.start; year <= opts.end; year += 1) {
		var isMaxima = true;
		for (var i = Math.max(opts.start, year - window_size); i <= Math.min(opts.end, year + window_size); i += 1) {
			if (typeof name.percents[i] == "undefined" || typeof name.percents[year] == "undefined") {
				isMaxima = false;
				break;
			}
			if ((i < year && name.percents[i] > name.percents[year]) || (i > year && name.percents[i] > name.percents[year])) {
				isMaxima = false;
				break;
			}
		}
		if (isMaxima && name.percents[year] / name.peaks.percents.value > 0.25) {
			maxima.push({
				year: year,
				value: name.values[year],
				percent: name.percents[year],
				height: name.percents[year] / name.peaks.percents.value
			});
		}
	}
	return maxima;
}<commit_msg>Fixed dense function<commit_after>var log = require("npmlog");
var d3 = require("d3");

module.exports.peaks = function(data) {
	//peaks
	data.forEach(function(d) {
		d.peaks = {}
		var peak;
		d3.entries(d.values).forEach(function(year) {
			if (!peak || peak.value < year.value) {
				peak = {
					year: parseInt(year.key, 10),
					value: year.value
				};
			}
		});
		d.peaks.values = peak;
	});

	data.forEach(function(d) {
		var peak;
		d3.entries(d.percents).forEach(function(year) {
			if (!peak || peak.value < year.value) {
				peak = {
					year: parseInt(year.key, 10),
					value: year.value
				};
			}
		});
		d.peaks.percents = peak;
	});
}

module.exports.normalize = function(data) {
	// normalized data from percents
	data.forEach(function(d) {
		d.normalized = {};
		d3.entries(d.percents).forEach(function(year) {
			d.normalized[year.key] = year.value / d.peaks.percents.value
		});
	});
}

module.exports.pronunciation = function(data) {
	var CMUDict = require('cmudict').CMUDict;
	var cmudict = new CMUDict();

	data.forEach(function(d) {
		var stressed = cmudict.get(d.name);
		d.stressed = stressed || null;
		d.pronunciation = stressed ? stressed.replace(/[0-9]/g, "") : null;
		if (!stressed) {
			log.verbose("CMU doesn't know how to pronounce " + d.name);
		}
	});
	log.info("(Found pronunciations for " + data.filter(function(d) { return d.stressed; }).length + " of those.)");
}

module.exports.dense = function(data, opts) {
	// fill in zero for names not present in given year if desired
	data.forEach(function(d) {
		for (var year = opts.start; year < opts.end; year += 1) {
			if (typeof d.values[year] == "undefined") {
				d.values[year] = 0;
				d.percents[year] = 0;
			}
		}
	});
}

module.exports.maxima = function(data, opts) {
	data.forEach(function(d) {
		d.maxima = maxima(d, opts);
	});
}

function maxima(name, opts) {
	// years to look in either direction before declaring it's a local maximum
	var window_size = 5,
		maxima = [];

	for (var year = opts.start; year <= opts.end; year += 1) {
		var isMaxima = true;
		for (var i = Math.max(opts.start, year - window_size); i <= Math.min(opts.end, year + window_size); i += 1) {
			if (typeof name.percents[i] == "undefined" || typeof name.percents[year] == "undefined") {
				isMaxima = false;
				break;
			}
			if ((i < year && name.percents[i] > name.percents[year]) || (i > year && name.percents[i] > name.percents[year])) {
				isMaxima = false;
				break;
			}
		}
		if (isMaxima && name.percents[year] / name.peaks.percents.value > 0.25) {
			maxima.push({
				year: year,
				value: name.values[year],
				percent: name.percents[year],
				height: name.percents[year] / name.peaks.percents.value
			});
		}
	}
	return maxima;
}<|endoftext|>


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

(function () {
  var tracers, formatters, zipkinCore_types;
  var Trace, Annotation, Endpoint, Int64;
  var forEach, has, getUniqueId, getNowMicros, getHex64;

  forEach = function(obj, f){
    Array.prototype.forEach.call(obj, f);
  };

  has = function(obj, val){
    return Object.hasOwnProperty.call(obj, val);
  };

	getUniqueId = function () {
		var random = new Int64(Math.random() * 0x7fffffff, Math.random() * 0x100000000);
		return random.toOctetString();
	};

	/**
	 * Get a hex representation of provided value
	 *
	 * @param {String|number} hex Ex: "0xffffeeeeffefefef", "ffffeeeeffefefef", 12342344543543
	 * NOTE: 0x12342344543543 is NOT a valid input
	 *
	 * @returns {Int64|undefined}
	 */
	getHex64 = function (hex) {
		try {
			return new Int64(hex).toOctetString();
		} catch (e) {
			return undefined;
		}
	};

	/**
	 * Return the current unix epoch timestamp in microseconds
	 * @return {number}
	 */
  getNowMicros = function() {
      return Date.now() * 1000;
  };

  /**
   * A Trace encapsulates information about the current span of this trace
   * and provides a mechanism for creating new child spans and recording
   * annotations for this span. It delegates to zero or more {Tracers} and
   * allows setting a default {Endpoint} to associate with {Annotation}s
   *
   * @param {String} name A string describing this span
   * @param {Hash} options A hash any or all or none of the following
   *    params, for which values will be generated if not provided:
   *
   * @param {Number} options.traceId 64-bit integer identifying this trace
   * @param {Number} options.spanId 64-bit integer identifying this span
   * @param {Number} options.parentSpanId 64-bit integer identifying this trace's
   *     parent span, or undefined.
   * @param {Array} options._tracers Zero or more {Tracers}
   */
  Trace = function(name, options) {
    var self = this;
    self.name = name;

    options = options || {};

    ['traceId', 'spanId', 'parentSpanId'].forEach(function(idName) {
      if (has(options, idName) && options[idName] !== null &&
        options[idName] !== undefined) {
        self[idName] = getHex64(options[idName]);
      } else if (idName !== 'parentSpanId') {
        self[idName] = getUniqueId();
      }
    });

    if (has(options, 'tracers') && options.tracers){
      self._tracers = options.tracers;
    } else {
      self._tracers = tracers.getTracers();
    }
  };

  /**
   * Create a new instance of this class derived from the current instance
   * such that:
   *    child.trace_id == current.trace_id, and
   *    child.parent_span_id == current.span_id
   * The child {Trace} will have a new unique {spanId} and if set, the
   * endpoint of the current {Trace} object.
   *
   * @param {String} name The name describing the new span represented by the
   *    new child {Trace} object.
   */
  Trace.prototype.child = function (name) {
    var optionalArgs = {
      traceId: this.traceId,
      parentSpanId: this.spanId,
      tracers: this._tracers
    };
    var trace = new Trace(name, optionalArgs);
    trace.setEndpoint(this.endpoint);
    return trace;
  };

  /**
   * Record an annotation for this {Trace}.  This is the primary entry point
   * for associating {Annotation}s with {Trace}s.  It will delegate actual
   * recording to zero or more {Tracer}s.
   *
   * @param {Annotation} annotation The annotation to associate
   */
  Trace.prototype.record = function (annotation) {
    var self = this;

    if (annotation.endpoint === undefined && this.endpoint !== undefined) {
      annotation.endpoint = this.endpoint;
    }

    forEach(this._tracers, function(tracer) {
      tracer.record([[self, [annotation]]]);
    });
  };

  /**
   * Set a default {Endpoint} for the current {Trace}. All {Annotation}s
   * recorded after this {Endpoint} is set will use it, unless they provide
   * their own {Endpoint}.
   *
   * @param {Endpoint} endpoint The default endpoint for all
   *    {Annotation}s associated with this Trace
   */
  Trace.prototype.setEndpoint = function (endpoint) {
    this.endpoint = endpoint;
  };

  /**
   * Returns a hash of HTTP headers for this trace (to be used for making http
   * requests) to a server that supports tracing
   *
   * These headers are based on the headers used by finagle's tracing
   * http Codec.
   *
   * https://github.com/twitter/finagle/blob/master/finagle-http/
   *
   * Currently not implemented are X-B3-Sampled and X-B3-Flags.
   * Tryfer's underlying Trace implementation has no notion of a Sampled
   * trace, and also does not support flags.
   *
   * @param {Object} headers Optional.  The headers to add tracing headers to.
   *    If not provided, will use a new empty hash.  Either way, will return
   *    said hash.
   */
  Trace.prototype.toHeaders = function (headers) {
    var self = this;
    if (headers === undefined) {
      headers = {};
    }
    headers['X-B3-TraceId'] = self.traceId;
    headers['X-B3-SpanId'] = self.spanId;
    if (self.parentSpanId !== undefined) {
      headers['X-B3-ParentSpanId'] = self.parentSpanId;
    }
    return headers;
  };

  /**
   * Creates a new {Trace} given a hash of HTTP headers (to be used when
   * dealing with an incoming http request on a server that supports tracing).
   *
   * These headers are based on the headers used by finagle's tracing
   * http Codec.
   *
   * Currently not implemented are X-B3-Sampled and X-B3-Flags.
   * Tryfer's underlying Trace implementation has no notion of a Sampled
   * trace, and also does not support flags.
   *
   * ASSUMPTION: header names are all lower cased
   *    The default behavior of the NodeJS http module is to lower-case all
   *    headers.  Express (and it seems most other node http servers) also do
   *    this, so we assume that all the headers are lower case
   *
   * @param {String} traceName What to name the trace - this can't come from
   *    headers - it's highly recommended that this be the request method, to
   *    match with tryfer's naming convention
   * @param {Object} headers A mapping of lower-cased header field names to
   *    values
   */
  Trace.fromHeaders = function(traceName, headers) {
    var traceOptions = {};

    ['X-B3-TraceId', 'X-B3-SpanId', 'X-B3-ParentSpanId'].forEach(function(v) {
      var processed = getHex64(headers[v.toLowerCase()]);
      if (processed !== undefined) {
        traceOptions[v.slice(5,6).toLowerCase() + v.slice(6)] = processed;
      }
    });

    return new Trace(traceName, traceOptions);
  };

  /**
   * Creates a new {Trace} given a {http.ServerRequest}-like object.
   * Not only does this build a {Trace} based on the headers but sets the
   * server endpoint.  The {http.ServerRequest}-like object should include at
   * least the following:
   *
   * - {request.method} - a {String} of the http method (e.g. GET, POST) -
   *    defaults to GET
   * - {request.headers} - an {Object} containing the http headers - defaults
   *    to an empty object
   * - {request.socket} - an {Object} containing information regarding the
   *    http socket - this is used to determine the server endpoint, which
   *    if socket is undefined will default to an IPv4 address of '127.0.0.1'
   *    and a port of 80
   *
   * For more information on how the {Trace} is constructed from the headers,
   * see {Trace.fromHeaders}
   *
   * @param {Object} request The request object
   * @param {String} serviceName The name of the service) - defaults to 'http'
   */
  Trace.fromRequest = function(request, serviceName) {
    var newTrace = Trace.fromHeaders(
      request.method || 'GET', request.headers || {});

    var host = (request.socket && request.socket.address ?
      request.socket.address() : {address: '127.0.0.1', port: 80});

    if (serviceName === undefined || serviceName === null) {
      serviceName = 'http';
    }

    newTrace.setEndpoint(new Endpoint(host.address, host.port, serviceName));
    return newTrace;
  };

  /**
   * An IEndpoint represents a source of annotations in a distributed system.
   *
   * An endpoint represents the place where an event represented by an
   * annotation occurs.
   *
   * In a simple client/server RPC system both the client and server will
   * record Annotations for the same trace & span but those annotations will
   * have separate endpoints.  On the client the endpoint will represent the
   * client service and on the server the endpoint will represent server
   * service.
   *
   * @param {String} ipv4 Dotted decimal string IP Address of this {Endpoint}
   * @param {number} port Integer port of this {Endpoint}
   * @param {String} serviceName Name of the service for this {Endpoint}
   */
  Endpoint = function(ipv4, port, serviceName) {
    this.ipv4 = ipv4;
    this.port = parseInt(port, 10);
    this.serviceName = serviceName;
  };

  /**
   * An annotation represents a piece of information attached to a trace.
   *
   * Most commonly this will be an event like:
   *    * Client send
   *    * Server receive
   *    * Server send
   *    * Client receive
   *
   * It may however also include non-event information such as the URI of
   * an HTTP request being made, or the user id that initiated the action
   * which caused the operations being traced to be performed.
   *
   * @param {String} name The name of this annotation
   * @param {number|String} value The value of this annotation
   * @param {String} annotationType A string describing the type of this
   *    annotation.  Should be one of:
   *      {zipkinCore_types.CLIENT_SEND},
   *      {zipkinCore_types.CLIENT_RECV},
   *      {zipkinCore_types.SERVER_SEND},
   *         zipkinCore_types.CLIENT_RECV,
   *         or String} annotationType
   * @param {Endpoint} endpoint
   *
   * NOTE: If the annotationType is NOT a timestamp, the value must be a string
   * (for now)
   */
  Annotation = function(name, value, annotationType, endpoint) {
    var self = this;
    self.name = name;
    self.value = value;
    self.annotationType = annotationType;
    if (endpoint !== undefined) {
      self.endpoint = endpoint;
    }
  };

  /**
   * Creates a timestamp annotation, which represents an event.
   *
   * @param {String} name The name of this timestamp
   * @param {number} timestamp The time of the event in microseconds since the
   *    epoch (UTC) - optional
   */
  Annotation.timestamp = function (name, timestamp) {
    if (timestamp === undefined) {
      timestamp = getNowMicros();
    }
    return new Annotation(name, timestamp, 'timestamp');
  };

  /**
   * Creates a client send (timestamp) annotation
   *
   * @param {number} timestamp The time of the client send event in
   *    microseconds since the epoch (UTC) - optional
   */
  Annotation.clientSend = function (timestamp) {
    return Annotation.timestamp(zipkinCore_types.CLIENT_SEND, timestamp);
  };

  /**
   * Creates a client receive (timestamp) annotation
   *
   * @param {number} timestamp The time of the client receive event in
   *    microseconds since the epoch (UTC) - optional
   */
  Annotation.clientRecv = function (timestamp) {
    return Annotation.timestamp(zipkinCore_types.CLIENT_RECV, timestamp);
  };

  /**
   * Creates a server send (timestamp) annotation
   *
   * @param {number} [timestamp] The time of the server send event in
   *    microseconds since the epoch (UTC) - optional
   */
  Annotation.serverSend = function (timestamp) {
    return Annotation.timestamp(zipkinCore_types.SERVER_SEND, timestamp);
  };

  /**
   * Creates a server receive (timestamp) annotation
   *
   * @param {number} [timestamp] The time of the server receive event in
   *    microseconds since the epoch (UTC) - optional
   */
  Annotation.serverRecv = function (timestamp) {
    return Annotation.timestamp(zipkinCore_types.SERVER_RECV, timestamp);
  };

  /**
   * Creates a unicode string (non-event) annotation
   *
   * @param {String} name The name of this string annotation
   * @param {String} value The string value of the annotation
   */
  Annotation.string = function (name, value) {
    return new Annotation(name, value, 'string');
  };

  /**
   * Creates a uri annotation for client requests.  This has the Annotation
   * name 'http.uri' because that is the standard set forth in the finagle
   * http Codec.
   *
   * @param {String} uri The URI to annotate
   */
  Annotation.uri = function(uri) {
    return Annotation.string('http.uri', uri);
  };

  if (typeof module !== 'undefined' && module.exports) {
    try {
      var microtime = require('microtime');
      getNowMicros = function() {
          return microtime.now();
      };
    } catch (err) {
      // Use default implementation if microtime unavailable
    }
    tracers = require('./tracers');
    formatters = require('./formatters');
    Int64 = require('node-int64');
    zipkinCore_types = require('./_thrift/zipkinCore/zipkinCore_types');
    exports.Trace = Trace;
    exports.Endpoint = Endpoint;
    exports.Annotation = Annotation;
    // Exported only for tests
    exports._overrideGetNowMicros = function(func) {
      getNowMicros = func;
    };
  } else {
    this.Trace = Trace;
    this.Endpoint = Endpoint;
    this.Annotation = Annotation;
  }

}());
<commit_msg>0x80000000 is the proper upperbound as Math.random has 16 digit precision<commit_after>// Copyright 2012 Rackspace Hosting, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

(function () {
  var tracers, formatters, zipkinCore_types;
  var Trace, Annotation, Endpoint, Int64;
  var forEach, has, getUniqueId, getNowMicros, getHex64;

  forEach = function(obj, f){
    Array.prototype.forEach.call(obj, f);
  };

  has = function(obj, val){
    return Object.hasOwnProperty.call(obj, val);
  };

	getUniqueId = function () {
		var random = new Int64(Math.random() * 0x80000000, Math.random() * 0x100000000);
		return random.toOctetString();
	};

	/**
	 * Get a hex representation of provided value
	 *
	 * @param {String|number} hex Ex: "0xffffeeeeffefefef", "ffffeeeeffefefef", 12342344543543
	 * NOTE: 0x12342344543543 is NOT a valid input
	 *
	 * @returns {Int64|undefined}
	 */
	getHex64 = function (hex) {
		try {
			return new Int64(hex).toOctetString();
		} catch (e) {
			return undefined;
		}
	};

	/**
	 * Return the current unix epoch timestamp in microseconds
	 * @return {number}
	 */
  getNowMicros = function() {
      return Date.now() * 1000;
  };

  /**
   * A Trace encapsulates information about the current span of this trace
   * and provides a mechanism for creating new child spans and recording
   * annotations for this span. It delegates to zero or more {Tracers} and
   * allows setting a default {Endpoint} to associate with {Annotation}s
   *
   * @param {String} name A string describing this span
   * @param {Hash} options A hash any or all or none of the following
   *    params, for which values will be generated if not provided:
   *
   * @param {Number} options.traceId 64-bit integer identifying this trace
   * @param {Number} options.spanId 64-bit integer identifying this span
   * @param {Number} options.parentSpanId 64-bit integer identifying this trace's
   *     parent span, or undefined.
   * @param {Array} options._tracers Zero or more {Tracers}
   */
  Trace = function(name, options) {
    var self = this;
    self.name = name;

    options = options || {};

    ['traceId', 'spanId', 'parentSpanId'].forEach(function(idName) {
      if (has(options, idName) && options[idName] !== null &&
        options[idName] !== undefined) {
        self[idName] = getHex64(options[idName]);
      } else if (idName !== 'parentSpanId') {
        self[idName] = getUniqueId();
      }
    });

    if (has(options, 'tracers') && options.tracers){
      self._tracers = options.tracers;
    } else {
      self._tracers = tracers.getTracers();
    }
  };

  /**
   * Create a new instance of this class derived from the current instance
   * such that:
   *    child.trace_id == current.trace_id, and
   *    child.parent_span_id == current.span_id
   * The child {Trace} will have a new unique {spanId} and if set, the
   * endpoint of the current {Trace} object.
   *
   * @param {String} name The name describing the new span represented by the
   *    new child {Trace} object.
   */
  Trace.prototype.child = function (name) {
    var optionalArgs = {
      traceId: this.traceId,
      parentSpanId: this.spanId,
      tracers: this._tracers
    };
    var trace = new Trace(name, optionalArgs);
    trace.setEndpoint(this.endpoint);
    return trace;
  };

  /**
   * Record an annotation for this {Trace}.  This is the primary entry point
   * for associating {Annotation}s with {Trace}s.  It will delegate actual
   * recording to zero or more {Tracer}s.
   *
   * @param {Annotation} annotation The annotation to associate
   */
  Trace.prototype.record = function (annotation) {
    var self = this;

    if (annotation.endpoint === undefined && this.endpoint !== undefined) {
      annotation.endpoint = this.endpoint;
    }

    forEach(this._tracers, function(tracer) {
      tracer.record([[self, [annotation]]]);
    });
  };

  /**
   * Set a default {Endpoint} for the current {Trace}. All {Annotation}s
   * recorded after this {Endpoint} is set will use it, unless they provide
   * their own {Endpoint}.
   *
   * @param {Endpoint} endpoint The default endpoint for all
   *    {Annotation}s associated with this Trace
   */
  Trace.prototype.setEndpoint = function (endpoint) {
    this.endpoint = endpoint;
  };

  /**
   * Returns a hash of HTTP headers for this trace (to be used for making http
   * requests) to a server that supports tracing
   *
   * These headers are based on the headers used by finagle's tracing
   * http Codec.
   *
   * https://github.com/twitter/finagle/blob/master/finagle-http/
   *
   * Currently not implemented are X-B3-Sampled and X-B3-Flags.
   * Tryfer's underlying Trace implementation has no notion of a Sampled
   * trace, and also does not support flags.
   *
   * @param {Object} headers Optional.  The headers to add tracing headers to.
   *    If not provided, will use a new empty hash.  Either way, will return
   *    said hash.
   */
  Trace.prototype.toHeaders = function (headers) {
    var self = this;
    if (headers === undefined) {
      headers = {};
    }
    headers['X-B3-TraceId'] = self.traceId;
    headers['X-B3-SpanId'] = self.spanId;
    if (self.parentSpanId !== undefined) {
      headers['X-B3-ParentSpanId'] = self.parentSpanId;
    }
    return headers;
  };

  /**
   * Creates a new {Trace} given a hash of HTTP headers (to be used when
   * dealing with an incoming http request on a server that supports tracing).
   *
   * These headers are based on the headers used by finagle's tracing
   * http Codec.
   *
   * Currently not implemented are X-B3-Sampled and X-B3-Flags.
   * Tryfer's underlying Trace implementation has no notion of a Sampled
   * trace, and also does not support flags.
   *
   * ASSUMPTION: header names are all lower cased
   *    The default behavior of the NodeJS http module is to lower-case all
   *    headers.  Express (and it seems most other node http servers) also do
   *    this, so we assume that all the headers are lower case
   *
   * @param {String} traceName What to name the trace - this can't come from
   *    headers - it's highly recommended that this be the request method, to
   *    match with tryfer's naming convention
   * @param {Object} headers A mapping of lower-cased header field names to
   *    values
   */
  Trace.fromHeaders = function(traceName, headers) {
    var traceOptions = {};

    ['X-B3-TraceId', 'X-B3-SpanId', 'X-B3-ParentSpanId'].forEach(function(v) {
      var processed = getHex64(headers[v.toLowerCase()]);
      if (processed !== undefined) {
        traceOptions[v.slice(5,6).toLowerCase() + v.slice(6)] = processed;
      }
    });

    return new Trace(traceName, traceOptions);
  };

  /**
   * Creates a new {Trace} given a {http.ServerRequest}-like object.
   * Not only does this build a {Trace} based on the headers but sets the
   * server endpoint.  The {http.ServerRequest}-like object should include at
   * least the following:
   *
   * - {request.method} - a {String} of the http method (e.g. GET, POST) -
   *    defaults to GET
   * - {request.headers} - an {Object} containing the http headers - defaults
   *    to an empty object
   * - {request.socket} - an {Object} containing information regarding the
   *    http socket - this is used to determine the server endpoint, which
   *    if socket is undefined will default to an IPv4 address of '127.0.0.1'
   *    and a port of 80
   *
   * For more information on how the {Trace} is constructed from the headers,
   * see {Trace.fromHeaders}
   *
   * @param {Object} request The request object
   * @param {String} serviceName The name of the service) - defaults to 'http'
   */
  Trace.fromRequest = function(request, serviceName) {
    var newTrace = Trace.fromHeaders(
      request.method || 'GET', request.headers || {});

    var host = (request.socket && request.socket.address ?
      request.socket.address() : {address: '127.0.0.1', port: 80});

    if (serviceName === undefined || serviceName === null) {
      serviceName = 'http';
    }

    newTrace.setEndpoint(new Endpoint(host.address, host.port, serviceName));
    return newTrace;
  };

  /**
   * An IEndpoint represents a source of annotations in a distributed system.
   *
   * An endpoint represents the place where an event represented by an
   * annotation occurs.
   *
   * In a simple client/server RPC system both the client and server will
   * record Annotations for the same trace & span but those annotations will
   * have separate endpoints.  On the client the endpoint will represent the
   * client service and on the server the endpoint will represent server
   * service.
   *
   * @param {String} ipv4 Dotted decimal string IP Address of this {Endpoint}
   * @param {number} port Integer port of this {Endpoint}
   * @param {String} serviceName Name of the service for this {Endpoint}
   */
  Endpoint = function(ipv4, port, serviceName) {
    this.ipv4 = ipv4;
    this.port = parseInt(port, 10);
    this.serviceName = serviceName;
  };

  /**
   * An annotation represents a piece of information attached to a trace.
   *
   * Most commonly this will be an event like:
   *    * Client send
   *    * Server receive
   *    * Server send
   *    * Client receive
   *
   * It may however also include non-event information such as the URI of
   * an HTTP request being made, or the user id that initiated the action
   * which caused the operations being traced to be performed.
   *
   * @param {String} name The name of this annotation
   * @param {number|String} value The value of this annotation
   * @param {String} annotationType A string describing the type of this
   *    annotation.  Should be one of:
   *      {zipkinCore_types.CLIENT_SEND},
   *      {zipkinCore_types.CLIENT_RECV},
   *      {zipkinCore_types.SERVER_SEND},
   *         zipkinCore_types.CLIENT_RECV,
   *         or String} annotationType
   * @param {Endpoint} endpoint
   *
   * NOTE: If the annotationType is NOT a timestamp, the value must be a string
   * (for now)
   */
  Annotation = function(name, value, annotationType, endpoint) {
    var self = this;
    self.name = name;
    self.value = value;
    self.annotationType = annotationType;
    if (endpoint !== undefined) {
      self.endpoint = endpoint;
    }
  };

  /**
   * Creates a timestamp annotation, which represents an event.
   *
   * @param {String} name The name of this timestamp
   * @param {number} timestamp The time of the event in microseconds since the
   *    epoch (UTC) - optional
   */
  Annotation.timestamp = function (name, timestamp) {
    if (timestamp === undefined) {
      timestamp = getNowMicros();
    }
    return new Annotation(name, timestamp, 'timestamp');
  };

  /**
   * Creates a client send (timestamp) annotation
   *
   * @param {number} timestamp The time of the client send event in
   *    microseconds since the epoch (UTC) - optional
   */
  Annotation.clientSend = function (timestamp) {
    return Annotation.timestamp(zipkinCore_types.CLIENT_SEND, timestamp);
  };

  /**
   * Creates a client receive (timestamp) annotation
   *
   * @param {number} timestamp The time of the client receive event in
   *    microseconds since the epoch (UTC) - optional
   */
  Annotation.clientRecv = function (timestamp) {
    return Annotation.timestamp(zipkinCore_types.CLIENT_RECV, timestamp);
  };

  /**
   * Creates a server send (timestamp) annotation
   *
   * @param {number} [timestamp] The time of the server send event in
   *    microseconds since the epoch (UTC) - optional
   */
  Annotation.serverSend = function (timestamp) {
    return Annotation.timestamp(zipkinCore_types.SERVER_SEND, timestamp);
  };

  /**
   * Creates a server receive (timestamp) annotation
   *
   * @param {number} [timestamp] The time of the server receive event in
   *    microseconds since the epoch (UTC) - optional
   */
  Annotation.serverRecv = function (timestamp) {
    return Annotation.timestamp(zipkinCore_types.SERVER_RECV, timestamp);
  };

  /**
   * Creates a unicode string (non-event) annotation
   *
   * @param {String} name The name of this string annotation
   * @param {String} value The string value of the annotation
   */
  Annotation.string = function (name, value) {
    return new Annotation(name, value, 'string');
  };

  /**
   * Creates a uri annotation for client requests.  This has the Annotation
   * name 'http.uri' because that is the standard set forth in the finagle
   * http Codec.
   *
   * @param {String} uri The URI to annotate
   */
  Annotation.uri = function(uri) {
    return Annotation.string('http.uri', uri);
  };

  if (typeof module !== 'undefined' && module.exports) {
    try {
      var microtime = require('microtime');
      getNowMicros = function() {
          return microtime.now();
      };
    } catch (err) {
      // Use default implementation if microtime unavailable
    }
    tracers = require('./tracers');
    formatters = require('./formatters');
    Int64 = require('node-int64');
    zipkinCore_types = require('./_thrift/zipkinCore/zipkinCore_types');
    exports.Trace = Trace;
    exports.Endpoint = Endpoint;
    exports.Annotation = Annotation;
    // Exported only for tests
    exports._overrideGetNowMicros = function(func) {
      getNowMicros = func;
    };
  } else {
    this.Trace = Trace;
    this.Endpoint = Endpoint;
    this.Annotation = Annotation;
  }

}());
<|endoftext|>


<commit_before>'use babel'

/* @flow */

export type Atom$Point = [number, number]
export type Atom$Range = [Atom$Point, Atom$Point]
export type Linter$Linter = {
  name?: string
}
export type Linter$Message = {
  type: string,
  text?: string,
  html?: string,
  name?: string,
  filePath?: string,
  range?: Atom$Range,
  trace?: Array<Linter$Message>
}
export type Linter$Difference = {
  added: Array<Linter$Message>,
  removed: Array<Linter$Message>,
  messages: Array<Linter$Message>
}
<commit_msg>:new: Add types for buffer difference<commit_after>'use babel'

/* @flow */

import type {TextBuffer, TextEditorMarker} from 'atom'

export type Atom$Point = [number, number]
export type Atom$Range = [Atom$Point, Atom$Point]
export type Linter$Linter = {
  name?: string
}
export type Linter$Message = {
  type: string,
  text?: string,
  html?: string,
  name?: string,
  filePath?: string,
  range?: Atom$Range,
  trace?: Array<Linter$Message>
}
export type Linter$Difference = {
  added: Array<Linter$Message>,
  removed: Array<Linter$Message>,
  messages: Array<Linter$Message>
}
export type Buffer$Difference = {
  textBuffer: TextBuffer,
  markers: Map<Linter$Message, TextEditorMarker>,
  added: Array<Linter$Message>,
  removed: Array<Linter$Message>
}
<|endoftext|>


<commit_before>/* jslint node: true, esnext: true */
"use strict";

const log4js = require('log4js');
const logger = log4js.getLogger('kronos-step-archive-tar:untar');

const tar = require('tar-stream');

exports = {
	"description": "decomposes tar archive into individual output requests",
	"endpoints": {
		"in": {
			"direction": "in(passive)",
			"uti": "public.tar-archive",
			"contentInfo": {
				"name": {
					"description": "The file name of the original tar file",
					"mandatory": false
				}
			}
		},
		"out": {
			"direction": "out(active)",
			"contentInfo": {
				"archiveName": {
					"description": "The file name of the original tar file"
				},
				"name": {
					"description": "The file name of the extratcted entry"
				},
				"mtime": {
					"description": "modification time of the entry"
				}
			}
		}
	},
	initialize(manager, step) {
		logger.debug(`Initialize`);

		let archiveName;

		// --------------------------------------
		// Initialize the OUT endpoint
		// --------------------------------------
		const out = step.endpoints.out.initialize(manager);
		logger.debug(`Initialized the OUT endpoint`);

		// --------------------------------------
		// get the untar function
		// --------------------------------------
		const extract = tar.extract();

		// This will be called from the untar function for each element in the TAR archive
		extract.on('entry', function (header, stream, callback) {
			step.debug(`Extract new entry '${header.name}'`);
			logger.debug(`Extract new entry '${header.name}'`);

			stream.on('end', function () {
				callback(); // ready for next entry
			});

			header.archiveName = archiveName;

			try {
				out.next({
					info: header,
					stream: stream
				});
			} catch (e) {
				logger.error(`Error for archive: '${archiveName}': ${e}`);
				step.error(e);
				stream.resume();
			}
		});

		// --------------------------------------
		// initialize the IN endpoint
		// --------------------------------------
		step.endpoints.in.initialize(manager, function* () {
			logger.debug(`IN': called`);

			const request = yield;
			logger.debug(`Got a new request to untar ${request.info.name}`);

			// set the archive name
			archiveName = request.info.name;
			step.debug(`New archive ${archiveName}`);

			request.stream.pipe(extract);

			logger.debug(`Done archive ${archiveName}`);
		});
		logger.debug(`Initialized the IN endpoint`);
	}
};
<commit_msg>fix: use module.exports if only exporting one entry<commit_after>/* jslint node: true, esnext: true */
"use strict";

const log4js = require('log4js');
const logger = log4js.getLogger('kronos-step-archive-tar:untar');

const tar = require('tar-stream');

module.exports = {
	"description": "decomposes tar archive into individual output requests",
	"endpoints": {
		"in": {
			"direction": "in(passive)",
			"uti": "public.tar-archive",
			"contentInfo": {
				"name": {
					"description": "The file name of the original tar file",
					"mandatory": false
				}
			}
		},
		"out": {
			"direction": "out(active)",
			"contentInfo": {
				"archiveName": {
					"description": "The file name of the original tar file"
				},
				"name": {
					"description": "The file name of the extratcted entry"
				},
				"mtime": {
					"description": "modification time of the entry"
				}
			}
		}
	},
	initialize(manager, step) {
		logger.debug(`Initialize`);

		let archiveName;

		// --------------------------------------
		// Initialize the OUT endpoint
		// --------------------------------------
		const out = step.endpoints.out.initialize(manager);
		logger.debug(`Initialized the OUT endpoint`);

		// --------------------------------------
		// get the untar function
		// --------------------------------------
		const extract = tar.extract();

		// This will be called from the untar function for each element in the TAR archive
		extract.on('entry', function (header, stream, callback) {
			step.debug(`Extract new entry '${header.name}'`);
			logger.debug(`Extract new entry '${header.name}'`);

			stream.on('end', function () {
				callback(); // ready for next entry
			});

			header.archiveName = archiveName;

			try {
				out.next({
					info: header,
					stream: stream
				});
			} catch (e) {
				logger.error(`Error for archive: '${archiveName}': ${e}`);
				step.error(e);
				stream.resume();
			}
		});

		// --------------------------------------
		// initialize the IN endpoint
		// --------------------------------------
		step.endpoints.in.initialize(manager, function* () {
			logger.debug(`IN': called`);

			const request = yield;
			logger.debug(`Got a new request to untar ${request.info.name}`);

			// set the archive name
			archiveName = request.info.name;
			step.debug(`New archive ${archiveName}`);

			request.stream.pipe(extract);

			logger.debug(`Done archive ${archiveName}`);
		});
		logger.debug(`Initialized the IN endpoint`);
	}
};
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var request = require('./util/request');
var debug = require('debug')('wpcom:users');

/**
 * Create a `Users` instance
 *
 * @param {WPCOM} wpcom
 * @api public
 */

function Users(wpcom) {
  if (!(this instanceof Users)) {
    return new Users(wpcom);
  }

  this.wpcom = wpcom;
}

/**
 * A list of @mention suggestions for the current user
 *
 * @param {Object} [query]
 * @param {Function} fn
 * @api public
 */

Users.prototype.suggest = function (query, fn) {
  return request.get(this.wpcom, null, '/users/suggest', query, fn);
};

/**
 * Expose `Users` module
 */

module.exports = Users;<commit_msg>users: update to wpcom.req method<commit_after>
/**
 * Module dependencies.
 */

var debug = require('debug')('wpcom:users');

/**
 * Create a `Users` instance
 *
 * @param {WPCOM} wpcom
 * @api public
 */

function Users(wpcom) {
  if (!(this instanceof Users)) {
    return new Users(wpcom);
  }

  this.wpcom = wpcom;
}

/**
 * A list of @mention suggestions for the current user
 *
 * @param {Object} [query]
 * @param {Function} fn
 * @api public
 */

Users.prototype.suggest = function (query, fn) {
  return this.wpcom.req.get('/users/suggest', query, fn);
};

/**
 * Expose `Users` module
 */

module.exports = Users;<|endoftext|>


<commit_before>'use strict';

var http = require('http');
var https = require('https');
var path = require('path');
var when = require('when');
var _ = require('lodash');

var utils = require('./utils');
var Error = require('./Error');

var hasOwn = {}.hasOwnProperty;

// Provide extension mechanism for Pingpp Resource Sub-Classes
PingppResource.extend = utils.protoExtend;

// Expose method-creator & prepared (basic) methods
PingppResource.method = require('./PingppMethod');
PingppResource.BASIC_METHODS = require('./PingppMethod.basic');

/**
 * Encapsulates request logic for a Pingpp Resource
 */
function PingppResource(pingpp, urlData) {
  this._pingpp = pingpp;
  this._urlData = urlData || {};

  this.basePath = utils.makeURLInterpolator(pingpp.getApiField('basePath'));
  this.path = utils.makeURLInterpolator(this.path);

  if (this.includeBasic) {
    this.includeBasic.forEach(function(methodName) {
      this[methodName] = PingppResource.BASIC_METHODS[methodName];
    }, this);
  }

  this.initialize.apply(this, arguments);
}

PingppResource.prototype = {
  path: '',

  initialize: function() {},

  createFullPath: function(commandPath, urlData) {
    return path.join(
      this.basePath(urlData),
      this.path(urlData),
      typeof commandPath == 'function' ?
        commandPath(urlData) : commandPath
    ).replace(/\\/g, '/'); // ugly workaround for Windows
  },

  createUrlData: function() {
    var urlData = {};
    for (var i in this._urlData) {
      if (hasOwn.call(this._urlData, i)) {
        urlData[i] = this._urlData[i];
      }
    }

    return urlData;
  },

  createDeferred: function(callback) {
    var deferred = when.defer();

    if (callback) {
      // Callback, if provided, is a simply translated to Promise'esque:
      // (Ensure callback is called outside of promise stack)
      deferred.promise.then(function(res) {
        setTimeout(function(){ callback(null, res); }, 0);
      }, function(err) {
        setTimeout(function(){ callback(err, null); }, 0);
      });
    }

    return deferred;
  },

  _timeoutHandler: function(timeout, req, callback) {
    var self = this;
    return function() {
      var timeoutErr = new Error('ETIMEOUT');
      timeoutErr.code = 'ETIMEOUT';

      req._isAborted = true;
      req.abort();

      callback.call(
        self,
        new Error.PingppConnectionError({
          message: 'Request aborted due to timeout being reached (' + timeout + 'ms)',
          detail: timeoutErr
        }),
        null
      );
    };
  },

  _responseHandler: function(req, callback) {
    var self = this;
    return function(res) {
      var response = '';

      res.setEncoding('utf8');
      res.on('data', function(chunk) {
        response += chunk;
      });
      res.on('end', function() {
        try {
          response = JSON.parse(response);
          if (response.error) {
            var err;
            if (res.statusCode === 401) {
              err = new Error.PingppAuthenticationError(response.error);
            } else {
              err = Error.PingppError.generate(response.error);
            }
            return callback.call(self, err, null);
          }
        } catch (e) {
          return callback.call(
            self,
            new Error.PingppAPIError({
              message: 'Invalid JSON received from the Pingpp API',
              response: response,
              exception: e
            }),
            null
          );
        }
        callback.call(self, null, response);
      });
    };
  },

  _errorHandler: function(req, callback) {
    var self = this;
    return function(error) {
      if (req._isAborted) return; // already handled
      callback.call(
        self,
        new Error.PingppConnectionError({
          message: 'An error occurred with our connection to Pingpp',
          detail: error.message
        }),
        null
      );
    };
  },

  _request: function(method, path, data, auth, callback) {
    var requestData = '';
    var contentType = 'application/json';
    switch (method) {
    case 'POST':
    case 'PUT':
      requestData = JSON.stringify(data || {});
      break;
    case 'GET':
    case 'DELETE':
      contentType = 'application/x-www-form-urlencoded';
      path = data ? (path + '?' + utils.stringifyRequestData(data)) : path;
      break;
    default:
    }
    var self = this;

    var apiVersion = this._pingpp.getApiField('version');
    var headers = {
      'Authorization': auth ?
        'Basic ' + new Buffer(auth + ':').toString('base64') :
        this._pingpp.getApiField('auth'),
      'Accept': 'application/json',
      'Content-Type': contentType + '; charset=UTF-8',
      'User-Agent': 'Pingpp/v1 NodeBindings/' + this._pingpp.getConstant('PACKAGE_VERSION')
    };

    var requestTime = Date.parse(new Date()) / 1000;
    if (this._pingpp.getPrivateKey()) {
      headers['Pingplusplus-Signature'] = utils.generateSign(
        requestData + path + requestTime,
        this._pingpp.getPrivateKey()
      );
    }
    headers['Pingplusplus-Request-Timestamp']= requestTime;

    if (apiVersion) {
      headers['Pingplusplus-Version'] = apiVersion;
    }

    headers = _.assign(headers, this._pingpp.getParsedHeaders());

    this._pingpp.getClientUserAgent(function(cua) {
      headers['X-Pingpp-Client-User-Agent'] = cua;
      makeRequest();
    });

    function makeRequest() {
      var timeout = self._pingpp.getApiField('timeout');
      var isInsecureConnection = self._pingpp.getApiField('protocol') == 'http';

      var req = (
        isInsecureConnection ? http : https
      ).request({
        host: self._pingpp.getApiField('host'),
        port: self._pingpp.getApiField('port'),
        path: path,
        method: method,
        headers: headers,
        ciphers: 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5',
        secureProtocol: 'TLSv1_method'
      });

      req.setTimeout(timeout, self._timeoutHandler(timeout, req, callback));
      req.on('response', self._responseHandler(req, callback));
      req.on('error', self._errorHandler(req, callback));

      req.on('socket', function(socket) {
        socket.on(isInsecureConnection ? 'connect' : 'secureConnect', function() {
          req.write(requestData);
          req.end();
        });
      });
    }
  }
};

module.exports = PingppResource;
<commit_msg>add retry mechanism<commit_after>'use strict';

var http = require('http');
var https = require('https');
var path = require('path');
var when = require('when');
var _ = require('lodash');

var utils = require('./utils');
var Error = require('./Error');

var hasOwn = {}.hasOwnProperty;

// Provide extension mechanism for Pingpp Resource Sub-Classes
PingppResource.extend = utils.protoExtend;

// Expose method-creator & prepared (basic) methods
PingppResource.method = require('./PingppMethod');
PingppResource.BASIC_METHODS = require('./PingppMethod.basic');

/**
 * Encapsulates request logic for a Pingpp Resource
 */
function PingppResource(pingpp, urlData) {
  this._pingpp = pingpp;
  this._urlData = urlData || {};

  this.basePath = utils.makeURLInterpolator(pingpp.getApiField('basePath'));
  this.path = utils.makeURLInterpolator(this.path);

  if (this.includeBasic) {
    this.includeBasic.forEach(function(methodName) {
      this[methodName] = PingppResource.BASIC_METHODS[methodName];
    }, this);
  }

  this.initialize.apply(this, arguments);
}

PingppResource.prototype = {
  path: '',

  initialize: function() {},

  createFullPath: function(commandPath, urlData) {
    return path.join(
      this.basePath(urlData),
      this.path(urlData),
      typeof commandPath == 'function' ?
        commandPath(urlData) : commandPath
    ).replace(/\\/g, '/'); // ugly workaround for Windows
  },

  createUrlData: function() {
    var urlData = {};
    for (var i in this._urlData) {
      if (hasOwn.call(this._urlData, i)) {
        urlData[i] = this._urlData[i];
      }
    }

    return urlData;
  },

  createDeferred: function(callback) {
    var deferred = when.defer();

    if (callback) {
      // Callback, if provided, is a simply translated to Promise'esque:
      // (Ensure callback is called outside of promise stack)
      deferred.promise.then(function(res) {
        setTimeout(function(){ callback(null, res); }, 0);
      }, function(err) {
        setTimeout(function(){ callback(err, null); }, 0);
      });
    }

    return deferred;
  },

  _timeoutHandler: function(timeout, req, callback) {
    var self = this;
    return function() {
      var timeoutErr = new Error('ETIMEOUT');
      timeoutErr.code = 'ETIMEOUT';

      req._isAborted = true;
      req.abort();

      callback.call(
        self,
        new Error.PingppConnectionError({
          message: 'Request aborted due to timeout being reached (' + timeout + 'ms)',
          detail: timeoutErr
        }),
        null
      );
    };
  },

  _responseHandler: function(req, callback, retryCallback) {
    var self = this;
    return function(res) {
      var response = '';

      res.setEncoding('utf8');
      res.on('data', function(chunk) {
        response += chunk;
      });
      res.on('end', function() {
        try {
          response = JSON.parse(response);
          if (response.error) {
            var err;
            if (res.statusCode === 401) {
              err = new Error.PingppAuthenticationError(response.error);
            } else if(res.statusCode === 502 && retryCallback) {
              return retryCallback.call(self, new Error.PingppConnectionError(response.error), null);
            } else {
              err = Error.PingppError.generate(response.error);
            }
            return callback.call(self, err, null);
          }
        } catch (e) {
          return callback.call(
            self,
            new Error.PingppAPIError({
              message: 'Invalid JSON received from the Pingpp API',
              response: response,
              exception: e
            }),
            null
          );
        }
        callback.call(self, null, response);
      });
    };
  },

  _errorHandler: function(req, callback) {
    var self = this;
    return function(error) {
      if (req._isAborted) return; // already handled
      callback.call(
        self,
        new Error.PingppConnectionError({
          message: 'An error occurred with our connection to Pingpp',
          detail: error.message
        }),
        null
      );
    };
  },

  _request: function(method, path, data, auth, callback) {
    var requestData = '';
    var contentType = 'application/json';
    switch (method) {
    case 'POST':
    case 'PUT':
      requestData = JSON.stringify(data || {});
      break;
    case 'GET':
    case 'DELETE':
      contentType = 'application/x-www-form-urlencoded';
      path = data ? (path + '?' + utils.stringifyRequestData(data)) : path;
      break;
    default:
    }
    var self = this;

    var apiVersion = this._pingpp.getApiField('version');
    var headers = {
      'Authorization': auth ?
        'Basic ' + new Buffer(auth + ':').toString('base64') :
        this._pingpp.getApiField('auth'),
      'Accept': 'application/json',
      'Content-Type': contentType + '; charset=UTF-8',
      'User-Agent': 'Pingpp/v1 NodeBindings/' + this._pingpp.getConstant('PACKAGE_VERSION')
    };

    var requestTime = Date.parse(new Date()) / 1000;
    if (this._pingpp.getPrivateKey()) {
      headers['Pingplusplus-Signature'] = utils.generateSign(
        requestData + path + requestTime,
        this._pingpp.getPrivateKey()
      );
    }
    headers['Pingplusplus-Request-Timestamp']= requestTime;

    if (apiVersion) {
      headers['Pingplusplus-Version'] = apiVersion;
    }

    headers = _.assign(headers, this._pingpp.getParsedHeaders());

    this._pingpp.getClientUserAgent(function(cua) {
      headers['X-Pingpp-Client-User-Agent'] = cua;
      makeRequest();
    });

    var retryCount = 0;
    var retryMax = 1;
    function makeRequest() {
      var timeout = self._pingpp.getApiField('timeout');
      var isInsecureConnection = self._pingpp.getApiField('protocol') == 'http';

      var req = (
        isInsecureConnection ? http : https
      ).request({
        host: self._pingpp.getApiField('host'),
        port: self._pingpp.getApiField('port'),
        path: path,
        method: method,
        headers: headers,
        ciphers: 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5',
        secureProtocol: 'TLSv1_method'
      });

      req.setTimeout(timeout, self._timeoutHandler(timeout, req, callback));
      req.on('response', self._responseHandler(req, callback, function(err) {
        if(retryCount < retryMax) {
          retryCount++;
          makeRequest();
        } else {
          return callback.call(self, err, null);
        }
      }));
      req.on('error', self._errorHandler(req, callback));

      req.on('socket', function(socket) {
        socket.on(isInsecureConnection ? 'connect' : 'secureConnect', function() {
          req.write(requestData);
          req.end();
        });
      });
    }
  }
};

module.exports = PingppResource;
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var crypto = require('crypto');
var gutil = require('gulp-util');
var AWS = require('aws-sdk');
var Q = require('q');
var gutil = require('gulp-util');

module.exports = function (options) {

    AWS.config.region = options.region;
    var s3 = new AWS.S3({
	params: {
		Bucket: options.params.bucket
	},
        accessKeyId: options.accesKeyId,
        secretAccessKey: options.secretAccesKeyId
    });

    var updateWebsiteIndex = function (indexFile) {

        var deferred = Q.defer();

	// this killed everything.. missing credentials.
        //var s3 = new AWS.S3({params: {Bucket: options.bucket}});

        s3.getBucketWebsite({}, function (err, data) {
            if (err) {
                deferred.reject(err);
            } else {
                data.IndexDocument.Suffix = indexFile.substr(1);

                //Remove empty properties
                Object.keys(data).forEach(function (k) {
                    if (!data[k] || (Array.isArray(data[k]) && !data[k].length)) {
                        delete data[k];
                    }
                });

                s3.putBucketWebsite({
                    WebsiteConfiguration: data
                }, function (err) {
                    if (err) {
                        deferred.reject(err);
                    } else {
                        gutil.log('gulp-s3-index:', 'WebsiteIndex updated to [' + indexFile.substr(1) + '].');
                        deferred.resolve();
                    }
                });
            }
        });

        return deferred.promise;

    };

    return {
        updateWebsiteIndex: updateWebsiteIndex
    };

};
<commit_msg>deleted comment<commit_after>var fs = require('fs');
var path = require('path');
var crypto = require('crypto');
var gutil = require('gulp-util');
var AWS = require('aws-sdk');
var Q = require('q');
var gutil = require('gulp-util');

module.exports = function (options) {

    AWS.config.region = options.region;
    var s3 = new AWS.S3({
	params: {
		Bucket: options.params.bucket
	},
        accessKeyId: options.accesKeyId,
        secretAccessKey: options.secretAccesKeyId
    });

    var updateWebsiteIndex = function (indexFile) {

        var deferred = Q.defer();

        s3.getBucketWebsite({}, function (err, data) {
            if (err) {
                deferred.reject(err);
            } else {
                data.IndexDocument.Suffix = indexFile.substr(1);

                //Remove empty properties
                Object.keys(data).forEach(function (k) {
                    if (!data[k] || (Array.isArray(data[k]) && !data[k].length)) {
                        delete data[k];
                    }
                });

                s3.putBucketWebsite({
                    WebsiteConfiguration: data
                }, function (err) {
                    if (err) {
                        deferred.reject(err);
                    } else {
                        gutil.log('gulp-s3-index:', 'WebsiteIndex updated to [' + indexFile.substr(1) + '].');
                        deferred.resolve();
                    }
                });
            }
        });

        return deferred.promise;

    };

    return {
        updateWebsiteIndex: updateWebsiteIndex
    };

};
<|endoftext|>


<commit_before>'use strict';

var Atom, Client, ChatMessage;

const _chain_parent = Symbol('_chain_parent');
const _chain_spliced = Symbol('_chain_spliced');

module.exports = {
	// Sort of like Object.assign(), but it assigns *behind* the other object, and it's also recursive.
	weak_deep_assign(a, b) {
		for(var key in b) {
			if(!b.hasOwnProperty(key))
				continue;
			if(typeof b[key] == "object" && b[key] != null && !(b[key] instanceof Array) && (!a.hasOwnProperty(key) || typeof a[key] != "object" || a[key] == null || (a[key] instanceof Array)))
				a[key] = {};
			if(a.hasOwnProperty(key)) {
				if((typeof a[key] == "object" && a[key] != null && !(a[key] instanceof Array)) && (typeof b[key] == "object" && b[key] != null && !(b[key] instanceof Array)))
					module.exports.weak_deep_assign(a[key], b[key]);
			} else {
				a[key] = b[key];
			}
		}
		return a;
	},

	// Recursive version of Object.create()
	deep_create(obj) {
		var newobj = Object.create(obj);
		for(var key in obj) {
			if(!obj.hasOwnProperty(key))
				continue;
			if(typeof obj[key] == "object" && !(obj[key] instanceof Array))
				newobj[key] = module.exports.deepCreate(obj[key]);
		}
		return newobj;
	},

	// Chaining:
	// Basically, you do it like this:
	// *original func* = chain_func(*original func*, *replacement func*);
	// This outputs a function which when called, calls the replacement function
	// but with an argument inserted at the beginning that is a reference to a function
	// referencing the original function.
	chain_func(func1, func2) {
		if(func2 == undefined)
			throw new Error('Chaining undefined function!');
		function chained_func(...args) {
			while(chained_func[_chain_parent] && chained_func[_chain_parent][_chain_spliced]) {
				chained_func[_chain_parent] = chained_func[_chain_parent][_chain_parent];
			}
			let prev = (...override_args)=>{
				if(!chained_func[_chain_parent])
					return;
				if(override_args.length)
					return chained_func[_chain_parent].call(this, ...override_args);
				else
					return chained_func[_chain_parent].call(this, ...args);
			};
			if(chained_func[_chain_spliced])
				return prev();
			return func2.call(this, prev, ...args);
		}
		chained_func.splice = function() {
			chained_func[_chain_spliced] = true;
		};
		chained_func[_chain_spliced] = false;
		chained_func[_chain_parent] = func1;
		return chained_func;
	},

	has_component(atom, name) {
		return atom && (atom instanceof Atom) && !!atom.components[name];
	},

	is_atom(atom) {
		return atom && (atom instanceof Atom);
	},

	turn_dir(dir, angle) {
		dir = dir & 15;
		angle = ((angle % 360 + 360) % 360);
		return [ // woo lookup table time
			[0, 1, 2 ,3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15],
			[0, 5,10,15, 6, 4, 2,15, 9, 1, 8,15,15,15,15,15],
			[0, 4, 8,12, 2, 6,10,14, 1, 5, 9,13, 3, 7,11,15],
			[0, 6, 9,15,10, 2, 8,15, 5, 4, 1,15,15,15,15,15],
			[0, 2, 1, 3, 8,10, 9,11, 4, 6, 5, 7,12,14,13,15],
			[0,10, 5,15, 9, 8, 1,15, 6, 2, 4,15,15,15,15,15],
			[0, 8, 4,12, 1, 9, 5,13, 2,10, 6,14, 3,11, 7,15],
			[0, 9, 6,15, 5, 1, 4,15,10, 8, 2,15,15,15,15,15]
		][Math.floor(angle / 90) * 2 + ((angle % 90) == 0 ? 0 : 1)][dir];
	},

	dir_dx(dir) {
		var dx = 0;
		if(dir & 4)
			dx++;
		if(dir & 8)
			dx--;
		return dx;
	},

	dir_dy(dir) {
		var dy = 0;
		if(dir & 1)
			dy++;
		if(dir & 2)
			dy--;
		return dy;
	},

	// setImmediate in promise form basically.
	stoplag() {
		return new Promise((resolve) => {
			setImmediate(resolve);
		});
	},

	sleep(time = 0) {
		return new Promise((resolve) => {
			setTimeout(resolve, time);
		});
	},

	visible_message(a, ...b) {
		if(typeof a == "string") {
			return new ChatMessage("see", a);
		}
		return module.exports.visible_message(module.exports.format_html(a, ...b));
	},

	audible_message(a, ...b) {
		if(typeof a == "string") {
			return new ChatMessage("hear", a);
		}
		return module.exports.audible_message(module.exports.format_html(a, ...b));
	},

	to_chat(a, ...b) {
		if(a instanceof Atom || a instanceof Client) {
			var cl;
			if(a instanceof Client)
				cl = a;
			else
				cl = a.c.Mob.client;
			if(!cl)
				return;
			if(!cl.next_message.to_chat)
				cl.next_message.to_chat = [];
			cl.next_message.to_chat.push(b.join(""));
		} else if(a instanceof Array && a.length && (a[0] instanceof Atom || a[0] instanceof Client || a[0] instanceof Array)) {
			for(var item of a) {
				module.exports.to_chat(item, ...b);
			}
		} else {
			var formatted = module.exports.format_html(a, ...b);
			return (...items) => {
				module.exports.to_chat(items, formatted);
			};
		}
	},

	format_html(strs, ...tags) {
		var out_str = '';
		for(let i = 0; i < strs.length; i++) {
			var pre_tag = strs[i];
			if(i == strs.length - 1) {
				out_str += pre_tag;
				continue;
			}
			var str_tag = ""+tags[i];
			var is_proper = str_tag.length && str_tag[0] == str_tag[0].toUpperCase();
			var gender = "neutral";
			if(tags[i] instanceof Atom) {
				if(tags[i].force_improper)
					is_proper = false;
				if(tags[i].force_proper)
					is_proper = true;
				gender = tags[i].gender;
			}
			if(is_proper)
				pre_tag = pre_tag.replace(/(^|[ \t.,>])(?:the|a) (?=(?:[ \t]|(?:<[^>]+>))*$)/i, "$1");
			else if(gender == "plural")
				pre_tag = pre_tag.replace(/((?:^|[ \t.,>]))a(?= (?:[ \t]|(?:<[^>]+>))*$)/i, "$1some");
			else if(str_tag.match(/^[aeiou]/i))
				pre_tag = pre_tag.replace(/((?:^|[ \t.,>])a)(?= (?:[ \t]|(?:<[^>]+>))*$)/i, "$1n");
			tags[i] = ""+tags[i];
			out_str += pre_tag;
			out_str += module.exports.escape_html(tags[i]);
		}
		return out_str;
	},

	escape_html(str) {
		return str.replace(/[&<>"']/gi, (chr) => {
			if(chr == '&') return '&';
			if(chr == '<') return '<';
			if(chr == '>') return '>';
			if(chr == '"') return '"';
			if(chr == "'") return ''';
		});
	},

	do_require() {
		Atom = require('./atom/atom.js');
		Client = require('./client.js');
		ChatMessage = require('./chat_message.js');
	},

	readonly_traps: {set: ()=>{},deleteProperty: ()=>{},defineProperty: ()=>{},setPrototypeOf: ()=>{},isExtensible:()=>{return false;}}
};
<commit_msg>a helper function<commit_after>'use strict';

var Atom, Client, ChatMessage;

const _chain_parent = Symbol('_chain_parent');
const _chain_spliced = Symbol('_chain_spliced');

module.exports = {
	// Sort of like Object.assign(), but it assigns *behind* the other object, and it's also recursive.
	weak_deep_assign(a, b) {
		for(var key in b) {
			if(!b.hasOwnProperty(key))
				continue;
			if(typeof b[key] == "object" && b[key] != null && !(b[key] instanceof Array) && (!a.hasOwnProperty(key) || typeof a[key] != "object" || a[key] == null || (a[key] instanceof Array)))
				a[key] = {};
			if(a.hasOwnProperty(key)) {
				if((typeof a[key] == "object" && a[key] != null && !(a[key] instanceof Array)) && (typeof b[key] == "object" && b[key] != null && !(b[key] instanceof Array)))
					module.exports.weak_deep_assign(a[key], b[key]);
			} else {
				a[key] = b[key];
			}
		}
		return a;
	},

	// Recursive version of Object.create()
	deep_create(obj) {
		var newobj = Object.create(obj);
		for(var key in obj) {
			if(!obj.hasOwnProperty(key))
				continue;
			if(typeof obj[key] == "object" && !(obj[key] instanceof Array))
				newobj[key] = module.exports.deepCreate(obj[key]);
		}
		return newobj;
	},

	// Chaining:
	// Basically, you do it like this:
	// *original func* = chain_func(*original func*, *replacement func*);
	// This outputs a function which when called, calls the replacement function
	// but with an argument inserted at the beginning that is a reference to a function
	// referencing the original function.
	chain_func(func1, func2) {
		if(func2 == undefined)
			throw new Error('Chaining undefined function!');
		function chained_func(...args) {
			while(chained_func[_chain_parent] && chained_func[_chain_parent][_chain_spliced]) {
				chained_func[_chain_parent] = chained_func[_chain_parent][_chain_parent];
			}
			let prev = (...override_args)=>{
				if(!chained_func[_chain_parent])
					return;
				if(override_args.length)
					return chained_func[_chain_parent].call(this, ...override_args);
				else
					return chained_func[_chain_parent].call(this, ...args);
			};
			if(chained_func[_chain_spliced])
				return prev();
			return func2.call(this, prev, ...args);
		}
		chained_func.splice = function() {
			chained_func[_chain_spliced] = true;
		};
		chained_func[_chain_spliced] = false;
		chained_func[_chain_parent] = func1;
		return chained_func;
	},

	has_component(atom, name) {
		return atom && (atom instanceof Atom) && !!atom.components[name];
	},

	is_atom(atom) {
		return atom && (atom instanceof Atom);
	},

	turn_dir(dir, angle) {
		dir = dir & 15;
		angle = ((angle % 360 + 360) % 360);
		return [ // woo lookup table time
			[0, 1, 2 ,3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15],
			[0, 5,10,15, 6, 4, 2,15, 9, 1, 8,15,15,15,15,15],
			[0, 4, 8,12, 2, 6,10,14, 1, 5, 9,13, 3, 7,11,15],
			[0, 6, 9,15,10, 2, 8,15, 5, 4, 1,15,15,15,15,15],
			[0, 2, 1, 3, 8,10, 9,11, 4, 6, 5, 7,12,14,13,15],
			[0,10, 5,15, 9, 8, 1,15, 6, 2, 4,15,15,15,15,15],
			[0, 8, 4,12, 1, 9, 5,13, 2,10, 6,14, 3,11, 7,15],
			[0, 9, 6,15, 5, 1, 4,15,10, 8, 2,15,15,15,15,15]
		][Math.floor(angle / 90) * 2 + ((angle % 90) == 0 ? 0 : 1)][dir];
	},

	dir_dx(dir) {
		var dx = 0;
		if(dir & 4)
			dx++;
		if(dir & 8)
			dx--;
		return dx;
	},

	dir_dy(dir) {
		var dy = 0;
		if(dir & 1)
			dy++;
		if(dir & 2)
			dy--;
		return dy;
	},

	dir_to(dx, dy) {
		let dir = 0;
		if(dy > 0) dir |= 1;
		if(dy < 0) dir |= 2;
		if(dx > 0) dir |= 4;
		if(dx < 0) dir |= 8;
		return dir;
	},

	// setImmediate in promise form basically.
	stoplag() {
		return new Promise((resolve) => {
			setImmediate(resolve);
		});
	},

	sleep(time = 0) {
		return new Promise((resolve) => {
			setTimeout(resolve, time);
		});
	},

	visible_message(a, ...b) {
		if(typeof a == "string") {
			return new ChatMessage("see", a);
		}
		return module.exports.visible_message(module.exports.format_html(a, ...b));
	},

	audible_message(a, ...b) {
		if(typeof a == "string") {
			return new ChatMessage("hear", a);
		}
		return module.exports.audible_message(module.exports.format_html(a, ...b));
	},

	to_chat(a, ...b) {
		if(a instanceof Atom || a instanceof Client) {
			var cl;
			if(a instanceof Client)
				cl = a;
			else
				cl = a.c.Mob.client;
			if(!cl)
				return;
			if(!cl.next_message.to_chat)
				cl.next_message.to_chat = [];
			cl.next_message.to_chat.push(b.join(""));
		} else if(a instanceof Array && a.length && (a[0] instanceof Atom || a[0] instanceof Client || a[0] instanceof Array)) {
			for(var item of a) {
				module.exports.to_chat(item, ...b);
			}
		} else {
			var formatted = module.exports.format_html(a, ...b);
			return (...items) => {
				module.exports.to_chat(items, formatted);
			};
		}
	},

	format_html(strs, ...tags) {
		var out_str = '';
		for(let i = 0; i < strs.length; i++) {
			var pre_tag = strs[i];
			if(i == strs.length - 1) {
				out_str += pre_tag;
				continue;
			}
			var str_tag = ""+tags[i];
			var is_proper = str_tag.length && str_tag[0] == str_tag[0].toUpperCase();
			var gender = "neutral";
			if(tags[i] instanceof Atom) {
				if(tags[i].force_improper)
					is_proper = false;
				if(tags[i].force_proper)
					is_proper = true;
				gender = tags[i].gender;
			}
			if(is_proper)
				pre_tag = pre_tag.replace(/(^|[ \t.,>])(?:the|a) (?=(?:[ \t]|(?:<[^>]+>))*$)/i, "$1");
			else if(gender == "plural")
				pre_tag = pre_tag.replace(/((?:^|[ \t.,>]))a(?= (?:[ \t]|(?:<[^>]+>))*$)/i, "$1some");
			else if(str_tag.match(/^[aeiou]/i))
				pre_tag = pre_tag.replace(/((?:^|[ \t.,>])a)(?= (?:[ \t]|(?:<[^>]+>))*$)/i, "$1n");
			tags[i] = ""+tags[i];
			out_str += pre_tag;
			out_str += module.exports.escape_html(tags[i]);
		}
		return out_str;
	},

	escape_html(str) {
		return str.replace(/[&<>"']/gi, (chr) => {
			if(chr == '&') return '&';
			if(chr == '<') return '<';
			if(chr == '>') return '>';
			if(chr == '"') return '"';
			if(chr == "'") return ''';
		});
	},

	do_require() {
		Atom = require('./atom/atom.js');
		Client = require('./client.js');
		ChatMessage = require('./chat_message.js');
	},

	readonly_traps: {set: ()=>{},deleteProperty: ()=>{},defineProperty: ()=>{},setPrototypeOf: ()=>{},isExtensible:()=>{return false;}}
};
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');

/**
 * Finds package.json file from either the directory the script was called from or a supplied path.
 *
 *     console.log(findPackageFileInPath());
 *     console.log(findPackageFileInPath('./package.json'));
 *     console.log(findPackageFileInPath('~/git/github/doxdox/'));
 *
 * @param {String} [input] Directory or file.
 * @return {String} Path to package.json file.
 * @public
 */

const findPackageFileInPath = input => {

    let pkgPath = null;

    if (!input) {

        input = process.cwd();

    }

    if (fs.existsSync(input)) {

        const stat = fs.statSync(input);

        if (stat.isDirectory()) {

            pkgPath = path.resolve(path.join(input, '/package.json'));

        } else if (stat.isFile()) {

            pkgPath = path.resolve(path.join(path.dirname(input), '/package.json'));

        }

    }

    return pkgPath;

};

module.exports = {
    findPackageFileInPath
};
<commit_msg>Cleaned up logic.<commit_after>const fs = require('fs');
const path = require('path');

/**
 * Finds package.json file from either the directory the script was called from or a supplied path.
 *
 *     console.log(findPackageFileInPath());
 *     console.log(findPackageFileInPath('./package.json'));
 *     console.log(findPackageFileInPath('~/git/github/doxdox/'));
 *
 * @param {String} [input] Directory or file.
 * @return {String} Path to package.json file.
 * @public
 */

const findPackageFileInPath = input => {

    let pkgPath = null;

    if (!input) {

        input = process.cwd();

    }

    if (fs.existsSync(input)) {

        const stat = fs.statSync(input);

        if (stat.isFile()) {

            pkgPath = path.resolve(path.join(path.dirname(input), '/package.json'));

        } else {

            pkgPath = path.resolve(path.join(input, '/package.json'));

        }

    }

    return pkgPath;

};

module.exports = {
    findPackageFileInPath
};
<|endoftext|>


<commit_before>'use strict'
/**
 * Copyright (c) 2010-2017 Brian Carlson (brian.m.carlson@gmail.com)
 * All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * README.md file in the root directory of this source tree.
 */

const crypto = require('crypto')

const defaults = require('./defaults')

function escapeElement (elementRepresentation) {
  var escaped = elementRepresentation
    .replace(/\\/g, '\\\\')
    .replace(/"/g, '\\"')

  return '"' + escaped + '"'
}

// convert a JS array to a postgres array literal
// uses comma separator so won't work for types like box that use
// a different array separator.
function arrayString (val) {
  var result = '{'
  for (var i = 0; i < val.length; i++) {
    if (i > 0) {
      result = result + ','
    }
    if (val[i] === null || typeof val[i] === 'undefined') {
      result = result + 'NULL'
    } else if (Array.isArray(val[i])) {
      result = result + arrayString(val[i])
    } else if (val[i] instanceof Buffer) {
      result += '\\\\x' + val[i].toString('hex')
    } else {
      result += escapeElement(prepareValue(val[i]))
    }
  }
  result = result + '}'
  return result
}

// converts values from javascript types
// to their 'raw' counterparts for use as a postgres parameter
// note: you can override this function to provide your own conversion mechanism
// for complex types, etc...
var prepareValue = function (val, seen) {
  if (val instanceof Buffer) {
    return val
  }
  if (val instanceof Date) {
    if (defaults.parseInputDatesAsUTC) {
      return dateToStringUTC(val)
    } else {
      return dateToString(val)
    }
  }
  if (Array.isArray(val)) {
    return arrayString(val)
  }
  if (val === null || typeof val === 'undefined') {
    return null
  }
  if (typeof val === 'object') {
    return prepareObject(val, seen)
  }
  return val.toString()
}

function prepareObject (val, seen) {
  if (val && typeof val.toPostgres === 'function') {
    seen = seen || []
    if (seen.indexOf(val) !== -1) {
      throw new Error('circular reference detected while preparing "' + val + '" for query')
    }
    seen.push(val)

    return prepareValue(val.toPostgres(prepareValue), seen)
  }
  return JSON.stringify(val)
}

function pad (number, digits) {
  number = '' + number
  while (number.length < digits) { number = '0' + number }
  return number
}

function dateToString (date) {
  var offset = -date.getTimezoneOffset()
  var ret = pad(date.getFullYear(), 4) + '-' +
    pad(date.getMonth() + 1, 2) + '-' +
    pad(date.getDate(), 2) + 'T' +
    pad(date.getHours(), 2) + ':' +
    pad(date.getMinutes(), 2) + ':' +
    pad(date.getSeconds(), 2) + '.' +
    pad(date.getMilliseconds(), 3)

  if (offset < 0) {
    ret += '-'
    offset *= -1
  } else { ret += '+' }

  return ret + pad(Math.floor(offset / 60), 2) + ':' + pad(offset % 60, 2)
}

function dateToStringUTC (date) {
  var ret = pad(date.getUTCFullYear(), 4) + '-' +
    pad(date.getUTCMonth() + 1, 2) + '-' +
    pad(date.getUTCDate(), 2) + 'T' +
    pad(date.getUTCHours(), 2) + ':' +
    pad(date.getUTCMinutes(), 2) + ':' +
    pad(date.getUTCSeconds(), 2) + '.' +
    pad(date.getUTCMilliseconds(), 3)

  return ret + '+00:00'
}

function normalizeQueryConfig (config, values, callback) {
  // can take in strings or config objects
  config = (typeof (config) === 'string') ? { text: config } : config
  if (values) {
    if (typeof values === 'function') {
      config.callback = values
    } else {
      config.values = values
    }
  }
  if (callback) {
    config.callback = callback
  }
  return config
}

const md5 = function (string) {
  return crypto.createHash('md5').update(string, 'utf-8').digest('hex')
}

// See AuthenticationMD5Password at https://www.postgresql.org/docs/current/static/protocol-flow.html
const postgresMd5PasswordHash = function (user, password, salt) {
  var inner = md5(password + user)
  var outer = md5(Buffer.concat([Buffer.from(inner), salt]))
  return 'md5' + outer
}

module.exports = {
  prepareValue: function prepareValueWrapper (value) {
    // this ensures that extra arguments do not get passed into prepareValue
    // by accident, eg: from calling values.map(utils.prepareValue)
    return prepareValue(value)
  },
  normalizeQueryConfig: normalizeQueryConfig,
  postgresMd5PasswordHash: postgresMd5PasswordHash,
  md5: md5
}
<commit_msg>Normalize export in utils to use short form<commit_after>'use strict'
/**
 * Copyright (c) 2010-2017 Brian Carlson (brian.m.carlson@gmail.com)
 * All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * README.md file in the root directory of this source tree.
 */

const crypto = require('crypto')

const defaults = require('./defaults')

function escapeElement (elementRepresentation) {
  var escaped = elementRepresentation
    .replace(/\\/g, '\\\\')
    .replace(/"/g, '\\"')

  return '"' + escaped + '"'
}

// convert a JS array to a postgres array literal
// uses comma separator so won't work for types like box that use
// a different array separator.
function arrayString (val) {
  var result = '{'
  for (var i = 0; i < val.length; i++) {
    if (i > 0) {
      result = result + ','
    }
    if (val[i] === null || typeof val[i] === 'undefined') {
      result = result + 'NULL'
    } else if (Array.isArray(val[i])) {
      result = result + arrayString(val[i])
    } else if (val[i] instanceof Buffer) {
      result += '\\\\x' + val[i].toString('hex')
    } else {
      result += escapeElement(prepareValue(val[i]))
    }
  }
  result = result + '}'
  return result
}

// converts values from javascript types
// to their 'raw' counterparts for use as a postgres parameter
// note: you can override this function to provide your own conversion mechanism
// for complex types, etc...
var prepareValue = function (val, seen) {
  if (val instanceof Buffer) {
    return val
  }
  if (val instanceof Date) {
    if (defaults.parseInputDatesAsUTC) {
      return dateToStringUTC(val)
    } else {
      return dateToString(val)
    }
  }
  if (Array.isArray(val)) {
    return arrayString(val)
  }
  if (val === null || typeof val === 'undefined') {
    return null
  }
  if (typeof val === 'object') {
    return prepareObject(val, seen)
  }
  return val.toString()
}

function prepareObject (val, seen) {
  if (val && typeof val.toPostgres === 'function') {
    seen = seen || []
    if (seen.indexOf(val) !== -1) {
      throw new Error('circular reference detected while preparing "' + val + '" for query')
    }
    seen.push(val)

    return prepareValue(val.toPostgres(prepareValue), seen)
  }
  return JSON.stringify(val)
}

function pad (number, digits) {
  number = '' + number
  while (number.length < digits) { number = '0' + number }
  return number
}

function dateToString (date) {
  var offset = -date.getTimezoneOffset()
  var ret = pad(date.getFullYear(), 4) + '-' +
    pad(date.getMonth() + 1, 2) + '-' +
    pad(date.getDate(), 2) + 'T' +
    pad(date.getHours(), 2) + ':' +
    pad(date.getMinutes(), 2) + ':' +
    pad(date.getSeconds(), 2) + '.' +
    pad(date.getMilliseconds(), 3)

  if (offset < 0) {
    ret += '-'
    offset *= -1
  } else { ret += '+' }

  return ret + pad(Math.floor(offset / 60), 2) + ':' + pad(offset % 60, 2)
}

function dateToStringUTC (date) {
  var ret = pad(date.getUTCFullYear(), 4) + '-' +
    pad(date.getUTCMonth() + 1, 2) + '-' +
    pad(date.getUTCDate(), 2) + 'T' +
    pad(date.getUTCHours(), 2) + ':' +
    pad(date.getUTCMinutes(), 2) + ':' +
    pad(date.getUTCSeconds(), 2) + '.' +
    pad(date.getUTCMilliseconds(), 3)

  return ret + '+00:00'
}

function normalizeQueryConfig (config, values, callback) {
  // can take in strings or config objects
  config = (typeof (config) === 'string') ? { text: config } : config
  if (values) {
    if (typeof values === 'function') {
      config.callback = values
    } else {
      config.values = values
    }
  }
  if (callback) {
    config.callback = callback
  }
  return config
}

const md5 = function (string) {
  return crypto.createHash('md5').update(string, 'utf-8').digest('hex')
}

// See AuthenticationMD5Password at https://www.postgresql.org/docs/current/static/protocol-flow.html
const postgresMd5PasswordHash = function (user, password, salt) {
  var inner = md5(password + user)
  var outer = md5(Buffer.concat([Buffer.from(inner), salt]))
  return 'md5' + outer
}

module.exports = {
  prepareValue: function prepareValueWrapper (value) {
    // this ensures that extra arguments do not get passed into prepareValue
    // by accident, eg: from calling values.map(utils.prepareValue)
    return prepareValue(value)
  },
  normalizeQueryConfig,
  postgresMd5PasswordHash,
  md5
}
<|endoftext|>