<commit_before>'use strict';

const Readable = require('stream').Readable;
const ConsumerGroup = require('./consumerGroup');
const _ = require('lodash');
const logger = require('./logging')('kafka-node:ConsumerGroupStream');
const async = require('async');
const DEFAULT_HIGH_WATER_MARK = 100;

const DEFAULTS = {
  autoCommit: true
};

function convertToCommitPayload (messages) {
  const ret = [];
  _.forEach(messages, function (partitionOffset, topic) {
    _.forEach(partitionOffset, function (offset, partition) {
      if (offset != null) {
        ret.push({
          topic: topic,
          partition: partition,
          offset: offset,
          metadata: 'm'
        });
      }
    });
  });
  return ret;
}

class ConsumerGroupStream extends Readable {
  constructor (options, topics) {
    super({ objectMode: true, highWaterMark: options.highWaterMark || DEFAULT_HIGH_WATER_MARK });

    _.defaultsDeep(options || {}, DEFAULTS);
    const self = this;

    this.autoCommit = options.autoCommit;

    options.connectOnReady = false;
    options.autoCommit = false;
    const originalOnRebalance = options.onRebalance;
    options.onRebalance = function (isAlreadyMember, callback) {
      const autoCommit = _.once(function (err) {
        if (err) {
          callback(err);
        } else {
          self.commit(null, true, callback);
        }
      });
      if (typeof originalOnRebalance === 'function') {
        try {
          originalOnRebalance(isAlreadyMember, autoCommit);
        } catch (e) {
          autoCommit(e);
        }
      } else {
        autoCommit();
      }
    };

    this.consumerGroup = new ConsumerGroup(options, topics);

    this.messageBuffer = [];
    this.commitQueue = {};

    this.consumerGroup.on('error', error => this.emit('error', error));
    this.consumerGroup.on('message', message => {
      this.messageBuffer.push(message);
      this.consumerGroup.pause();
    });
    this.consumerGroup.on('done', message => {
      setImmediate(() => this.transmitMessages());
    });
  }

  emit (event, value) {
    if (event === 'data' && this.autoCommit && !_.isEmpty(value)) {
      setImmediate(() => this.commit(value));
    }
    super.emit.apply(this, arguments);
  }

  _read () {
    logger.debug('_read called');
    if (!this.consumerGroup.ready) {
      logger.debug('consumerGroup is not ready, calling consumerGroup.connect');
      this.consumerGroup.connect();
    }
    this._reading = true;
    this.transmitMessages();
  }

  commit (message, force, callback) {
    if (message != null && message.offset !== -1) {
      _.set(this.commitQueue, [message.topic, message.partition], message.offset + 1);
    }

    if (this.committing && !force) {
      logger.debug('skipping committing');
      return callback && callback(null);
    }

    const commits = convertToCommitPayload(this.commitQueue);
    this.commitQueued(commits, force, callback);
  }

  commitQueued (commits, force, callback) {
    this.committing = true;

    if (!force) {
      this.autoCommitTimer = setTimeout(() => {
        logger.debug('setting committing to false');
        this.committing = false;

        const queuedCommits = convertToCommitPayload(this.commitQueue);
        if (!_.isEmpty(queuedCommits)) this.commitQueued(queuedCommits);
      }, this.consumerGroup.options.autoCommitIntervalMs);
    }

    if (_.isEmpty(commits)) {
      logger.debug('commit ignored. no commits to make.');
      return callback && callback(null);
    }

    logger.debug('committing', commits);

    this.consumerGroup.sendOffsetCommitRequest(commits, error => {
      if (error) {
        logger.error('commit request failed', error);
        if (callback) {
          return callback(error);
        }
        this.emit('error', error);
        return;
      }
      for (let tp of commits) {
        if (_.get(this.commitQueue, [tp.topic, tp.partition]) === tp.offset) {
          this.commitQueue[tp.topic][tp.partition] = null;
        }
      }
      callback && callback(null);
    });
  }

  transmitMessages () {
    while (this._reading && this.messageBuffer.length > 0) {
      this._reading = this.push(this.messageBuffer.shift());
    }
    if (this.messageBuffer.length === 0 && this._reading) {
      this.consumerGroup.resume();
    }
  }

  close (callback) {
    clearTimeout(this.autoCommitTimer);
    async.series(
      [
        callback => {
          if (this.autoCommit) {
            this.commit(null, true, callback);
          } else {
            callback(null);
          }
        },
        callback => {
          this.consumerGroup.close(false, () => {
            callback();
            this.emit('close');
          });
        }
      ],
      callback || _.noop
    );
  }

  _destroy () {
    this.close();
  }
}

module.exports = ConsumerGroupStream;
<commit_msg>Emit connect event for consumer group stream (#935)<commit_after>'use strict';

const Readable = require('stream').Readable;
const ConsumerGroup = require('./consumerGroup');
const _ = require('lodash');
const logger = require('./logging')('kafka-node:ConsumerGroupStream');
const async = require('async');
const DEFAULT_HIGH_WATER_MARK = 100;

const DEFAULTS = {
  autoCommit: true
};

function convertToCommitPayload (messages) {
  const ret = [];
  _.forEach(messages, function (partitionOffset, topic) {
    _.forEach(partitionOffset, function (offset, partition) {
      if (offset != null) {
        ret.push({
          topic: topic,
          partition: partition,
          offset: offset,
          metadata: 'm'
        });
      }
    });
  });
  return ret;
}

class ConsumerGroupStream extends Readable {
  constructor (options, topics) {
    super({ objectMode: true, highWaterMark: options.highWaterMark || DEFAULT_HIGH_WATER_MARK });

    _.defaultsDeep(options || {}, DEFAULTS);
    const self = this;

    this.autoCommit = options.autoCommit;

    options.connectOnReady = false;
    options.autoCommit = false;
    const originalOnRebalance = options.onRebalance;
    options.onRebalance = function (isAlreadyMember, callback) {
      const autoCommit = _.once(function (err) {
        if (err) {
          callback(err);
        } else {
          self.commit(null, true, callback);
        }
      });
      if (typeof originalOnRebalance === 'function') {
        try {
          originalOnRebalance(isAlreadyMember, autoCommit);
        } catch (e) {
          autoCommit(e);
        }
      } else {
        autoCommit();
      }
    };

    this.consumerGroup = new ConsumerGroup(options, topics);

    this.messageBuffer = [];
    this.commitQueue = {};

    this.consumerGroup.on('error', error => this.emit('error', error));
    this.consumerGroup.on('connect', () => this.emit('connect'));
    this.consumerGroup.on('message', message => {
      this.messageBuffer.push(message);
      this.consumerGroup.pause();
    });
    this.consumerGroup.on('done', message => {
      setImmediate(() => this.transmitMessages());
    });
  }

  emit (event, value) {
    if (event === 'data' && this.autoCommit && !_.isEmpty(value)) {
      setImmediate(() => this.commit(value));
    }
    super.emit.apply(this, arguments);
  }

  _read () {
    logger.debug('_read called');
    if (!this.consumerGroup.ready) {
      logger.debug('consumerGroup is not ready, calling consumerGroup.connect');
      this.consumerGroup.connect();
    }
    this._reading = true;
    this.transmitMessages();
  }

  commit (message, force, callback) {
    if (message != null && message.offset !== -1) {
      _.set(this.commitQueue, [message.topic, message.partition], message.offset + 1);
    }

    if (this.committing && !force) {
      logger.debug('skipping committing');
      return callback && callback(null);
    }

    const commits = convertToCommitPayload(this.commitQueue);
    this.commitQueued(commits, force, callback);
  }

  commitQueued (commits, force, callback) {
    this.committing = true;

    if (!force) {
      this.autoCommitTimer = setTimeout(() => {
        logger.debug('setting committing to false');
        this.committing = false;

        const queuedCommits = convertToCommitPayload(this.commitQueue);
        if (!_.isEmpty(queuedCommits)) this.commitQueued(queuedCommits);
      }, this.consumerGroup.options.autoCommitIntervalMs);
    }

    if (_.isEmpty(commits)) {
      logger.debug('commit ignored. no commits to make.');
      return callback && callback(null);
    }

    logger.debug('committing', commits);

    this.consumerGroup.sendOffsetCommitRequest(commits, error => {
      if (error) {
        logger.error('commit request failed', error);
        if (callback) {
          return callback(error);
        }
        this.emit('error', error);
        return;
      }
      for (let tp of commits) {
        if (_.get(this.commitQueue, [tp.topic, tp.partition]) === tp.offset) {
          this.commitQueue[tp.topic][tp.partition] = null;
        }
      }
      callback && callback(null);
    });
  }

  transmitMessages () {
    while (this._reading && this.messageBuffer.length > 0) {
      this._reading = this.push(this.messageBuffer.shift());
    }
    if (this.messageBuffer.length === 0 && this._reading) {
      this.consumerGroup.resume();
    }
  }

  close (callback) {
    clearTimeout(this.autoCommitTimer);
    async.series(
      [
        callback => {
          if (this.autoCommit) {
            this.commit(null, true, callback);
          } else {
            callback(null);
          }
        },
        callback => {
          this.consumerGroup.close(false, () => {
            callback();
            this.emit('close');
          });
        }
      ],
      callback || _.noop
    );
  }

  _destroy () {
    this.close();
  }
}

module.exports = ConsumerGroupStream;
<|endoftext|>


<commit_before>var util = require("./util");

exports['test Known property'] = function() {
	// Known property document.getElementById
	util.assertLint("var elt = document.getElementById('myId');", {
		messages : []
	}, [ "browser" ]);
}

exports['test Unknown property'] = function() {
	// Unknown property
	util.assertLint("var elt = document.getElementByIdXXX('myId');", {
		messages : [ {
			"message" : "Unknown property 'getElementByIdXXX'",
			"from" : 19,
			"to" : 36,
			"severity" : "warning"
		} ]
	}, [ "browser" ]);
	// Unknown property as error
	var options = {"rules" : {"UnknownProperty" : {"severity" : "error"}}};
	util.assertLint("var elt = document.getElementByIdXXX('myId');", {
		messages : [ {
			"message" : "Unknown property 'getElementByIdXXX'",
			"from" : 19,
			"to" : 36,
			"severity" : "error"
		} ]
	}, [ "browser" ], options);
}

exports['test Unknown identifier'] = function() {
	// without 'browser' def, document is not known
	// The check does not continue to getElementById, since
	// the real cause is that document is undefined.
	util.assertLint("var elt = document.getElementById('myId');", {
		messages : [ {
			"message" : "Unknown identifier 'document'",
			"from" : 10,
			"to" : 18,
			"severity" : "warning"
		} ]
	});
	// Unknown identifier as error
	var options = {"rules" : {"UnknownIdentifier" : {"severity" : "error"}}};
	util.assertLint("var elt = document.getElementById('myId');", {
		messages : [ {
			"message" : "Unknown identifier 'document'",
			"from" : 10,
			"to" : 18,
			"severity" : "error"
		} ]
	}, null, options);
}

exports['test issue1'] = function() {
	// Known property for this. See issue
	// https://github.com/angelozerr/tern.lint/issues/1
	util.assertLint("var a = [];\nvar len = a.length();", {
		messages : [ {
			"message" : "'length' is not a function",
			"from" : 24,
			"to" : 30,
			"severity" : "error"
		} ]
	}, [ "ecma5" ]);
	// Not a function as warning
	var options = {"rules" : {"NotAFunction" : {"severity" : "warning"}}};
	util.assertLint("var a = [];\nvar len = a.length();", {
		messages : [ {
			"message" : "'length' is not a function",
			"from" : 24,
			"to" : 30,
			"severity" : "warning"
		} ]
	}, [ "ecma5" ], options);
	// without ecma5, var 'a' is not an array.
	util.assertLint("var a = [];\nvar len = a.length();", {
		messages : [ {
			"message" : "Unknown property 'length'",
			"from" : 24,
			"to" : 30,
			"severity" : "warning"
		} ]
	});
}

exports['test issue2'] = function() {
	// Known property for this. See issue
	// https://github.com/angelozerr/tern.lint/issues/2
	util
			.assertLint(
					"function CTor() { this.size = 10; }\nCTor.prototype.hallo = 'hallo';",
					{
						messages : []
					});
}

exports['test variables inside functions'] = function() {
	util.assertLint("function test() { var a = {len: 5}; var len = a.len; }\nfunction b() { }", {
		messages : [ ]
	});

	util.assertLint("function b() { }\nfunction test() { var d = 5; var a = {len: 5}; var len = a.len; }", {
		messages : [ ]
	});
}

exports['test functions parameters'] = function() {
	// In this case the type of `a` is inferred as a string
	util.assertLint("function test(a) { var t = a; }; test('something');", {
		messages : [ ]
	});

	// In this case the type is unknown, but the variable is defined
	// (should not produce a warning)
	util.assertLint("function test(a) { var t = a; };", {
		messages : [ ]
	});
}

exports['test properties on functions parameters'] = function() {
	// In this case the type of `a` is inferred as an object with a property `len`.
	util.assertLint("function test(a) { var len = a.len; }; test({len: 5});", {
		messages : [ ]
	});

	// In this case the type of `a` is unknown, and should not produce warnings
	// on any of its properties.
	util.assertLint("function test(a) { var len = a.len; };", {
		messages : [ ]
	});

	// The same goes for function calls on an unknown type
	util.assertLint("function test(a) { var len = a.myLength(); };", {
		messages : [ ]
	});
}

exports['test assignment of unknown value'] = function() {

	util.assertLint("var a = {}; function test(p) { var b = a.b; };", {
		messages : [ {
			"message": "Unknown property 'b'",
			"from": 41,
			"to": 42,
			"severity": "warning"} ]
	});

	// The type of a.t is unknown, but it is still a valid property.
	util.assertLint("var a = {}; function test(p) { a.t = p; var b = a.t; }", {
		messages : [ ]
	});

	util.assertLint("var a = {}; function test(p) { a.t = p; }", {
		messages : [ ]
	});

	// This should only contain a warning for `notdefined`, not for b = a.val.
	util.assertLint("function A() {}; A.prototype.val = notdefined; var a = new A(); var b = a.val;", {
		messages : [ {
			"message": "Unknown identifier 'notdefined'",
			"from": 35,
			"to": 45,
			"severity": "warning"} ]
	});

	util.assertLint("var a = {t: 5}; function test(p) { a.t = p; }", {
		messages : [ ]
	});
}

exports['test dynamic properties (bracket notation)'] = function() {
	util.assertLint("var obj = { test: 1 }; var key = 'test'; var val1 = obj[key]; var val2 = obj['test'];", {
		messages : [ ]
	});

	util.assertLint("var obj = { test: function() {} }; var key = 'test'; obj[key](); obj['test']();", {
		messages : [ ]
	});
}

exports['test Invalid Argument'] = function() {
  // id is string => OK
  util.assertLint("var elt = document.getElementById('100');", {
          messages : []
  }, [ "browser" ]);
  // id is string => OK
  util.assertLint("var id = '100'; var elt = document.getElementById(id);", {
          messages : []
  }, [ "browser" ]);
  // id is number although it should be string
  util.assertLint("var elt = document.getElementById(100);", {
          messages : [ {
            "message": "Invalid argument at 1: cannot convert from Number.prototype to String.prototype",
            "from": 34,
            "to": 37,
            "severity": "error"}]
  }, [ "browser" ]);
  // id is number although it should be string
  util.assertLint("var id = 100; var elt = document.getElementById(id);", {
          messages : [ {
            "message": "Invalid argument at 1: cannot convert from Number.prototype to String.prototype",
            "from": 48,
            "to": 50,
            "severity": "error"}]
  }, [ "browser" ]);
  // listener must be a function => OK
  util.assertLint("var f = function() {}; document.addEventListener('click', f, true)", {
          messages : []
  }, [ "browser" ]);
  // listener must be a function => OK
  util.assertLint("var f = true {}; document.addEventListener('click', f, true)", {
          messages : [{
            "message": "Invalid argument at 2: cannot convert from Boolean.prototype to Function.prototype",
            "from": 52,
            "to": 53,
            "severity": "error"}]
  }, [ "browser" ]);
  // null argument => OK
  util.assertLint("var elt = document.getElementById(null);", {
          messages : []
  }, [ "browser" ]);
  // Unknown argument => throw error widh Unknown identifier
  util.assertLint("var elt = document.getElementById(xxx);", {
          messages : [{
            "message" : "Unknown identifier 'xxx'",
            "from" : 34,
            "to" : 37,
            "severity" : "warning"
    }]
  }, [ "browser" ]);

  // isEqualNode waits Node.prototype and document.getElementById returns Element.prototype which extends Node.prototype => OK
  util.assertLint("document.getElementById('id1').isEqualNode(document.getElementById('id2'))", {
          messages : []
  }, [ "browser" ]);

  // New expression works like Call expression
  util.assertLint("new Array('');", {
    messages : [{
      "message" : "Invalid argument at 1: cannot convert from String.prototype to Number.prototype",
      "from" : 10,
      "to" : 12,
      "severity" : "error"
    }]
  }, [ "ecma5" ]);

}

if (module == require.main)
	require('test').run(exports)<commit_msg>fix comments, make code a bit more clear<commit_after>var util = require("./util");

exports['test Known property'] = function() {
	// Known property document.getElementById
	util.assertLint("var elt = document.getElementById('myId');", {
		messages : []
	}, [ "browser" ]);
}

exports['test Unknown property'] = function() {
	// Unknown property
	util.assertLint("var elt = document.getElementByIdXXX('myId');", {
		messages : [ {
			"message" : "Unknown property 'getElementByIdXXX'",
			"from" : 19,
			"to" : 36,
			"severity" : "warning"
		} ]
	}, [ "browser" ]);
	// Unknown property as error
	var options = {"rules" : {"UnknownProperty" : {"severity" : "error"}}};
	util.assertLint("var elt = document.getElementByIdXXX('myId');", {
		messages : [ {
			"message" : "Unknown property 'getElementByIdXXX'",
			"from" : 19,
			"to" : 36,
			"severity" : "error"
		} ]
	}, [ "browser" ], options);
}

exports['test Unknown identifier'] = function() {
	// without 'browser' def, document is not known
	// The check does not continue to getElementById, since
	// the real cause is that document is undefined.
	util.assertLint("var elt = document.getElementById('myId');", {
		messages : [ {
			"message" : "Unknown identifier 'document'",
			"from" : 10,
			"to" : 18,
			"severity" : "warning"
		} ]
	});
	// Unknown identifier as error
	var options = {"rules" : {"UnknownIdentifier" : {"severity" : "error"}}};
	util.assertLint("var elt = document.getElementById('myId');", {
		messages : [ {
			"message" : "Unknown identifier 'document'",
			"from" : 10,
			"to" : 18,
			"severity" : "error"
		} ]
	}, null, options);
}

exports['test issue1'] = function() {
	// Known property for this. See issue
	// https://github.com/angelozerr/tern.lint/issues/1
	util.assertLint("var a = [];\nvar len = a.length();", {
		messages : [ {
			"message" : "'length' is not a function",
			"from" : 24,
			"to" : 30,
			"severity" : "error"
		} ]
	}, [ "ecma5" ]);
	// Not a function as warning
	var options = {"rules" : {"NotAFunction" : {"severity" : "warning"}}};
	util.assertLint("var a = [];\nvar len = a.length();", {
		messages : [ {
			"message" : "'length' is not a function",
			"from" : 24,
			"to" : 30,
			"severity" : "warning"
		} ]
	}, [ "ecma5" ], options);
	// without ecma5, var 'a' is not an array.
	util.assertLint("var a = [];\nvar len = a.length();", {
		messages : [ {
			"message" : "Unknown property 'length'",
			"from" : 24,
			"to" : 30,
			"severity" : "warning"
		} ]
	});
}

exports['test issue2'] = function() {
	// Known property for this. See issue
	// https://github.com/angelozerr/tern.lint/issues/2
	util
			.assertLint(
					"function CTor() { this.size = 10; }\nCTor.prototype.hallo = 'hallo';",
					{
						messages : []
					});
}

exports['test variables inside functions'] = function() {
	util.assertLint("function test() { var a = {len: 5}; var len = a.len; }\nfunction b() { }", {
		messages : [ ]
	});

	util.assertLint("function b() { }\nfunction test() { var d = 5; var a = {len: 5}; var len = a.len; }", {
		messages : [ ]
	});
}

exports['test functions parameters'] = function() {
	// In this case the type of `a` is inferred as a string
	util.assertLint("function test(a) { var t = a; }; test('something');", {
		messages : [ ]
	});

	// In this case the type is unknown, but the variable is defined
	// (should not produce a warning)
	util.assertLint("function test(a) { var t = a; };", {
		messages : [ ]
	});
}

exports['test properties on functions parameters'] = function() {
	// In this case the type of `a` is inferred as an object with a property `len`.
	util.assertLint("function test(a) { var len = a.len; }; test({len: 5});", {
		messages : [ ]
	});

	// In this case the type of `a` is unknown, and should not produce warnings
	// on any of its properties.
	util.assertLint("function test(a) { var len = a.len; };", {
		messages : [ ]
	});

	// The same goes for function calls on an unknown type
	util.assertLint("function test(a) { var len = a.myLength(); };", {
		messages : [ ]
	});
}

exports['test assignment of unknown value'] = function() {

	util.assertLint("var a = {}; function test(p) { var b = a.b; };", {
		messages : [ {
			"message": "Unknown property 'b'",
			"from": 41,
			"to": 42,
			"severity": "warning"} ]
	});

	// The type of a.t is unknown, but it is still a valid property.
	util.assertLint("var a = {}; function test(p) { a.t = p; var b = a.t; }", {
		messages : [ ]
	});

	util.assertLint("var a = {}; function test(p) { a.t = p; }", {
		messages : [ ]
	});

	// This should only contain a warning for `notdefined`, not for b = a.val.
	util.assertLint("function A() {}; A.prototype.val = notdefined; var a = new A(); var b = a.val;", {
		messages : [ {
			"message": "Unknown identifier 'notdefined'",
			"from": 35,
			"to": 45,
			"severity": "warning"} ]
	});

	util.assertLint("var a = {t: 5}; function test(p) { a.t = p; }", {
		messages : [ ]
	});
}

exports['test dynamic properties (bracket notation)'] = function() {
	util.assertLint("var obj = { test: 1 }; var key = 'test'; var val1 = obj[key]; var val2 = obj['test'];", {
		messages : [ ]
	});

	util.assertLint("var obj = { test: function() {} }; var key = 'test'; obj[key](); obj['test']();", {
		messages : [ ]
	});
}

exports['test Invalid Argument'] = function() {
  // id is string => OK
  util.assertLint("var elt = document.getElementById('100');", {
          messages : []
  }, [ "browser" ]);
  // id is string => OK
  util.assertLint("var id = '100'; var elt = document.getElementById(id);", {
          messages : []
  }, [ "browser" ]);
  // id is number although it should be string
  util.assertLint("var elt = document.getElementById(100);", {
          messages : [ {
            "message": "Invalid argument at 1: cannot convert from Number.prototype to String.prototype",
            "from": 34,
            "to": 37,
            "severity": "error"}]
  }, [ "browser" ]);
  // id is number although it should be string
  util.assertLint("var id = 100; var elt = document.getElementById(id);", {
          messages : [ {
            "message": "Invalid argument at 1: cannot convert from Number.prototype to String.prototype",
            "from": 48,
            "to": 50,
            "severity": "error"}]
  }, [ "browser" ]);
  // listener must be a function => OK
  util.assertLint("var f = function() {}; document.addEventListener('click', f, true)", {
          messages : []
  }, [ "browser" ]);
  // listener must be a function but argument is a boolean
  util.assertLint("var b = true; document.addEventListener('click', b, true)", {
          messages : [{
            "message": "Invalid argument at 2: cannot convert from Boolean.prototype to Function.prototype",
            "from": 49,
            "to": 50,
            "severity": "error"}]
  }, [ "browser" ]);
  // null argument => OK
  util.assertLint("var elt = document.getElementById(null);", {
          messages : []
  }, [ "browser" ]);
  // Unknown argument => throw error widh Unknown identifier
  util.assertLint("var elt = document.getElementById(xxx);", {
          messages : [{
            "message" : "Unknown identifier 'xxx'",
            "from" : 34,
            "to" : 37,
            "severity" : "warning"
    }]
  }, [ "browser" ]);

  // isEqualNode waits Node.prototype and document.getElementById returns Element.prototype which extends Node.prototype => OK
  util.assertLint("document.getElementById('id1').isEqualNode(document.getElementById('id2'))", {
          messages : []
  }, [ "browser" ]);

  // New expression works like Call expression
  util.assertLint("new Array('');", {
    messages : [{
      "message" : "Invalid argument at 1: cannot convert from String.prototype to Number.prototype",
      "from" : 10,
      "to" : 12,
      "severity" : "error"
    }]
  }, [ "ecma5" ]);

}

if (module == require.main)
	require('test').run(exports)
<|endoftext|>


<commit_before>require('normalize.css');
require('styles/App.css');

import React from 'react';

let yeomanImage = require('../images/yeoman.png');

class AppComponent extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = { background: 'red' };
  }
  render() {
    return (

Please edit src/components/Main.js to get started!

    );
  }
}

AppComponent.defaultProps = {
};

export default AppComponent;
<commit_msg>Add in stuff at the top of the file<commit_after>require('normalize.css');
require('styles/App.css');

import React from 'react';

let someUnusedStuff = 'hello';
let yeomanImage = require('../images/yeoman.png');

const one = 1;
const moreStuff = [{}]
console.info([1,2,3].map(console.info));

class AppComponent extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = { background: 'red' };
  }
  render() {
    return (

Please edit src/components/Main.js to get started!

    );
  }
}

AppComponent.defaultProps = {
};

export default AppComponent;
<|endoftext|>


<commit_before><commit_msg>Add back extra procedural calls to functional definitions in toolbox in start blocks editing<commit_after><|endoftext|>


<commit_before>const webpack = require('webpack')
const debounce = require('lodash.debounce')

const { log, warn, fatal } = require('../helpers/logger')
const { spawn } = require('../helpers/spawn')
const appPaths = require('../app-paths')
const nodePackager = require('../helpers/node-packager')
const getPackageJson = require('../helpers/get-package-json')
const getPackage = require('../helpers/get-package')

class ElectronRunner {
  constructor () {
    this.pid = 0
    this.watcher = null
  }

  init () {}

  async run (quasarConfFile, argv) {
    const url = quasarConfFile.quasarConf.build.APP_URL

    if (this.pid) {
      if (this.url !== url) {
        await this.stop()
      }
      else {
        return
      }
    }

    this.url = url

    const compiler = webpack(quasarConfFile.webpackConf.main)

    return new Promise(resolve => {
      log(`Building main Electron process...`)

      this.watcher = compiler.watch({}, async (err, stats) => {
        if (err) {
          console.log(err)
          return
        }

        log(`Webpack built Electron main process`)
        log()
        process.stdout.write(stats.toString({
          colors: true,
          modules: false,
          children: false,
          chunks: false,
          chunkModules: false
        }) + '\n')
        log()

        if (stats.hasErrors()) {
          warn(`Electron main build failed with errors`)
          return
        }

        await this.__stopElectron()
        this.__startElectron(argv._)

        resolve()
      })

      const preloadFile = appPaths.resolve.electron('main-process/electron-preload.js')

      if (fs.existsSync(preloadFile)) {
        // Start watching for electron-preload.js changes
        this.preloadWatcher = chokidar
          .watch(preloadFile, { watchers: { chokidar: { ignoreInitial: true } } })

        this.preloadWatcher.on('change', debounce(async () => {
          console.log()
          log(`electron-preload.js changed`)

          await this.__stopElectron()
          this.__startElectron(argv._)

          resolve()
        }, 1000))
      }
    })
  }

  build (quasarConfFile) {
    const cfg = quasarConfFile.quasarConf

    return new Promise(resolve => {
      spawn(
        nodePackager,
        [ 'install', '--production' ].concat(cfg.electron.unPackagedInstallParams),
        { cwd: cfg.build.distDir },
        code => {
          if (code) {
            fatal(`[FAIL] ${nodePackager} failed installing dependencies`)
          }
          resolve()
        }
      )
    }).then(() => {
      return new Promise(async resolve => {
        if (typeof cfg.electron.beforePackaging === 'function') {
          log('Running beforePackaging()')
          log()

          const result = cfg.electron.beforePackaging({
            appPaths,
            unpackagedDir: cfg.build.distDir
          })

          if (result && result.then) {
            await result
          }

          log()
          log('[SUCCESS] Done running beforePackaging()')
        }
        resolve()
      })
    }).then(() => {
      const bundlerName = cfg.electron.bundler
      const bundlerConfig = cfg.electron[bundlerName]
      const bundler = require('./bundler').getBundler(bundlerName)
      const pkgName = `electron-${bundlerName}`

      return new Promise((resolve, reject) => {
        log(`Bundling app with electron-${bundlerName}...`)
        log()

        const bundlePromise = bundlerName === 'packager'
          ? bundler({
            ...bundlerConfig,
            electronVersion: getPackageJson('electron').version
          })
          : bundler.build(bundlerConfig)

        bundlePromise
          .then(() => {
            log()
            log(`[SUCCESS] ${pkgName} built the app`)
            log()
            resolve()
          })
          .catch(err => {
            log()
            warn(`[FAIL] ${pkgName} could not build`)
            log()
            console.error(err + '\n')
            reject()
          })
      })
    })
  }

  stop () {
    return new Promise(resolve => {
      let counter = 0
      const maxCounter = (this.watcher ? 1 : 0) + (this.preloadWatcher ? 1 : 0)

      const finalize = () => {
        counter++
        if (maxCounter <= counter) {
          this.__stopElectron().then(resolve)
        }
      }

      if (this.watcher) {
        this.watcher.close(finalize)
        this.watcher = null
      }

      if (this.preloadWatcher) {
        this.preloadWatcher.close().then(finalize)
        this.preloadWatcher = null
      }

      if (maxCounter === 0) {
        finalize()
      }
    })
  }

  __startElectron (extraParams) {
    log(`Booting up Electron process...`)
    this.pid = spawn(
      getPackage('electron'),
      [
        '--inspect=5858',
        appPaths.resolve.app('.quasar/electron/electron-main.js')
      ].concat(extraParams),
      { cwd: appPaths.appDir },
      code => {
        if (this.killPromise) {
          this.killPromise()
          this.killPromise = null
        }
        else if (code) {
          warn()
          fatal(`Electron process ended with error code: ${code}\n`)
        }
        else { // else it wasn't killed by us
          warn()
          fatal('Electron process was killed. Exiting...\n')
        }
      }
    )
  }

  __stopElectron () {
    const pid = this.pid

    if (!pid) {
      return Promise.resolve()
    }

    log('Shutting down Electron process...')
    this.pid = 0
    return new Promise(resolve => {
      this.killPromise = resolve
      process.kill(pid)
    })
  }
}

module.exports = new ElectronRunner()
<commit_msg>chore(app): addition to previous electron commit<commit_after>const webpack = require('webpack')
const chokidar = require('chokidar')
const fs = require('fs')
const debounce = require('lodash.debounce')

const { log, warn, fatal } = require('../helpers/logger')
const { spawn } = require('../helpers/spawn')
const appPaths = require('../app-paths')
const nodePackager = require('../helpers/node-packager')
const getPackageJson = require('../helpers/get-package-json')
const getPackage = require('../helpers/get-package')

class ElectronRunner {
  constructor () {
    this.pid = 0
    this.watcher = null
  }

  init () {}

  async run (quasarConfFile, argv) {
    const url = quasarConfFile.quasarConf.build.APP_URL

    if (this.pid) {
      if (this.url !== url) {
        await this.stop()
      }
      else {
        return
      }
    }

    this.url = url

    const compiler = webpack(quasarConfFile.webpackConf.main)

    return new Promise(resolve => {
      log(`Building main Electron process...`)

      this.watcher = compiler.watch({}, async (err, stats) => {
        if (err) {
          console.log(err)
          return
        }

        log(`Webpack built Electron main process`)
        log()
        process.stdout.write(stats.toString({
          colors: true,
          modules: false,
          children: false,
          chunks: false,
          chunkModules: false
        }) + '\n')
        log()

        if (stats.hasErrors()) {
          warn(`Electron main build failed with errors`)
          return
        }

        await this.__stopElectron()
        this.__startElectron(argv._)

        resolve()
      })

      const preloadFile = appPaths.resolve.electron('main-process/electron-preload.js')

      if (fs.existsSync(preloadFile)) {
        // Start watching for electron-preload.js changes
        this.preloadWatcher = chokidar
          .watch(preloadFile, { watchers: { chokidar: { ignoreInitial: true } } })

        this.preloadWatcher.on('change', debounce(async () => {
          console.log()
          log(`electron-preload.js changed`)

          await this.__stopElectron()
          this.__startElectron(argv._)

          resolve()
        }, 1000))
      }
    })
  }

  build (quasarConfFile) {
    const cfg = quasarConfFile.quasarConf

    return new Promise(resolve => {
      spawn(
        nodePackager,
        [ 'install', '--production' ].concat(cfg.electron.unPackagedInstallParams),
        { cwd: cfg.build.distDir },
        code => {
          if (code) {
            fatal(`[FAIL] ${nodePackager} failed installing dependencies`)
          }
          resolve()
        }
      )
    }).then(() => {
      return new Promise(async resolve => {
        if (typeof cfg.electron.beforePackaging === 'function') {
          log('Running beforePackaging()')
          log()

          const result = cfg.electron.beforePackaging({
            appPaths,
            unpackagedDir: cfg.build.distDir
          })

          if (result && result.then) {
            await result
          }

          log()
          log('[SUCCESS] Done running beforePackaging()')
        }
        resolve()
      })
    }).then(() => {
      const bundlerName = cfg.electron.bundler
      const bundlerConfig = cfg.electron[bundlerName]
      const bundler = require('./bundler').getBundler(bundlerName)
      const pkgName = `electron-${bundlerName}`

      return new Promise((resolve, reject) => {
        log(`Bundling app with electron-${bundlerName}...`)
        log()

        const bundlePromise = bundlerName === 'packager'
          ? bundler({
            ...bundlerConfig,
            electronVersion: getPackageJson('electron').version
          })
          : bundler.build(bundlerConfig)

        bundlePromise
          .then(() => {
            log()
            log(`[SUCCESS] ${pkgName} built the app`)
            log()
            resolve()
          })
          .catch(err => {
            log()
            warn(`[FAIL] ${pkgName} could not build`)
            log()
            console.error(err + '\n')
            reject()
          })
      })
    })
  }

  stop () {
    return new Promise(resolve => {
      let counter = 0
      const maxCounter = (this.watcher ? 1 : 0) + (this.preloadWatcher ? 1 : 0)

      const finalize = () => {
        counter++
        if (maxCounter <= counter) {
          this.__stopElectron().then(resolve)
        }
      }

      if (this.watcher) {
        this.watcher.close(finalize)
        this.watcher = null
      }

      if (this.preloadWatcher) {
        this.preloadWatcher.close().then(finalize)
        this.preloadWatcher = null
      }

      if (maxCounter === 0) {
        finalize()
      }
    })
  }

  __startElectron (extraParams) {
    log(`Booting up Electron process...`)
    this.pid = spawn(
      getPackage('electron'),
      [
        '--inspect=5858',
        appPaths.resolve.app('.quasar/electron/electron-main.js')
      ].concat(extraParams),
      { cwd: appPaths.appDir },
      code => {
        if (this.killPromise) {
          this.killPromise()
          this.killPromise = null
        }
        else if (code) {
          warn()
          fatal(`Electron process ended with error code: ${code}\n`)
        }
        else { // else it wasn't killed by us
          warn()
          fatal('Electron process was killed. Exiting...\n')
        }
      }
    )
  }

  __stopElectron () {
    const pid = this.pid

    if (!pid) {
      return Promise.resolve()
    }

    log('Shutting down Electron process...')
    this.pid = 0
    return new Promise(resolve => {
      this.killPromise = resolve
      process.kill(pid)
    })
  }
}

module.exports = new ElectronRunner()
<|endoftext|>


<commit_before>var React = require('react/addons');
var ReactGoogleMaps = require('react-googlemaps');
var GoogleMapsAPI = window.google.maps;
var {Map,Marker, Polyline, Circle, OverlayView} = ReactGoogleMaps;
var LatLng = GoogleMapsAPI.LatLng;
import Constants from '../constants/Main.js'
import PathStore from '../stores/PathStore.js'
import assign from 'react/lib/Object.assign';

var Path = React.createClass({
    getInitialState: function () {
        return assign({}, {
            center: Constants.WarsawPosition(),
            zoom: 11
        }, PathStore.getState());
    },
    componentDidMount: function () {
        PathStore.onChange(this._handlePathStoreChange)
    },
    componentWillUnmount: function () {
        PathStore.off(this._handlePathStoreChange)
    },
    componentWillReceiveProps: function(nextProps) {
        this.setState({
            beg_coord: this._toPosition(nextProps.beginCoord),
            dest_coord: this._toPosition(nextProps.destCoord)
        });
    },
    render: function () {
        var location_circle = this.state.location.coords === undefined ? null : <Circle
            strokeColor="#64b5f6"
            fillColor="#64b5f6"
            center={new LatLng(this.state.location.coords.latitude, this.state.location.coords.longitude)}
            radius={this.state.location.coords.accuracy}/>;
        if (this.state.route.path === undefined || this.state.route.path.points === null) {
            var route = null;
            if (this.state.route.beg_coord && this.state.route.dest_coord) {
                var from_start = (<Polyline
                    strokeColor="#999"
                    path={[this.state.route.beg_coord, this.state.route.dest_coord].map(this._toPosition)}/>);
            } else {
                from_start = null;
            }
            var to_finish = null;
        } else {
            route = (<Polyline
                strokeColor="#000"
                path={this.state.route.path.points.coordinates.map(this._toPosition)}/>);
            from_start = (<Polyline
                strokeColor="#999"
                path={[this.state.route.beg_coord, this.state.route.path.points.coordinates[0]].map(this._toPosition)}/>);
            to_finish = (<Polyline
                strokeColor="#999"
                path={[this.state.route.dest_coord, this.state.route.path.points.coordinates.slice(-1)[0]].map(this._toPosition)}/>);
        }
        var overlay =
            (
                <OverlayView
                    className="myOverlay"
                    mapPane="floatPane"
                    position={Constants.WarsawPosition()}>

Title

                </OverlayView>
            );
        var preloader = !this.state.loading ? null : (

        );
        return (

                {preloader}
                <Map zoom={this.state.zoom}
                     onZoomChange={this._handleZoomChange}
                     center={this.state.center}
                     onCenterChange={this._handleCenterChange}
                     width={window.innerWidth}
                     height={window.innerHeight}>
                    {this.state.route.stations === undefined ?
                        null :
                        this.state.route.stations.map(this._renderMarker)}
                    {this.state.beg_coord ? this._renderCustomMarker('beg_coord', 'start.png') : null}
                    {this.state.dest_coord ? this._renderCustomMarker('dest_coord', 'finish.png') : null}
                    {location_circle}
                    {route}
                    {from_start}
                    {to_finish}
                </Map>

        );
    }
    ,
    _handlePathStoreChange: function () {
        this.setState(function (previousState, currentProps) {
            var state = PathStore.getState();
            if (previousState.location.coords === undefined && state.location.coords !== undefined) {
                var center = new LatLng(state.location.coords.latitude, state.location.coords.longitude);
                var radius = state.location.coords.accuracy / 500;
                var bound = this._getMapBound([new LatLng(center.A - radius, center.F - radius),
                    new LatLng(center.A + radius, center.F + radius)]);
            } else if (previousState.route.stations === undefined && state.route.stations !== undefined) {
                bound = this._getMapBound(state.route.stations.map((station)=>station.location));
            }
            if (bound !== undefined) {
                state.zoom = bound.zoom;
                state.center = bound.center;
            }
            return state;
        });
        this.setState(PathStore.getState());
    }
    ,
    _getMapBound: function (points) {
        var min_x = Infinity,
            max_x = -Infinity,
            min_y = Infinity,
            max_y = -Infinity;
        points.map(function (item, i) {
            if (item.A !== undefined) {
                min_x = Math.min(min_x, item.A);
                max_x = Math.max(max_x, item.A);
                min_y = Math.min(min_y, item.F);
                max_y = Math.max(max_y, item.F);
            } else {
                min_x = Math.min(min_x, item[0]);
                max_x = Math.max(max_x, item[0]);
                min_y = Math.min(min_y, item[1]);
                max_y = Math.max(max_y, item[1]);
            }
        });
        var scale = Math.max(max_x - min_x, max_y - min_y);
        var zoom = Math.min((16 - Math.log(scale) / Math.log(2)), 12);
        var center = new LatLng((min_x + max_x) / 2, (min_y + max_y) / 2);
        return {zoom: zoom, center: center};
    }
    ,
    _handleCenterChange: function (map) {
        this.setState({
            center: map.getCenter()
        });
    }
    ,
    _handleZoomChange: function (map) {
        this.setState({
            zoom: map.getZoom()
        });
    }
    ,
    _renderMarker: function (state, i) {
        return (
            <Marker position={this._toPosition(state.location)}
                    key={i}
                    icon={'marker.png'}
                />
        );
    },
    _renderCustomMarker: function (stateVar, icon_path) {
        const location = this.state[stateVar];
        return (
            <Marker position={this._toPosition(location)}
                    icon={icon_path}
                    onDrag={this._handleDrag.bind(this, stateVar)}
                    onDragEnd={this._onLocationsUpdated}
                    draggable={true}
                />
        );
    },
    _handleDrag: function(stateVar, event) {
        var update = {};
        update[stateVar] = event.latLng;
        this.setState(update);
    },
    _onLocationsUpdated: function() {
      if(this.props.onUpdate) {
        this.props.onUpdate({
          start: this._toPosition(this.state.beg_coord),
          finish: this._toPosition(this.state.dest_coord)
        });
      }
    },
    _toPosition: function (pos) {
        if(!pos) return null;
        if (pos.F !== undefined) {
            var res = new LatLng(pos.A, pos.F);
        } else if (pos.lat !== undefined) {
            var res = new LatLng(pos.lat, pos.lng);
        } else {
            res = new LatLng(Math.max(pos[0], pos[1]), Math.min(pos[0], pos[1]));
        }
        return res;
    }
});
export default Path;
<commit_msg>Remove cebula marker<commit_after>var React = require('react/addons');
var ReactGoogleMaps = require('react-googlemaps');
var GoogleMapsAPI = window.google.maps;
var {Map,Marker, Polyline, Circle, OverlayView} = ReactGoogleMaps;
var LatLng = GoogleMapsAPI.LatLng;
import Constants from '../constants/Main.js'
import PathStore from '../stores/PathStore.js'
import assign from 'react/lib/Object.assign';

var Path = React.createClass({
    getInitialState: function () {
        return assign({}, {
            center: Constants.WarsawPosition(),
            zoom: 11
        }, PathStore.getState());
    },
    componentDidMount: function () {
        PathStore.onChange(this._handlePathStoreChange)
    },
    componentWillUnmount: function () {
        PathStore.off(this._handlePathStoreChange)
    },
    componentWillReceiveProps: function(nextProps) {
        this.setState({
            beg_coord: this._toPosition(nextProps.beginCoord),
            dest_coord: this._toPosition(nextProps.destCoord)
        });
    },
    render: function () {
        var location_circle = this.state.location.coords === undefined ? null : <Circle
            strokeColor="#64b5f6"
            fillColor="#64b5f6"
            center={new LatLng(this.state.location.coords.latitude, this.state.location.coords.longitude)}
            radius={this.state.location.coords.accuracy}/>;
        if (this.state.route.path === undefined || this.state.route.path.points === null) {
            var route = null;
            if (this.state.route.beg_coord && this.state.route.dest_coord) {
                var from_start = (<Polyline
                    strokeColor="#999"
                    path={[this.state.route.beg_coord, this.state.route.dest_coord].map(this._toPosition)}/>);
            } else {
                from_start = null;
            }
            var to_finish = null;
        } else {
            route = (<Polyline
                strokeColor="#000"
                path={this.state.route.path.points.coordinates.map(this._toPosition)}/>);
            from_start = (<Polyline
                strokeColor="#999"
                path={[this.state.route.beg_coord, this.state.route.path.points.coordinates[0]].map(this._toPosition)}/>);
            to_finish = (<Polyline
                strokeColor="#999"
                path={[this.state.route.dest_coord, this.state.route.path.points.coordinates.slice(-1)[0]].map(this._toPosition)}/>);
        }
        var overlay =
            (
                <OverlayView
                    className="myOverlay"
                    mapPane="floatPane"
                    position={Constants.WarsawPosition()}>

Title

                </OverlayView>
            );
        var preloader = !this.state.loading ? null : (

        );
        return (

                {preloader}
                <Map zoom={this.state.zoom}
                     onZoomChange={this._handleZoomChange}
                     center={this.state.center}
                     onCenterChange={this._handleCenterChange}
                     width={window.innerWidth}
                     height={window.innerHeight}>
                    {this.state.route.stations === undefined ?
                        null :
                        this.state.route.stations.map(this._renderMarker)}
                    {this.state.beg_coord ? this._renderCustomMarker('beg_coord', 'start.png') : null}
                    {this.state.dest_coord ? this._renderCustomMarker('dest_coord', 'finish.png') : null}
                    {location_circle}
                    {route}
                    {from_start}
                    {to_finish}
                </Map>

        );
    }
    ,
    _handlePathStoreChange: function () {
        this.setState(function (previousState, currentProps) {
            var state = PathStore.getState();
            if (previousState.location.coords === undefined && state.location.coords !== undefined) {
                var center = new LatLng(state.location.coords.latitude, state.location.coords.longitude);
                var radius = state.location.coords.accuracy / 500;
                var bound = this._getMapBound([new LatLng(center.A - radius, center.F - radius),
                    new LatLng(center.A + radius, center.F + radius)]);
            } else if (previousState.route.stations === undefined && state.route.stations !== undefined) {
                bound = this._getMapBound(state.route.stations.map((station)=>station.location));
            }
            if (bound !== undefined) {
                state.zoom = bound.zoom;
                state.center = bound.center;
            }
            return state;
        });
        this.setState(PathStore.getState());
    }
    ,
    _getMapBound: function (points) {
        var min_x = Infinity,
            max_x = -Infinity,
            min_y = Infinity,
            max_y = -Infinity;
        points.map(function (item, i) {
            if (item.A !== undefined) {
                min_x = Math.min(min_x, item.A);
                max_x = Math.max(max_x, item.A);
                min_y = Math.min(min_y, item.F);
                max_y = Math.max(max_y, item.F);
            } else {
                min_x = Math.min(min_x, item[0]);
                max_x = Math.max(max_x, item[0]);
                min_y = Math.min(min_y, item[1]);
                max_y = Math.max(max_y, item[1]);
            }
        });
        var scale = Math.max(max_x - min_x, max_y - min_y);
        var zoom = Math.min((16 - Math.log(scale) / Math.log(2)), 12);
        var center = new LatLng((min_x + max_x) / 2, (min_y + max_y) / 2);
        return {zoom: zoom, center: center};
    }
    ,
    _handleCenterChange: function (map) {
        this.setState({
            center: map.getCenter()
        });
    }
    ,
    _handleZoomChange: function (map) {
        this.setState({
            zoom: map.getZoom()
        });
    }
    ,
    _renderMarker: function (state, i) {
        return (
            <Marker position={this._toPosition(state.location)}
                    key={i}
                />
        );
    },
    _renderCustomMarker: function (stateVar, icon_path) {
        const location = this.state[stateVar];
        return (
            <Marker position={this._toPosition(location)}
                    icon={icon_path}
                    onDrag={this._handleDrag.bind(this, stateVar)}
                    onDragEnd={this._onLocationsUpdated}
                    draggable={true}
                />
        );
    },
    _handleDrag: function(stateVar, event) {
        var update = {};
        update[stateVar] = event.latLng;
        this.setState(update);
    },
    _onLocationsUpdated: function() {
      if(this.props.onUpdate) {
        this.props.onUpdate({
          start: this._toPosition(this.state.beg_coord),
          finish: this._toPosition(this.state.dest_coord)
        });
      }
    },
    _toPosition: function (pos) {
        if(!pos) return null;
        if (pos.F !== undefined) {
            var res = new LatLng(pos.A, pos.F);
        } else if (pos.lat !== undefined) {
            var res = new LatLng(pos.lat, pos.lng);
        } else {
            res = new LatLng(Math.max(pos[0], pos[1]), Math.min(pos[0], pos[1]));
        }
        return res;
    }
});
export default Path;
<|endoftext|>


<commit_before>/***
  This will reset the preferences that are under sections 4600 & 4700 in the
  arkenfox user.js. These are the prefs that are no longer necessary, or they
  conflict with, privacy.resistFingerprinting if you have that enabled.

  Final update: 10-August-2021

  As of v91, section 4600 is no longer recommended, and is all inactive. This
  now includes the old 4700 section. You can reset them using prefsCleaner.

  For instructions see:
  https://github.com/arkenfox/user.js/wiki/3.1-Resetting-Inactive-Prefs-[Scripts]
***/

(() => {

  if ('undefined' === typeof(Services)) return alert('about:config needs to be the active tab!');

  const aPREFS = [
    /* section 4600 */
    'dom.maxHardwareConcurrency',
    'dom.enable_resource_timing',
    'dom.enable_performance',
    'device.sensors.enabled',
    'browser.zoom.siteSpecific',
    'dom.gamepad.enabled',
    'dom.netinfo.enabled',
    'media.webspeech.synth.enabled',
    'media.video_stats.enabled',
    'dom.w3c_touch_events.enabled',
    'media.navigator.enabled',
    'media.ondevicechange.enabled',
    'webgl.enable-debug-renderer-info',
    'ui.prefersReducedMotion',
    'dom.w3c_pointer_events.enabled', // deprecated FF87
    'ui.use_standins_for_native_colors',
    'ui.systemUsesDarkTheme',
    'dom.webaudio.enabled',
    'layout.css.font-visibility.level',
    /* section 4700 */
    'general.appname.override',
    'general.appversion.override',
    'general.buildID.override',
    'general.oscpu.override',
    'general.platform.override',
    'general.useragent.override',
    /* reset parrot: check your open about:config after running the script */
    '_user.js.parrot'
  ];

  console.clear();

  let c = 0;
  for (const sPname of aPREFS) {
    if (Services.prefs.prefHasUserValue(sPname)) {
      Services.prefs.clearUserPref(sPname);
      if (!Services.prefs.prefHasUserValue(sPname)) {
        console.info('reset', sPname);
        c++;
      } else console.warn('failed to reset', sPname);
    }
  }

  focus();

  const d = (c==1) ? ' pref' : ' prefs';
  alert(c ? 'successfully reset ' + c + d + "\n\nfor details check the console" : 'nothing to reset');

  return 'all done';

})();
<commit_msg>Delete arkenfox-clear-RFP-alternatives.js<commit_after><|endoftext|>


<commit_before>define([
    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/on',
    'dojo/dom',
    'dojo/_base/array',
    'dojo/Deferred',

    'esri/map',

    'esri/IdentityManager'

], function (
    declare,
    lang,
    on,
    dom,
    array,
    Deferred,

    Map
) {
    'use strict';
    return declare(null, {

        initMapAsync: function () {
            var returnDeferred = new Deferred();
            var returnWarnings = [];

            var container = dom.byId(this.config.layout.map) || 'mapCenter';
            this.map = new Map(container, this.config.mapOptions);

            if (this.config.mapOptions.basemap) {
                this.map.on('load', lang.hitch(this, '_initLayers', returnWarnings));
            } else {
                this._initLayers(returnWarnings);
            }

            if (this.config.operationalLayers && this.config.operationalLayers.length > 0) {
                on.once(this.map, 'layers-add-result', lang.hitch(this, '_onLayersAddResult', returnDeferred, returnWarnings));
            } else {
                returnDeferred.resolve(returnWarnings);
            }
            return returnDeferred;
        },

        _onLayersAddResult: function (returnDeferred, returnWarnings, lyrsResult) {
            array.forEach(lyrsResult.layers, function (addedLayer) {
                if (addedLayer.success !== true) {
                    returnWarnings.push(addedLayer.error);
                }
            }, this);
            returnDeferred.resolve(returnWarnings);
        },

        _initLayers: function (returnWarnings) {
            this.layers = [];
            var layerTypes = {
                csv: 'CSV',
                dataadapter: 'DataAdapterFeature', //untested
                dynamic: 'ArcGISDynamicMapService',
                feature: 'Feature',
                georss: 'GeoRSS',
                image: 'ArcGISImageService',
                imagevector: 'ArcGISImageServiceVector',
                kml: 'KML',
                label: 'Label', //untested
                mapimage: 'MapImage', //untested
                osm: 'OpenStreetMap',
                raster: 'Raster',
                stream: 'Stream',
                tiled: 'ArcGISTiledMapService',
                vectortile: 'VectorTile',
                webtiled: 'WebTiled',
                wms: 'WMS',
                wmts: 'WMTS' //untested
            };
            // loading all the required modules first ensures the layer order is maintained
            var modules = [];
            array.forEach(this.config.operationalLayers, function (layer) {
                var type = layerTypes[layer.type];
                if (type) {
                    modules.push('esri/layers/' + type + 'Layer');
                } else {
                    returnWarnings.push('Layer type "' + layer.type + '"" isnot supported: ');
                }
            }, this);

            require(modules, lang.hitch(this, function () {
                array.forEach(this.config.operationalLayers, function (layer) {
                    var type = layerTypes[layer.type];
                    if (type) {
                        require(['esri/layers/' + type + 'Layer'], lang.hitch(this, '_initLayer', layer));
                    }
                }, this);
                this.map.addLayers(this.layers);
            }));
        },

        _initLayer: function (layer, Layer) {
            var l;
            if (layer.url) {
                l = new Layer(layer.url, layer.options);
            } else {
                l = new Layer(layer.options);
            }
            this.layers.unshift(l); //unshift instead of push to keep layer ordering on map intact

            //Legend LayerInfos array
            var excludeLayerFromLegend = false;
            if (typeof layer.legendLayerInfos !== 'undefined' && typeof layer.legendLayerInfos.exclude !== 'undefined') {
                excludeLayerFromLegend = layer.legendLayerInfos.exclude;
            }
            if (!excludeLayerFromLegend) {
                var configuredLayerInfo = {};
                if (typeof layer.legendLayerInfos !== 'undefined' && typeof layer.legendLayerInfos.layerInfo !== 'undefined') {
                    configuredLayerInfo = layer.legendLayerInfos.layerInfo;
                }
                var layerInfo = lang.mixin({
                    layer: l,
                    title: layer.title || null
                }, configuredLayerInfo);
                this.legendLayerInfos.unshift(layerInfo); //unshift instead of push to keep layer ordering in legend intact
            }

            //LayerControl LayerInfos array
            this.layerControlLayerInfos.unshift({ //unshift instead of push to keep layer ordering in LayerControl intact
                layer: l,
                type: layer.type,
                title: layer.title,
                controlOptions: layer.layerControlLayerInfos
            });

            if (layer.type === 'feature') {
                var options = {
                    featureLayer: l
                };
                if (layer.editorLayerInfos) {
                    lang.mixin(options, layer.editorLayerInfos);
                }
                if (options.exclude !== true) {
                    this.editorLayerInfos.push(options);
                }
            }

            if (layer.type === 'dynamic' || layer.type === 'feature') {
                var idOptions = {
                    layer: l,
                    title: layer.title
                };
                if (layer.identifyLayerInfos) {
                    lang.mixin(idOptions, layer.identifyLayerInfos);
                }
                if (idOptions.exclude !== true) {
                    this.identifyLayerInfos.push(idOptions);
                }
            }
        },

        initMapComplete: function (warnings) {
            if (warnings && warnings.length > 0) {
                this.handleError({
                    source: 'Controller',
                    error: warnings.join(', ')
                });
            }

            this.map.on('resize', function (evt) {
                var pnt = evt.target.extent.getCenter();
                setTimeout(function () {
                    evt.target.centerAt(pnt);
                }, 100);
            });

            // in _LayoutsMixin
            this.resizeLayout();

            // in _WidgetsMixin
            this.initWidgets();
        },

        initMapError: function (err) {
            this.handleError({
                source: 'Controller',
                error: err
            });
        },

        resizeMap: function () {
            if (this.map) {
                this.map.resize();
            }
        },

        getMapHeight: function () {
            if (this.map) {
                return this.map.height;
            } else {
                return 0;
            }
        }
    });
});<commit_msg>Add new `_createMap` method to allow custom mixins to override the method. This is useful when using CMV with BootstrapMap (https://github.com/Esri/bootstrap-map-js).<commit_after>define([
    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/on',
    'dojo/dom',
    'dojo/_base/array',
    'dojo/Deferred',

    'esri/map',

    'esri/IdentityManager'

], function (
    declare,
    lang,
    on,
    dom,
    array,
    Deferred,

    Map
) {
    'use strict';
    return declare(null, {

        initMapAsync: function () {
            var returnDeferred = new Deferred();
            var returnWarnings = [];

            this._createMap();

            if (this.config.mapOptions.basemap) {
                this.map.on('load', lang.hitch(this, '_initLayers', returnWarnings));
            } else {
                this._initLayers(returnWarnings);
            }

            if (this.config.operationalLayers && this.config.operationalLayers.length > 0) {
                on.once(this.map, 'layers-add-result', lang.hitch(this, '_onLayersAddResult', returnDeferred, returnWarnings));
            } else {
                returnDeferred.resolve(returnWarnings);
            }
            return returnDeferred;
        },

        _createMap: function () {
            var container = dom.byId(this.config.layout.map) || 'mapCenter';
            this.map = new Map(container, this.config.mapOptions);
        },

        _onLayersAddResult: function (returnDeferred, returnWarnings, lyrsResult) {
            array.forEach(lyrsResult.layers, function (addedLayer) {
                if (addedLayer.success !== true) {
                    returnWarnings.push(addedLayer.error);
                }
            }, this);
            returnDeferred.resolve(returnWarnings);
        },

        _initLayers: function (returnWarnings) {
            this.layers = [];
            var layerTypes = {
                csv: 'CSV',
                dataadapter: 'DataAdapterFeature', //untested
                dynamic: 'ArcGISDynamicMapService',
                feature: 'Feature',
                georss: 'GeoRSS',
                image: 'ArcGISImageService',
                imagevector: 'ArcGISImageServiceVector',
                kml: 'KML',
                label: 'Label', //untested
                mapimage: 'MapImage', //untested
                osm: 'OpenStreetMap',
                raster: 'Raster',
                stream: 'Stream',
                tiled: 'ArcGISTiledMapService',
                vectortile: 'VectorTile',
                webtiled: 'WebTiled',
                wms: 'WMS',
                wmts: 'WMTS' //untested
            };
            // loading all the required modules first ensures the layer order is maintained
            var modules = [];
            array.forEach(this.config.operationalLayers, function (layer) {
                var type = layerTypes[layer.type];
                if (type) {
                    modules.push('esri/layers/' + type + 'Layer');
                } else {
                    returnWarnings.push('Layer type "' + layer.type + '"" isnot supported: ');
                }
            }, this);

            require(modules, lang.hitch(this, function () {
                array.forEach(this.config.operationalLayers, function (layer) {
                    var type = layerTypes[layer.type];
                    if (type) {
                        require(['esri/layers/' + type + 'Layer'], lang.hitch(this, '_initLayer', layer));
                    }
                }, this);
                this.map.addLayers(this.layers);
            }));
        },

        _initLayer: function (layer, Layer) {
            var l;
            if (layer.url) {
                l = new Layer(layer.url, layer.options);
            } else {
                l = new Layer(layer.options);
            }
            this.layers.unshift(l); //unshift instead of push to keep layer ordering on map intact

            //Legend LayerInfos array
            var excludeLayerFromLegend = false;
            if (typeof layer.legendLayerInfos !== 'undefined' && typeof layer.legendLayerInfos.exclude !== 'undefined') {
                excludeLayerFromLegend = layer.legendLayerInfos.exclude;
            }
            if (!excludeLayerFromLegend) {
                var configuredLayerInfo = {};
                if (typeof layer.legendLayerInfos !== 'undefined' && typeof layer.legendLayerInfos.layerInfo !== 'undefined') {
                    configuredLayerInfo = layer.legendLayerInfos.layerInfo;
                }
                var layerInfo = lang.mixin({
                    layer: l,
                    title: layer.title || null
                }, configuredLayerInfo);
                this.legendLayerInfos.unshift(layerInfo); //unshift instead of push to keep layer ordering in legend intact
            }

            //LayerControl LayerInfos array
            this.layerControlLayerInfos.unshift({ //unshift instead of push to keep layer ordering in LayerControl intact
                layer: l,
                type: layer.type,
                title: layer.title,
                controlOptions: layer.layerControlLayerInfos
            });

            if (layer.type === 'feature') {
                var options = {
                    featureLayer: l
                };
                if (layer.editorLayerInfos) {
                    lang.mixin(options, layer.editorLayerInfos);
                }
                if (options.exclude !== true) {
                    this.editorLayerInfos.push(options);
                }
            }

            if (layer.type === 'dynamic' || layer.type === 'feature') {
                var idOptions = {
                    layer: l,
                    title: layer.title
                };
                if (layer.identifyLayerInfos) {
                    lang.mixin(idOptions, layer.identifyLayerInfos);
                }
                if (idOptions.exclude !== true) {
                    this.identifyLayerInfos.push(idOptions);
                }
            }
        },

        initMapComplete: function (warnings) {
            if (warnings && warnings.length > 0) {
                this.handleError({
                    source: 'Controller',
                    error: warnings.join(', ')
                });
            }

            this.map.on('resize', function (evt) {
                var pnt = evt.target.extent.getCenter();
                setTimeout(function () {
                    evt.target.centerAt(pnt);
                }, 100);
            });

            // in _LayoutsMixin
            this.resizeLayout();

            // in _WidgetsMixin
            this.initWidgets();
        },

        initMapError: function (err) {
            this.handleError({
                source: 'Controller',
                error: err
            });
        },

        resizeMap: function () {
            if (this.map) {
                this.map.resize();
            }
        },

        getMapHeight: function () {
            if (this.map) {
                return this.map.height;
            } else {
                return 0;
            }
        }
    });
});<|endoftext|>


<commit_before>

var wwd = new WorldWind.WorldWindow("canvasOne");
wwd.addLayer(new WorldWind.BMNGOneImageLayer());
wwd.addLayer(new WorldWind.BingAerialLayer());
wwd.addLayer(new WorldWind.CompassLayer());
wwd.addLayer(new WorldWind.CoordinatesDisplayLayer(wwd));
wwd.addLayer(new WorldWind.ViewControlsLayer(wwd));

<!--add placemark layer-->
var placemarkLayer = new WorldWind.RenderableLayer("Placemark Layer");
wwd.addLayer(placemarkLayer);

var placemarkAttributes = new WorldWind.PlacemarkAttributes(null);

placemarkAttributes.imageOffset = new WorldWind.Offset(
		WorldWind.OFFSET_FRACTION, 0.5,
		WorldWind.OFFSET_FRACTION, 0.5);

placemarkAttributes.labelAttributes.color = WorldWind.Color.YELLOW;
placemarkAttributes.labelAttributes.offset = new WorldWind.Offset(
		WorldWind.OFFSET_FRACTION, 0.5,
		WorldWind.OFFSET_FRACTION, 1.5);

placemarkAttributes.imageSource = WorldWind.configuration.baseUrl + "images/crosshair.png"; //pushpins/plain-red.png";
var placemark = new WorldWind.Placemark(new WorldWind.Position(-30, -54, 1.0), false, placemarkAttributes);
wwd.navigator.range = 300.0;//(1 - thisLayer.zoomIncrement);
wwd.redraw();

function showPosition(position) {
	let lat = position.coords.latitude;
	let lon = position.coords.longitude;
	let acu = position.coords.accuracy;

	let altitude = position.coords.altitude;

	let altitudeAccuracy = position.coords.altitudeAccuracy;
	let heading = position.coords.heading;
	let speed = position.coords.speed;
	let timestamp = position.coords.timestamp;

	var position = new WorldWind.Position(lat, lon, 0.0);
	placemark.position=position;

	placemark.label = "Ud esta aqui!\n" +
	"Lat " + placemark.position.latitude.toPrecision(4).toString() + "\n" +
	"Lon " + placemark.position.longitude.toPrecision(5).toString();
	placemark.alwaysOnTop = true;
	placemarkLayer.addRenderable(placemark);

	//wwd.goTo(new WorldWind.Position(lat,lon,100));
	wwd.navigator.lookAtLocation.latitude=position.latitude;
	wwd.navigator.lookAtLocation.longitude=position.longitude;
	//this.wwd.navigator.range);
	wwd.redraw();

}

if (navigator.geolocation) {
	//  alert("getting location");

	navigator.geolocation.watchPosition(showPosition);

} else {
	alert("Geolocation is not supported by this browser.");
	// x.innerHTML = "Geolocation is not supported by this browser.";
}

<!-- fin de placemarks-->

<!-- 3d shapes-->

var polygonLayer = new WorldWind.RenderableLayer();
wwd.addLayer(polygonLayer);

var polygonAttributes = new WorldWind.ShapeAttributes(null);
polygonAttributes.interiorColor = new WorldWind.Color(0, 1, 1, 0.75);
polygonAttributes.outlineColor = WorldWind.Color.BLUE;
polygonAttributes.drawOutline = true;
polygonAttributes.applyLighting = true;

var boundaries = [];
boundaries.push(new WorldWind.Position(20.0, -75.0, 700000.0));
boundaries.push(new WorldWind.Position(25.0, -85.0, 700000.0));
boundaries.push(new WorldWind.Position(20.0, -95.0, 700000.0));

var polygon = new WorldWind.Polygon(boundaries, polygonAttributes);
polygon.extrude = true;
polygonLayer.addRenderable(polygon);

/*    var serviceAddress = "https://neo.sci.gsfc.nasa.gov/wms/wms?SERVICE=WMS&REQUEST=GetCapabilities&VERSION=1.3.0";
    var layerName = "MOD_LSTD_CLIM_M";
    var createLayer = function (xmlDom) {
	    var wms = new WorldWind.WmsCapabilities(xmlDom);
	    var wmsLayerCapabilities = wms.getNamedLayer(layerName);
	    var wmsConfig = WorldWind.WmsLayer.formLayerConfiguration(wmsLayerCapabilities);
	    var wmsLayer = new WorldWind.WmsLayer(wmsConfig);
	    wwd.addLayer(wmsLayer);
		};

	var logError = function (jqXhr, text, exception) {
	    console.log("There was a failure retrieving the capabilities document: " +
	        text +
	    " exception: " + exception);
	};

	<!-- call jquery serviceAdress y createLayer on success-->
	$.get(serviceAddress).done(createLayer).fail(logError);
 */

function requestPoligons(){
	const API_URL="https://www.ursulagis.com/last_poligon";
	const xhr = new XMLHttpReqyest();

	function onResponse(){
		if(this.readyState===4 && this.status === 200){
			const data = JSON.parse(this.response)
			console.log(data);
		}
	}
	xhr.addEventListener('load',onResponse);
	xhr.open("GET",API_URL);
	xhr.send();
}<commit_msg>requests query 1<commit_after>

var wwd = new WorldWind.WorldWindow("canvasOne");
wwd.addLayer(new WorldWind.BMNGOneImageLayer());
wwd.addLayer(new WorldWind.BingAerialLayer());
wwd.addLayer(new WorldWind.CompassLayer());
wwd.addLayer(new WorldWind.CoordinatesDisplayLayer(wwd));
wwd.addLayer(new WorldWind.ViewControlsLayer(wwd));

<!--add placemark layer-->
var placemarkLayer = new WorldWind.RenderableLayer("Placemark Layer");
wwd.addLayer(placemarkLayer);

var placemarkAttributes = new WorldWind.PlacemarkAttributes(null);

placemarkAttributes.imageOffset = new WorldWind.Offset(
		WorldWind.OFFSET_FRACTION, 0.5,
		WorldWind.OFFSET_FRACTION, 0.5);

placemarkAttributes.labelAttributes.color = WorldWind.Color.YELLOW;
placemarkAttributes.labelAttributes.offset = new WorldWind.Offset(
		WorldWind.OFFSET_FRACTION, 0.5,
		WorldWind.OFFSET_FRACTION, 1.5);

placemarkAttributes.imageSource = WorldWind.configuration.baseUrl + "images/crosshair.png"; //pushpins/plain-red.png";
var placemark = new WorldWind.Placemark(new WorldWind.Position(-30, -54, 1.0), false, placemarkAttributes);
wwd.navigator.range = 300.0;//(1 - thisLayer.zoomIncrement);
wwd.redraw();

function showPosition(position) {
	let lat = position.coords.latitude;
	let lon = position.coords.longitude;
	let acu = position.coords.accuracy;

	let altitude = position.coords.altitude;

	let altitudeAccuracy = position.coords.altitudeAccuracy;
	let heading = position.coords.heading;
	let speed = position.coords.speed;
	let timestamp = position.coords.timestamp;

	var position = new WorldWind.Position(lat, lon, 0.0);
	placemark.position=position;

	placemark.label = "Ud esta aqui!\n" +
	"Lat " + placemark.position.latitude.toPrecision(4).toString() + "\n" +
	"Lon " + placemark.position.longitude.toPrecision(5).toString();
	placemark.alwaysOnTop = true;
	placemarkLayer.addRenderable(placemark);

	//wwd.goTo(new WorldWind.Position(lat,lon,100));
	wwd.navigator.lookAtLocation.latitude=position.latitude;
	wwd.navigator.lookAtLocation.longitude=position.longitude;
	//this.wwd.navigator.range);
	wwd.redraw();

}

if (navigator.geolocation) {
	//  alert("getting location");

	navigator.geolocation.watchPosition(showPosition);

} else {
	alert("Geolocation is not supported by this browser.");
	// x.innerHTML = "Geolocation is not supported by this browser.";
}

<!-- fin de placemarks-->

<!-- 3d shapes-->

var polygonLayer = new WorldWind.RenderableLayer();
wwd.addLayer(polygonLayer);

var polygonAttributes = new WorldWind.ShapeAttributes(null);
polygonAttributes.interiorColor = new WorldWind.Color(0, 1, 1, 0.75);
polygonAttributes.outlineColor = WorldWind.Color.BLUE;
polygonAttributes.drawOutline = true;
polygonAttributes.applyLighting = true;

var boundaries = [];
boundaries.push(new WorldWind.Position(20.0, -75.0, 700000.0));
boundaries.push(new WorldWind.Position(25.0, -85.0, 700000.0));
boundaries.push(new WorldWind.Position(20.0, -95.0, 700000.0));

var polygon = new WorldWind.Polygon(boundaries, polygonAttributes);
polygon.extrude = true;
polygonLayer.addRenderable(polygon);

/*    var serviceAddress = "https://neo.sci.gsfc.nasa.gov/wms/wms?SERVICE=WMS&REQUEST=GetCapabilities&VERSION=1.3.0";
    var layerName = "MOD_LSTD_CLIM_M";
    var createLayer = function (xmlDom) {
	    var wms = new WorldWind.WmsCapabilities(xmlDom);
	    var wmsLayerCapabilities = wms.getNamedLayer(layerName);
	    var wmsConfig = WorldWind.WmsLayer.formLayerConfiguration(wmsLayerCapabilities);
	    var wmsLayer = new WorldWind.WmsLayer(wmsConfig);
	    wwd.addLayer(wmsLayer);
		};

	var logError = function (jqXhr, text, exception) {
	    console.log("There was a failure retrieving the capabilities document: " +
	        text +
	    " exception: " + exception);
	};

	<!-- call jquery serviceAdress y createLayer on success-->
	$.get(serviceAddress).done(createLayer).fail(logError);
 */

function requestPoligons(){
	const API_URL="https://www.ursulagis.com/last_poligon";
	const xhr = new XMLHttpReqyest();

	function onResponse(){
		if(this.readyState===4 && this.status === 200){
			const data = JSON.parse(this.response)
			console.log(data);
		}
	}
	xhr.addEventListener('load',onResponse);
	xhr.open("GET",API_URL);
	xhr.send();
}

const interval = setInterval(requestPoligons, 5000);

	//clearInterval(interval); // thanks @Luca D'Amico<|endoftext|>


<commit_before>var slideIndex;

$(document).ready(function(){
	$("#btn-right").click(function(){
		pic(1)
	});
	$("#btn-left").click(function(){
		pic(-1)});

	showPic(0);

	slideIndex = 1;
	showPic(slideIndex);

});

function pic(n){
	$('#current').parent().trigger('zoom.destroy');
	$('#current').unwrap();
	showPic(slideIndex += n);
}

function showPic(n){
	var i;
	var x = document.getElementsByClassName("images");
	if (n > x.length) {slideIndex = 1}
	if (n < 1) {slideIndex = x.length}
	for (i = 0; i < x.length; i++) {
		$(x[i]).css("display", "none");
		$(x[i]).removeAttr('id');
	}
	$(x[slideIndex-1]).css("display", "block");
	$(x[slideIndex-1]).attr("id", "current");
	$("#current")
		.wrap('')
	    .css('display', 'block')
	    .parent()
	    .zoom();
}

function getPrice()
{

    var startDate = $("#startVal").val();
    var endDate = $("#endVal").val();

    var msDay = 1000*60*60*24;

    var d1 = new Date(startDate);
    var d2 = new Date(endDate);

    var totalTime = Math.abs(d1-d2);
    //difference in milliseconds between two dates.

    totalTime = Number(totalTime);
    //converts date to stirng.

    totalTime = totalTime % msDay;

    var totalPrice = 20 * totalTime;

    $("#priceBox").val(totalPrice);

    //return 20 * totalTime;
    //calculates the price and returns.

}
<commit_msg>fixed bug/issue with getPrice<commit_after>var slideIndex;

$(document).ready(function(){
	$("#btn-right").click(function(){
		pic(1)
	});
	$("#btn-left").click(function(){
		pic(-1)});

	showPic(0);

	slideIndex = 1;
	showPic(slideIndex);

});

function pic(n){
	$('#current').parent().trigger('zoom.destroy');
	$('#current').unwrap();
	showPic(slideIndex += n);
}

function showPic(n){
	var i;
	var x = document.getElementsByClassName("images");
	if (n > x.length) {slideIndex = 1}
	if (n < 1) {slideIndex = x.length}
	for (i = 0; i < x.length; i++) {
		$(x[i]).css("display", "none");
		$(x[i]).removeAttr('id');
	}
	$(x[slideIndex-1]).css("display", "block");
	$(x[slideIndex-1]).attr("id", "current");
	$("#current")
		.wrap('')
	    .css('display', 'block')
	    .parent()
	    .zoom();
}

function getPrice()
{

    var startDate = $("#from").val();
    var endDate = $("#to").val();

    var msDay = 1000*60*60*24;

    var d1 = new Date(startDate);
    var d2 = new Date(endDate);

    var totalTime = Math.abs(d1-d2);
    //difference in milliseconds between two dates.

    totalTime = Number(totalTime);
    //converts date to stirng.

    totalTime = totalTime % msDay;

    var totalPrice = 20 * totalTime;

    $("#priceBox").val(totalPrice);

    //return 20 * totalTime;
    //calculates the price and returns.

}
<|endoftext|>


<commit_before>import md from 'components/md'

const TypeScript = () => md`
  ## TypeScript

  styled-components has TypeScript definitions to allow the library to be used in any TypeScript project.
  A basic example can be found [here](https://github.com/patrick91/Styled-Components-Typescript-Example).

  Before you can effectively start to use TypeScript you will have to do a little bit of configuration.

  ### Define a theme interface

  By default every styled component will have the \`theme\` prop set to \`any\`.
  When building complex apps it would be better to have autocomplete and error checks everywhere.

  To have autocomplete and checks around the \`theme\` prop we should first define the theme
  interface we would like to use throughout our app:

  \`\`\`jsx
  // theme.ts
  export default interface ThemeInterface {
    primaryColor: string;
    primaryColorInverted: string;
  }
  \`\`\`

  Then we can re-export the \`styled\` function with our custom theme interface:

  \`\`\`jsx
  // styled-components.ts
  import * as styledComponents from 'styled-components';
  import { ThemedStyledComponentsModule } from 'styled-components';

  import ThemeInterface from './theme';

  const {
    default: styled,
    css,
    injectGlobal,
    keyframes,
    ThemeProvider
  } = styledComponents as ThemedStyledComponentsModule<ThemeInterface>;

  export { css, injectGlobal, keyframes, ThemeProvider };
  export default styled;
  \`\`\`

  ### Styling components
  Finally, instead of importing the styled functions from the styled-components module,
  we import it from our above, custom module.

  \`\`\`jsx
  import styled from 'app/styled-components'

  // theme is now fully typed
  const Title = styled.h1\`
    color: props => props.theme.primaryColor
  \`
  \`\`\`

  If you are passing custom properties to your styled component it is a good idea to follow this convention:

  \`\`\`jsx
  import styled from 'app/styled-components'

  // theme is now fully typed
  const Title = styled<{ isActive: boolean }, 'h1'>('h1')\`
    color: props => props.isActive ? props.theme.primaryColor : props.theme.secondaryColor
  \`
  \`\`\`

  You will need to define both the custom props and the type of tag which will be used. When you pass a custom component,
  the type of tag is not required.

  \`\`\`jsx
  import styled from 'app/styled-components'
  import Header from './Header'

  const Title = styled<{ isActive: boolean }>(Header)\`
    color: props => props.isActive ? props.theme.primaryColor : props.theme.secondaryColor
  \`
  \`\`\`

  If the **isActive** property should not be passed into the **Header** component you will have to extract it using the
  following convention:

  \`\`\`jsx
  import styled from 'app/styled-components'
  import Header, { Props as HeaderProps } from './Header'

  const Title = styled<{ isActive: boolean }>(({ isActive, ...rest}) => )\`
    color: props => props.isActive ? props.theme.primaryColor : props.theme.secondaryColor
  \`
  \`\`\`

  But it might be the opposite. Maybe your styled component needs to proxy props required by the **Header**. Then
  you follow this convention:

  \`\`\`jsx
  import styled from 'app/styled-components'
  import Header, { Props as HeaderProps } from './Header'

  const Title = styled<{ isActive: boolean } & HeaderProps>(({ isActive, ...rest}) => )\`
    color: props => props.isActive ? props.theme.primaryColor : props.theme.secondaryColor
  \`
  \`\`\`

  This is the most complex example where we have specific properties for the styling of the component and pass
  the rest of the required properties by the **Header** through. That means when you use **Title** it will have
  the combined typing of both the styled requirements and the actual component requirements.

  ### Caveat with \`className\`

  When defining a component you will need to mark \`className\` as optional
  in your Props interface:

  \`\`\`jsx
  interface LogoProps {
    /* This prop is optional, since TypeScript won't know that it's passed by the wrapper */
    className?: string;
  }

  class Logo extends React.Component<LogoProps, {}> {
    render() {
      return (

          Logo

      );
    }
  }

  const LogoStyled = styled(Logo)\`
    font-family: 'Helvetica';
    font-weight: bold;
    font-size: 1.8rem;
  \`;
  \`\`\`

  ### Caveat with Stateless Components

  To use stateless components and have typechecking for the props you'll need to define
  the component alongside with its type. This is not special to styled-components, this is just
  how React works:

  \`\`\`jsx
  interface BoxProps {
    theme?: ThemeInterface;
    borders?: boolean;
    className?: string;
  }

  const Box: React.SFC<BoxProps> = props => (

      {props.children}

  );

  const StyledBox = styled(Box)\`
    padding: \${props => props.theme.lateralPadding};
  \`;
  \`\`\`
`

export default TypeScript
<commit_msg>TypeScript API documentation: Fix interpolations missing ${ }.<commit_after>import md from 'components/md'

const TypeScript = () => md`
  ## TypeScript

  styled-components has TypeScript definitions to allow the library to be used in any TypeScript project.
  A basic example can be found [here](https://github.com/patrick91/Styled-Components-Typescript-Example).

  Before you can effectively start to use TypeScript you will have to do a little bit of configuration.

  ### Define a theme interface

  By default every styled component will have the \`theme\` prop set to \`any\`.
  When building complex apps it would be better to have autocomplete and error checks everywhere.

  To have autocomplete and checks around the \`theme\` prop we should first define the theme
  interface we would like to use throughout our app:

  \`\`\`jsx
  // theme.ts
  export default interface ThemeInterface {
    primaryColor: string;
    primaryColorInverted: string;
  }
  \`\`\`

  Then we can re-export the \`styled\` function with our custom theme interface:

  \`\`\`jsx
  // styled-components.ts
  import * as styledComponents from 'styled-components';
  import { ThemedStyledComponentsModule } from 'styled-components';

  import ThemeInterface from './theme';

  const {
    default: styled,
    css,
    injectGlobal,
    keyframes,
    ThemeProvider
  } = styledComponents as ThemedStyledComponentsModule<ThemeInterface>;

  export { css, injectGlobal, keyframes, ThemeProvider };
  export default styled;
  \`\`\`

  ### Styling components
  Finally, instead of importing the styled functions from the styled-components module,
  we import it from our above, custom module.

  \`\`\`jsx
  import styled from 'app/styled-components'

  // theme is now fully typed
  const Title = styled.h1\`
    color: \${props => props.theme.primaryColor}
  \`
  \`\`\`

  If you are passing custom properties to your styled component it is a good idea to follow this convention:

  \`\`\`jsx
  import styled from 'app/styled-components'

  // theme is now fully typed
  const Title = styled<{ isActive: boolean }, 'h1'>('h1')\`
    color: \${props => props.isActive ? props.theme.primaryColor : props.theme.secondaryColor}
  \`
  \`\`\`

  You will need to define both the custom props and the type of tag which will be used. When you pass a custom component,
  the type of tag is not required.

  \`\`\`jsx
  import styled from 'app/styled-components'
  import Header from './Header'

  const Title = styled<{ isActive: boolean }>(Header)\`
    color: \${props => props.isActive ? props.theme.primaryColor : props.theme.secondaryColor}
  \`
  \`\`\`

  If the **isActive** property should not be passed into the **Header** component you will have to extract it using the
  following convention:

  \`\`\`jsx
  import styled from 'app/styled-components'
  import Header, { Props as HeaderProps } from './Header'

  const Title = styled<{ isActive: boolean }>(({ isActive, ...rest}) => )\`
    color: \${props => props.isActive ? props.theme.primaryColor : props.theme.secondaryColor}
  \`
  \`\`\`

  But it might be the opposite. Maybe your styled component needs to proxy props required by the **Header**. Then
  you follow this convention:

  \`\`\`jsx
  import styled from 'app/styled-components'
  import Header, { Props as HeaderProps } from './Header'

  const Title = styled<{ isActive: boolean } & HeaderProps>(({ isActive, ...rest}) => )\`
    color: \${props => props.isActive ? props.theme.primaryColor : props.theme.secondaryColor}
  \`
  \`\`\`

  This is the most complex example where we have specific properties for the styling of the component and pass
  the rest of the required properties by the **Header** through. That means when you use **Title** it will have
  the combined typing of both the styled requirements and the actual component requirements.

  ### Caveat with \`className\`

  When defining a component you will need to mark \`className\` as optional
  in your Props interface:

  \`\`\`jsx
  interface LogoProps {
    /* This prop is optional, since TypeScript won't know that it's passed by the wrapper */
    className?: string;
  }

  class Logo extends React.Component<LogoProps, {}> {
    render() {
      return (

          Logo

      );
    }
  }

  const LogoStyled = styled(Logo)\`
    font-family: 'Helvetica';
    font-weight: bold;
    font-size: 1.8rem;
  \`;
  \`\`\`

  ### Caveat with Stateless Components

  To use stateless components and have typechecking for the props you'll need to define
  the component alongside with its type. This is not special to styled-components, this is just
  how React works:

  \`\`\`jsx
  interface BoxProps {
    theme?: ThemeInterface;
    borders?: boolean;
    className?: string;
  }

  const Box: React.SFC<BoxProps> = props => (

      {props.children}

  );

  const StyledBox = styled(Box)\`
    padding: \${props => props.theme.lateralPadding};
  \`;
  \`\`\`
`

export default TypeScript
<|endoftext|>