<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Patrick Gansterer <paroga@paroga.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

(function(global, undefined) { "use strict";
var POW_2_24 = 5.960464477539063e-8,
    POW_2_32 = 4294967296,
    POW_2_53 = 9007199254740992;

function encode(value) {
  var data = new ArrayBuffer(256);
  var dataView = new DataView(data);
  var lastLength;
  var offset = 0;

  function ensureSpace(length) {
    var newByteLength = data.byteLength;
    var requiredLength = offset + length;
    while (newByteLength < requiredLength)
      newByteLength *= 2;
    if (newByteLength !== data.byteLength) {
      var oldDataView = dataView;
      data = new ArrayBuffer(newByteLength);
      dataView = new DataView(data);
      var uint32count = (offset + 3) >> 2;
      for (var i = 0; i < uint32count; ++i)
        dataView.setUint32(i * 4, oldDataView.getUint32(i * 4));
    }

    lastLength = length;
    return dataView;
  }
  function write() {
    offset += lastLength;
  }
  function writeFloat64(value) {
    write(ensureSpace(8).setFloat64(offset, value));
  }
  function writeUint8(value) {
    write(ensureSpace(1).setUint8(offset, value));
  }
  function writeUint8Array(value) {
    var dataView = ensureSpace(value.length);
    for (var i = 0; i < value.length; ++i)
      dataView.setUint8(offset + i, value[i]);
    write();
  }
  function writeUint16(value) {
    write(ensureSpace(2).setUint16(offset, value));
  }
  function writeUint32(value) {
    write(ensureSpace(4).setUint32(offset, value));
  }
  function writeUint64(value) {
    var low = value % POW_2_32;
    var high = (value - low) / POW_2_32;
    var dataView = ensureSpace(8);
    dataView.setUint32(offset, high);
    dataView.setUint32(offset + 4, low);
    write();
  }
  function writeTypeAndLength(type, length) {
    if (length < 24) {
      writeUint8(type << 5 | length);
    } else if (length < 0x100) {
      writeUint8(type << 5 | 24);
      writeUint8(length);
    } else if (length < 0x10000) {
      writeUint8(type << 5 | 25);
      writeUint16(length);
    } else if (length < 0x100000000) {
      writeUint8(type << 5 | 26);
      writeUint32(length);
    } else {
      writeUint8(type << 5 | 27);
      writeUint64(length);
    }
  }

  function encodeItem(value) {
    var i;

    if (value === false)
      return writeUint8(0xf4);
    if (value === true)
      return writeUint8(0xf5);
    if (value === null)
      return writeUint8(0xf6);
    if (value === undefined)
      return writeUint8(0xf7);

    switch (typeof value) {
      case "number":
        if (Math.floor(value) === value) {
          if (0 <= value && value <= POW_2_53)
            return writeTypeAndLength(0, value);
          if (-POW_2_53 <= value && value < 0)
            return writeTypeAndLength(1, -(value + 1));
        }
        writeUint8(0xfb);
        return writeFloat64(value);

      case "string":
        var utf8data = [];
        for (i = 0; i < value.length; ++i) {
          var charCode = value.charCodeAt(i);
          if (charCode < 0x80) {
            utf8data.push(charCode);
          } else if (charCode < 0x800) {
            utf8data.push(0xc0 | charCode >> 6);
            utf8data.push(0x80 | charCode & 0x3f);
          } else if (charCode < 0xd800) {
            utf8data.push(0xe0 | charCode >> 12);
            utf8data.push(0x80 | (charCode >> 6)  & 0x3f);
            utf8data.push(0x80 | charCode & 0x3f);
          } else {
            charCode = (charCode & 0x3ff) << 10;
            charCode |= value.charCodeAt(++i) & 0x3ff;
            charCode += 0x10000;

            utf8data.push(0xf0 | charCode >> 18);
            utf8data.push(0x80 | (charCode >> 12)  & 0x3f);
            utf8data.push(0x80 | (charCode >> 6)  & 0x3f);
            utf8data.push(0x80 | charCode & 0x3f);
          }
        }

        writeTypeAndLength(3, utf8data.length);
        return writeUint8Array(utf8data);

      default:
        var length;
        if (Array.isArray(value)) {
          length = value.length;
          writeTypeAndLength(4, length);
          for (i = 0; i < length; ++i)
            encodeItem(value[i]);
        } else if (value instanceof Uint8Array) {
          writeTypeAndLength(2, value.length);
          writeUint8Array(value);
        } else {
          var keys = Object.keys(value);
          length = keys.length;
          writeTypeAndLength(5, length);
          for (i = 0; i < length; ++i) {
            var key = keys[i];
            encodeItem(key);
            encodeItem(value[key]);
          }
        }
    }
  }

  encodeItem(value);

  if ("slice" in data)
    return data.slice(0, offset);

  var ret = new ArrayBuffer(offset);
  var retView = new DataView(ret);
  for (var i = 0; i < offset; ++i)
    retView.setUint8(i, dataView.getUint8(i));
  return ret;
}

function decode(data, tagger, simpleValue) {
  var dataView = new DataView(data);
  var offset = 0;

  if (typeof tagger !== "function")
    tagger = function(value) { return value; };
  if (typeof simpleValue !== "function")
    simpleValue = function() { return undefined; };

  function read(value, length) {
    offset += length;
    return value;
  }
  function readArrayBuffer(length) {
    return read(new Uint8Array(data, offset, length), length);
  }
  function readFloat16() {
    var tempArrayBuffer = new ArrayBuffer(4);
    var tempDataView = new DataView(tempArrayBuffer);
    var value = readUint16();

    var sign = value & 0x8000;
    var exponent = value & 0x7c00;
    var fraction = value & 0x03ff;

    if (exponent === 0x7c00)
      exponent = 0xff << 10;
    else if (exponent !== 0)
      exponent += (127 - 15) << 10;
    else if (fraction !== 0)
      return fraction * POW_2_24;

    tempDataView.setUint32(0, sign << 16 | exponent << 13 | fraction << 13);
    return tempDataView.getFloat32(0);
  }
  function readFloat32() {
    return read(dataView.getFloat32(offset), 4);
  }
  function readFloat64() {
    return read(dataView.getFloat64(offset), 8);
  }
  function readUint8() {
    return read(dataView.getUint8(offset), 1);
  }
  function readUint16() {
    return read(dataView.getUint16(offset), 2);
  }
  function readUint32() {
    return read(dataView.getUint32(offset), 4);
  }
  function readUint64() {
    return readUint32() * POW_2_32 + readUint32();
  }
  function readBreak() {
    if (dataView.getUint8(offset) !== 0xff)
      return false;
    offset += 1;
    return true;
  }
  function readLength(additionalInformation) {
    if (additionalInformation < 24)
      return additionalInformation;
    if (additionalInformation === 24)
      return readUint8();
    if (additionalInformation === 25)
      return readUint16();
    if (additionalInformation === 26)
      return readUint32();
    if (additionalInformation === 27)
      return readUint64();
    if (additionalInformation === 31)
      return -1;
    throw "Invalid length encoding";
  }
  function readIndefiniteStringLength(majorType) {
    var initialByte = readUint8();
    if (initialByte === 0xff)
      return -1;
    var length = readLength(initialByte & 0x1f);
    if (length < 0 || (initialByte >> 5) !== majorType)
      throw "Invalid indefinite length element";
    return length;
  }

  function appendUtf16data(utf16data, length) {
    for (var i = 0; i < length; ++i) {
      var value = readUint8();
      if (value & 0x80) {
        if (value < 0xe0) {
          value = (value & 0x1f) <<  6
                | (readUint8() & 0x3f);
          length -= 1;
        } else if (value < 0xf0) {
          value = (value & 0x0f) << 12
                | (readUint8() & 0x3f) << 6
                | (readUint8() & 0x3f);
          length -= 2;
        } else {
          value = (value & 0x0f) << 18
                | (readUint8() & 0x3f) << 12
                | (readUint8() & 0x3f) << 6
                | (readUint8() & 0x3f);
          length -= 3;
        }
      }

      if (value < 0x10000) {
        utf16data.push(value);
      } else {
        value -= 0x10000;
        utf16data.push(0xd800 | (value >> 10));
        utf16data.push(0xdc00 | (value & 0x3ff));
      }
    }
  }

  function decodeItem() {
    var initialByte = readUint8();
    var majorType = initialByte >> 5;
    var additionalInformation = initialByte & 0x1f;
    var i;
    var length;

    if (majorType === 7) {
      switch (additionalInformation) {
        case 25:
          return readFloat16();
        case 26:
          return readFloat32();
        case 27:
          return readFloat64();
      }
    }

    length = readLength(additionalInformation);
    if (length < 0 && (majorType < 2 || 6 < majorType))
      throw "Invalid length";

    switch (majorType) {
      case 0:
        return length;
      case 1:
        return -1 - length;
      case 2:
        if (length < 0) {
          var elements = [];
          var fullArrayLength = 0;
          while ((length = readIndefiniteStringLength(majorType)) >= 0) {
            fullArrayLength += length;
            elements.push(readArrayBuffer(length));
          }
          var fullArray = new Uint8Array(fullArrayLength);
          var fullArrayOffset = 0;
          for (i = 0; i < elements.length; ++i) {
            fullArray.set(elements[i], fullArrayOffset);
            fullArrayOffset += elements[i].length;
          }
          return fullArray;
        }
        return readArrayBuffer(length);
      case 3:
        var utf16data = [];
        if (length < 0) {
          while ((length = readIndefiniteStringLength(majorType)) >= 0)
            appendUtf16data(utf16data, length);
        } else
          appendUtf16data(utf16data, length);
        return String.fromCharCode.apply(null, utf16data);
      case 4:
        var retArray;
        if (length < 0) {
          retArray = [];
          while (!readBreak())
            retArray.push(decodeItem());
        } else {
          retArray = new Array(length);
          for (i = 0; i < length; ++i)
            retArray[i] = decodeItem();
        }
        return retArray;
      case 5:
        var retObject = {};
        for (i = 0; i < length || length < 0 && !readBreak(); ++i) {
          var key = decodeItem();
          retObject[key] = decodeItem();
        }
        return retObject;
      case 6:
        return tagger(decodeItem(), length);
      case 7:
        switch (length) {
          case 20:
            return false;
          case 21:
            return true;
          case 22:
            return null;
          case 23:
            return undefined;
          default:
            return simpleValue(length);
        }
    }
  }

  var ret = decodeItem();
  if (offset !== data.byteLength)
    throw "Remaining bytes";
  return ret;
}

var obj = { encode: encode, decode: decode };

if (typeof define === "function" && define.amd)
  define("cbor/cbor", obj);
else if (!global.CBOR)
  global.CBOR = obj;

})(this);
<commit_msg>Use shifts for integer multiplications.<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Patrick Gansterer <paroga@paroga.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

(function(global, undefined) { "use strict";
var POW_2_24 = 5.960464477539063e-8,
    POW_2_32 = 4294967296,
    POW_2_53 = 9007199254740992;

function encode(value) {
  var data = new ArrayBuffer(256);
  var dataView = new DataView(data);
  var lastLength;
  var offset = 0;

  function ensureSpace(length) {
    var newByteLength = data.byteLength;
    var requiredLength = offset + length;
    while (newByteLength < requiredLength)
      newByteLength = newByteLength << 1;
    if (newByteLength !== data.byteLength) {
      var oldDataView = dataView;
      data = new ArrayBuffer(newByteLength);
      dataView = new DataView(data);
      var uint32count = (offset + 3) >> 2;
      for (var i = 0; i < uint32count; ++i)
        dataView.setUint32(i << 2, oldDataView.getUint32(i << 2));
    }

    lastLength = length;
    return dataView;
  }
  function write() {
    offset += lastLength;
  }
  function writeFloat64(value) {
    write(ensureSpace(8).setFloat64(offset, value));
  }
  function writeUint8(value) {
    write(ensureSpace(1).setUint8(offset, value));
  }
  function writeUint8Array(value) {
    var dataView = ensureSpace(value.length);
    for (var i = 0; i < value.length; ++i)
      dataView.setUint8(offset + i, value[i]);
    write();
  }
  function writeUint16(value) {
    write(ensureSpace(2).setUint16(offset, value));
  }
  function writeUint32(value) {
    write(ensureSpace(4).setUint32(offset, value));
  }
  function writeUint64(value) {
    var low = value % POW_2_32;
    var high = (value - low) / POW_2_32;
    var dataView = ensureSpace(8);
    dataView.setUint32(offset, high);
    dataView.setUint32(offset + 4, low);
    write();
  }
  function writeTypeAndLength(type, length) {
    if (length < 24) {
      writeUint8(type << 5 | length);
    } else if (length < 0x100) {
      writeUint8(type << 5 | 24);
      writeUint8(length);
    } else if (length < 0x10000) {
      writeUint8(type << 5 | 25);
      writeUint16(length);
    } else if (length < 0x100000000) {
      writeUint8(type << 5 | 26);
      writeUint32(length);
    } else {
      writeUint8(type << 5 | 27);
      writeUint64(length);
    }
  }

  function encodeItem(value) {
    var i;

    if (value === false)
      return writeUint8(0xf4);
    if (value === true)
      return writeUint8(0xf5);
    if (value === null)
      return writeUint8(0xf6);
    if (value === undefined)
      return writeUint8(0xf7);

    switch (typeof value) {
      case "number":
        if (Math.floor(value) === value) {
          if (0 <= value && value <= POW_2_53)
            return writeTypeAndLength(0, value);
          if (-POW_2_53 <= value && value < 0)
            return writeTypeAndLength(1, -(value + 1));
        }
        writeUint8(0xfb);
        return writeFloat64(value);

      case "string":
        var utf8data = [];
        for (i = 0; i < value.length; ++i) {
          var charCode = value.charCodeAt(i);
          if (charCode < 0x80) {
            utf8data.push(charCode);
          } else if (charCode < 0x800) {
            utf8data.push(0xc0 | charCode >> 6);
            utf8data.push(0x80 | charCode & 0x3f);
          } else if (charCode < 0xd800) {
            utf8data.push(0xe0 | charCode >> 12);
            utf8data.push(0x80 | (charCode >> 6)  & 0x3f);
            utf8data.push(0x80 | charCode & 0x3f);
          } else {
            charCode = (charCode & 0x3ff) << 10;
            charCode |= value.charCodeAt(++i) & 0x3ff;
            charCode += 0x10000;

            utf8data.push(0xf0 | charCode >> 18);
            utf8data.push(0x80 | (charCode >> 12)  & 0x3f);
            utf8data.push(0x80 | (charCode >> 6)  & 0x3f);
            utf8data.push(0x80 | charCode & 0x3f);
          }
        }

        writeTypeAndLength(3, utf8data.length);
        return writeUint8Array(utf8data);

      default:
        var length;
        if (Array.isArray(value)) {
          length = value.length;
          writeTypeAndLength(4, length);
          for (i = 0; i < length; ++i)
            encodeItem(value[i]);
        } else if (value instanceof Uint8Array) {
          writeTypeAndLength(2, value.length);
          writeUint8Array(value);
        } else {
          var keys = Object.keys(value);
          length = keys.length;
          writeTypeAndLength(5, length);
          for (i = 0; i < length; ++i) {
            var key = keys[i];
            encodeItem(key);
            encodeItem(value[key]);
          }
        }
    }
  }

  encodeItem(value);

  if ("slice" in data)
    return data.slice(0, offset);

  var ret = new ArrayBuffer(offset);
  var retView = new DataView(ret);
  for (var i = 0; i < offset; ++i)
    retView.setUint8(i, dataView.getUint8(i));
  return ret;
}

function decode(data, tagger, simpleValue) {
  var dataView = new DataView(data);
  var offset = 0;

  if (typeof tagger !== "function")
    tagger = function(value) { return value; };
  if (typeof simpleValue !== "function")
    simpleValue = function() { return undefined; };

  function read(value, length) {
    offset += length;
    return value;
  }
  function readArrayBuffer(length) {
    return read(new Uint8Array(data, offset, length), length);
  }
  function readFloat16() {
    var tempArrayBuffer = new ArrayBuffer(4);
    var tempDataView = new DataView(tempArrayBuffer);
    var value = readUint16();

    var sign = value & 0x8000;
    var exponent = value & 0x7c00;
    var fraction = value & 0x03ff;

    if (exponent === 0x7c00)
      exponent = 0xff << 10;
    else if (exponent !== 0)
      exponent += (127 - 15) << 10;
    else if (fraction !== 0)
      return fraction * POW_2_24;

    tempDataView.setUint32(0, sign << 16 | exponent << 13 | fraction << 13);
    return tempDataView.getFloat32(0);
  }
  function readFloat32() {
    return read(dataView.getFloat32(offset), 4);
  }
  function readFloat64() {
    return read(dataView.getFloat64(offset), 8);
  }
  function readUint8() {
    return read(dataView.getUint8(offset), 1);
  }
  function readUint16() {
    return read(dataView.getUint16(offset), 2);
  }
  function readUint32() {
    return read(dataView.getUint32(offset), 4);
  }
  function readUint64() {
    return readUint32() * POW_2_32 + readUint32();
  }
  function readBreak() {
    if (dataView.getUint8(offset) !== 0xff)
      return false;
    offset += 1;
    return true;
  }
  function readLength(additionalInformation) {
    if (additionalInformation < 24)
      return additionalInformation;
    if (additionalInformation === 24)
      return readUint8();
    if (additionalInformation === 25)
      return readUint16();
    if (additionalInformation === 26)
      return readUint32();
    if (additionalInformation === 27)
      return readUint64();
    if (additionalInformation === 31)
      return -1;
    throw "Invalid length encoding";
  }
  function readIndefiniteStringLength(majorType) {
    var initialByte = readUint8();
    if (initialByte === 0xff)
      return -1;
    var length = readLength(initialByte & 0x1f);
    if (length < 0 || (initialByte >> 5) !== majorType)
      throw "Invalid indefinite length element";
    return length;
  }

  function appendUtf16data(utf16data, length) {
    for (var i = 0; i < length; ++i) {
      var value = readUint8();
      if (value & 0x80) {
        if (value < 0xe0) {
          value = (value & 0x1f) <<  6
                | (readUint8() & 0x3f);
          length -= 1;
        } else if (value < 0xf0) {
          value = (value & 0x0f) << 12
                | (readUint8() & 0x3f) << 6
                | (readUint8() & 0x3f);
          length -= 2;
        } else {
          value = (value & 0x0f) << 18
                | (readUint8() & 0x3f) << 12
                | (readUint8() & 0x3f) << 6
                | (readUint8() & 0x3f);
          length -= 3;
        }
      }

      if (value < 0x10000) {
        utf16data.push(value);
      } else {
        value -= 0x10000;
        utf16data.push(0xd800 | (value >> 10));
        utf16data.push(0xdc00 | (value & 0x3ff));
      }
    }
  }

  function decodeItem() {
    var initialByte = readUint8();
    var majorType = initialByte >> 5;
    var additionalInformation = initialByte & 0x1f;
    var i;
    var length;

    if (majorType === 7) {
      switch (additionalInformation) {
        case 25:
          return readFloat16();
        case 26:
          return readFloat32();
        case 27:
          return readFloat64();
      }
    }

    length = readLength(additionalInformation);
    if (length < 0 && (majorType < 2 || 6 < majorType))
      throw "Invalid length";

    switch (majorType) {
      case 0:
        return length;
      case 1:
        return -1 - length;
      case 2:
        if (length < 0) {
          var elements = [];
          var fullArrayLength = 0;
          while ((length = readIndefiniteStringLength(majorType)) >= 0) {
            fullArrayLength += length;
            elements.push(readArrayBuffer(length));
          }
          var fullArray = new Uint8Array(fullArrayLength);
          var fullArrayOffset = 0;
          for (i = 0; i < elements.length; ++i) {
            fullArray.set(elements[i], fullArrayOffset);
            fullArrayOffset += elements[i].length;
          }
          return fullArray;
        }
        return readArrayBuffer(length);
      case 3:
        var utf16data = [];
        if (length < 0) {
          while ((length = readIndefiniteStringLength(majorType)) >= 0)
            appendUtf16data(utf16data, length);
        } else
          appendUtf16data(utf16data, length);
        return String.fromCharCode.apply(null, utf16data);
      case 4:
        var retArray;
        if (length < 0) {
          retArray = [];
          while (!readBreak())
            retArray.push(decodeItem());
        } else {
          retArray = new Array(length);
          for (i = 0; i < length; ++i)
            retArray[i] = decodeItem();
        }
        return retArray;
      case 5:
        var retObject = {};
        for (i = 0; i < length || length < 0 && !readBreak(); ++i) {
          var key = decodeItem();
          retObject[key] = decodeItem();
        }
        return retObject;
      case 6:
        return tagger(decodeItem(), length);
      case 7:
        switch (length) {
          case 20:
            return false;
          case 21:
            return true;
          case 22:
            return null;
          case 23:
            return undefined;
          default:
            return simpleValue(length);
        }
    }
  }

  var ret = decodeItem();
  if (offset !== data.byteLength)
    throw "Remaining bytes";
  return ret;
}

var obj = { encode: encode, decode: decode };

if (typeof define === "function" && define.amd)
  define("cbor/cbor", obj);
else if (!global.CBOR)
  global.CBOR = obj;

})(this);
<|endoftext|>


<commit_before>function Cell(loc, d) {
  this.location = createVector(width/2,height/2) || loc
  this.diameter = height || d

  this.color = {
    r: random(50, 230),
    g: random(50, 230),
    b: random(50, 230),
    a: 255
  }

  this.render = function() {
    noStroke()
    fill (this.color.r, this.color.g, this.color.b, this.color.a)
    ellipse(this.location.x,this.location.y,this.diameter,this.diameter)
  }
}
<commit_msg>Fixed syntax error<commit_after>function Cell(loc, d) {
  this.location = loc || createVector(width/2,height/2)
  this.diameter = d || height

  this.color = {
    r: random(50, 230),
    g: random(50, 230),
    b: random(50, 230),
    a: 255
  }

  this.render = function() {
    noStroke()
    fill (this.color.r, this.color.g, this.color.b, this.color.a)
    ellipse(this.location.x,this.location.y,this.diameter,this.diameter)
  }
}
<|endoftext|>


<commit_before>import angularWamp from 'angular-wamp';

const chatModule = angular.module('yunityChat', [angularWamp]);

chatModule.provider('$yunityChat', function () {

    this.$get = () => {

        return {

            sendMessage(message) {
                console.log('would send message :)');
            }

        };

    };

    return this;

});

chatModule.config(['$wampProvider', $wampProvider => {

    console.log('configuring wamp');

    $wampProvider.init({
        url: 'ws://localhost:8080/ws',
        realm: 'realm1'
        //Any other AutobahnJS options
    });

}]);

chatModule.run(['$wamp', $wamp => {
    $wamp.open();
}]);

export default 'yunityChat';<commit_msg>use current web location as ws base address<commit_after>import angularWamp from 'angular-wamp';

const chatModule = angular.module('yunityChat', [angularWamp]);

chatModule.provider('$yunityChat', function () {

    this.$get = () => {

        return {

            sendMessage(message) {
                console.log('would send message :)');
            }

        };

    };

    return this;

});

chatModule.config(['$wampProvider', $wampProvider => {

    console.log('configuring wamp');

    $wampProvider.init({
        url: 'ws://' + location.host + '/ws',
        realm: 'realm1'
        //Any other AutobahnJS options
    });

}]);

chatModule.run(['$wamp', $wamp => {
    $wamp.open();
}]);

export default 'yunityChat';
<|endoftext|>


<commit_before>var code;
var pts = 0;
var asdfUsed = 0;
var qwertyUsed = 0;

function codeTest() {
	code = document.getElementById('code');
	if((code.value == "asdf"))
	{
		if (asdfUsed == 0) {}
			pts = pts + 1;
			alert(pts);
		} else {
			alert("You have already used that code!")
		}
		asdfUsed = 1;
	} else if((code.value == "qwerty")) {
		if (qwertyUsed == 0) {
			pts++;
			alert(pts);
		} else {
			alert("you hava already used that code!");
		}
		qwertyUsed = 1;
	}
}

$(document).ready(function() {
	$("#points").append(pts);
});<commit_msg>hfgdhjmsf<commit_after>var code;
var pts = 0;
var asdfUsed = 0;
var qwertyUsed = 0;

function codeTest() {
	code = document.getElementById('code');
	if(code.value == "asdf")
	{
		if (asdfUsed == 0) {
			pts = pts + 1;
			alert(pts);
		} else {
			alert("You have already used that code!")
		}
		asdfUsed = 1;
	} else if(code.value == "qwerty") {
		if (qwertyUsed == 0) {
			pts++;
			alert(pts);
		} else {
			alert("you hava already used that code!");
		}
		qwertyUsed = 1;
	}
}

$(document).ready(function() {
	$("#points").append(pts);
});<|endoftext|>


<commit_before>// most of the code for legalese lives inside libraries:
// legaleseMain M6YlbsVrWR18KeWvOMc3708UQWaHMB8in
// go to Resources / Libraries and import it.

//---------------------------------------------------------------------------------------------------------------- onOpen
/**
 * Adds a custom menu to the active spreadsheet.
 * The onOpen() function, when defined, is automatically invoked whenever the
 * spreadsheet is opened.
 * For more information on using the Spreadsheet API, see
 * https://developers.google.com/apps-script/service_spreadsheet
 */
function onOpen() {
  var legaleseMainExists = false;
  try { if (legaleseMain) { legaleseMainExists = legaleseMain._loaded } }
  catch (e) { Logger.log("caught error %s while testing legaleseMain", e) }

  var legaleseSignatureExists = false;
  try { if (legaleseSignature) { legaleseSignatureExists = legaleseSignature._loaded } }
  catch (e) { Logger.log("caught error %s while testing legaleseSignature", e) }

  if (legaleseMainExists) {
	legaleseMain.onOpen(SpreadsheetApp.getUi().createAddonMenu(),
						legaleseSignatureExists ? legaleseSignature : null
					   );
  }
};

function onFormSubmit(e) {
  var legaleseMainExists = false;
  try { if (legaleseMain) { legaleseMainExists = legaleseMain._loaded } }
  catch (e) { Logger.log("caught error %s while testing legaleseMain", e) }
  if (legaleseMainExists) {
	legaleseMain.onFormSubmit(e);
  }
}
<commit_msg>pass legaleseSignature in onFormSubmit<commit_after>// most of the code for legalese lives inside libraries:
// legaleseMain M6YlbsVrWR18KeWvOMc3708UQWaHMB8in
// go to Resources / Libraries and import it.

//---------------------------------------------------------------------------------------------------------------- onOpen
/**
 * Adds a custom menu to the active spreadsheet.
 * The onOpen() function, when defined, is automatically invoked whenever the
 * spreadsheet is opened.
 * For more information on using the Spreadsheet API, see
 * https://developers.google.com/apps-script/service_spreadsheet
 */
function onOpen() {
  var legaleseMainExists = false;
  try { if (legaleseMain) { legaleseMainExists = legaleseMain._loaded } }
  catch (e) { Logger.log("caught error %s while testing legaleseMain", e) }

  var legaleseSignatureExists = false;
  try { if (legaleseSignature) { legaleseSignatureExists = legaleseSignature._loaded } }
  catch (e) { Logger.log("caught error %s while testing legaleseSignature", e) }

  if (legaleseMainExists) {
	legaleseMain.onOpen(SpreadsheetApp.getUi().createAddonMenu(),
						legaleseSignatureExists ? legaleseSignature : null
					   );
  }
};

function onFormSubmit(e) {
  var legaleseMainExists = false;
  try { if (legaleseMain) { legaleseMainExists = legaleseMain._loaded } }
  catch (e) { Logger.log("caught error %s while testing legaleseMain", e) }

  if (! legaleseMainExists) return;

  var legaleseSignatureExists = false;
  try { if (legaleseSignature) { legaleseSignatureExists = legaleseSignature._loaded } }
  catch (e) { Logger.log("caught error %s while testing legaleseSignature", e) }

  if (legaleseSignatureExists) legaleseMain.onFormSubmit(e, legaleseSignature);
  else                         legaleseMain.onFormSubmit(e, null);
}
<|endoftext|>


<commit_before>var url = 'http://127.0.0.1:8000/'; // This should be local webserver
var capabilities = {
    'browserName': 'firefox'
};
if (process.env.TRAVIS) {
    url = 'https://b3ncr.github.io/angular-xeditable/'; // Change to your dev server
    capabilities["tunnel-identifier"] = process.env.TRAVIS_JOB_NUMBER; // this is required by saucelabs
}

exports.config = {
	baseUrl: url,
	seleniumAddress: 'http://localhost:4444/wd/hub',
    capabilities: capabilities,
	specs: ['docs/demos/text-simple/test-spec.js']
};
<commit_msg>Remove selenium address frm travis config<commit_after>var url = 'http://127.0.0.1:8000/'; // This should be local webserver
var capabilities = {
    'browserName': 'firefox'
};
if (process.env.TRAVIS) {
    url = 'https://b3ncr.github.io/angular-xeditable/'; // Change to your dev server
    capabilities["tunnel-identifier"] = process.env.TRAVIS_JOB_NUMBER; // this is required by saucelabs
}

exports.config = {
    baseUrl: url,
    //seleniumAddress: 'http://localhost:4444/wd/hub',
    capabilities: {
        "browserName": "firefox",
        "tunnel-identifier": process.env.TRAVIS_JOB_NUMBER
    },
    specs: ['docs/demos/text-simple/test-spec.js']
};
<|endoftext|>


<commit_before>(function($){

  function parseDate(str) {
    var d = new Date(Date.parse(str));

    return d.toISOString();
  }

  // Gets some JSON from the url in `opts.url` then uses `opts.vars` and
  // `opts.display` to add another list item in the required format.
  function getJson(opts, callback) {
    $.getJSON(opts.url, function(data) {
      var vars = {};

      if (opts.vars) {

        // For each element of `opts.vars` run through the given call path to get
        // the value. So, say we have:
        //
        //     vars: {
        //       title: ['title']
        //     }
        //
        // Which would translate to:
        //
        //    vars['title'] = data['title']
        //
        $.each(opts.vars, function(key, val) {
          vars[key] = data;
          $.each(val, function(i, meth) {
            vars[key] = vars[key][meth];
          });
        });

        if (vars.date) {
          // Parse the date, and return in a common format.
          vars.date = parseDate(vars.date);
        };

        callback(vars);

      } else {
        callback(data);
      }
    });
  }

  function addToList(opts, list) {
    return function(data) {
      var text = ''

      if (typeof opts.display == "function") {
        text = opts.display(data);
      } else {
        text = Mustache.render(opts.display, data);
      }

      // Now append a new list element using Mustache with `opts.display` and the
      // vars found above.
      list.append('
' + text + '
');
    }
  }

  function map(obj, func) {
    for (var key in obj) {
      obj[key] = func(obj[key])
    }
    return obj
  }

  var JsonGetter = function() {
    var getter = {
      appendTo: function(list) {
        getJson(this, addToList(this, list))
      }
    }
    return getter
  }

  var XmlGetter = function() {
    var getter = {
      appendTo: function(list) {
        this.url = "http://query.yahooapis.com/v1/public/yql?q=" +
                   encodeURIComponent('select * from xml where url="' + this.url + '"') +
                   "&env=store://datatables.org/alltableswithkeys&format=json"

        this.vars = map(this.vars, function(e) {
          return ['query', 'results'].concat(e);
        });

        getJson(this, addToList(this, list));
      }
    }
    return getter
  };

  var Maker = function(getter, defaults) {
    return function(opts) {
      var getterWithDefaults = $.extend(getter, defaults(opts));

      return $.extend(getterWithDefaults, opts)
    }
  }

  var Twitter = Maker(JsonGetter(), function (opts) {
    return {
      url:  "https://api.twitter.com/1/statuses/user_timeline/" + opts.user + ".json?count=1&include_rts=1&callback=?",
      vars: {
        text: [0, 'text'],
        id:   [0, 'id'],
        date: [0, 'created_at']
      },
      display: '
twitter: {{text}}
'
    }
  })

  var LastFm = Maker(XmlGetter(), function(opts) {
    return {
      url:  'http://ws.audioscrobbler.com/1.0/user/' + opts.user + '/recenttracks.rss?limit=1',
      vars: {
        title: ['rss', 'channel', 'item', 'title'],
        link:  ['rss', 'channel', 'item', 'link'],
        date:  ['rss', 'channel', 'item', 'pubDate']
      },
      display: '
last.fm: {{title}}
',
    }
  })

  var Blog = Maker(XmlGetter(), function(opts) {
    var name = opts.name || 'blog';

    return {
      url: opts.feed,
      vars: {
        title: ['rss', 'channel', 'item', 0, 'title'],
        link:  ['rss', 'channel', 'item', 0, 'link'],
        date:  ['rss', 'channel', 'item', 0, 'pubDate'],
        text:  ['rss', 'channel', 'item', 0, 'description']
      },
      display: '
' + name + ': {{title}}

{{{text}}}
'
    }
  })

  var Flickr = Maker(XmlGetter(), function(opts) {
    return {
      url: "http://api.flickr.com/services/feeds/photos_public.gne?id=" + opts.user + "&lang=en-us&format=rss_200",
      vars: {
        title: ['rss', 'channel', 'item', 0, 'title', 0],
        photo: ['rss', 'channel', 'item', 0, 'content', 'url'],
        date:  ['rss', 'channel', 'item', 0, 'pubDate'],
        link:  ['rss', 'channel', 'item', 0, 'link']
      },
      display: '
flickr: {{title}}
 '
    }
  })

  var Xml = Maker(XmlGetter(), function(opts) {
    return {}
  })

  var Json = Maker(JsonGetter(), function(opts) {
    return {}
  })

  var Providers = {
    flickr:    Flickr,
    "last.fm": LastFm,
    twitter:   Twitter,
    blog:      Blog,
    xml:       Xml,
    json:      Json,
  }

  $.fn.myLast = function(config) {
    var list = $(this);

    $.each(config, function(i, obj) {
      var provider = Providers[obj.type];

      if (provider == null) {
        console.log("ERROR: No provider '" + obj.type + "'");
      } else {
        provider(obj).appendTo(list);
      }
    });
  };

})(jQuery);<commit_msg>Moved providers into Provider object<commit_after>(function($){

  function parseDate(str) {
    var d = new Date(Date.parse(str));

    return d.toISOString();
  }

  // Gets some JSON from the url in `opts.url` then uses `opts.vars` and
  // `opts.display` to add another list item in the required format.
  function getJson(opts, callback) {
    $.getJSON(opts.url, function(data) {
      var vars = {};

      if (opts.vars) {

        // For each element of `opts.vars` run through the given call path to get
        // the value. So, say we have:
        //
        //     vars: {
        //       title: ['title']
        //     }
        //
        // Which would translate to:
        //
        //    vars['title'] = data['title']
        //
        $.each(opts.vars, function(key, val) {
          vars[key] = data;
          $.each(val, function(i, meth) {
            vars[key] = vars[key][meth];
          });
        });

        if (vars.date) {
          // Parse the date, and return in a common format.
          vars.date = parseDate(vars.date);
        };

        callback(vars);

      } else {
        callback(data);
      }
    });
  }

  function addToList(opts, list) {
    return function(data) {
      var text = ''

      if (typeof opts.display == "function") {
        text = opts.display(data);
      } else {
        text = Mustache.render(opts.display, data);
      }

      // Now append a new list element using Mustache with `opts.display` and the
      // vars found above.
      list.append('
' + text + '
');
    }
  }

  function map(obj, func) {
    for (var key in obj) {
      obj[key] = func(obj[key])
    }
    return obj
  }

  var JsonGetter = function() {
    var getter = {
      appendTo: function(list) {
        getJson(this, addToList(this, list))
      }
    }
    return getter
  }

  var XmlGetter = function() {
    var getter = {
      appendTo: function(list) {
        this.url = "http://query.yahooapis.com/v1/public/yql?q=" +
                   encodeURIComponent('select * from xml where url="' + this.url + '"') +
                   "&env=store://datatables.org/alltableswithkeys&format=json"

        this.vars = map(this.vars, function(e) {
          return ['query', 'results'].concat(e);
        });

        getJson(this, addToList(this, list));
      }
    }
    return getter
  };

  var Maker = function(getter, defaults) {
    return function(opts) {
      var getterWithDefaults = $.extend(getter, defaults(opts));

      return $.extend(getterWithDefaults, opts)
    }
  }

  var Providers = {
    flickr: Maker(XmlGetter(), function(opts) {
      return {
        url: "http://api.flickr.com/services/feeds/photos_public.gne?id=" + opts.user + "&lang=en-us&format=rss_200",
        vars: {
          title: ['rss', 'channel', 'item', 0, 'title', 0],
          photo: ['rss', 'channel', 'item', 0, 'content', 'url'],
          date:  ['rss', 'channel', 'item', 0, 'pubDate'],
          link:  ['rss', 'channel', 'item', 0, 'link']
        },
        display: '
flickr: {{title}}
 '
      }
    }),

    "last.fm": Maker(XmlGetter(), function(opts) {
      return {
        url:  'http://ws.audioscrobbler.com/1.0/user/' + opts.user + '/recenttracks.rss?limit=1',
        vars: {
          title: ['rss', 'channel', 'item', 'title'],
          link:  ['rss', 'channel', 'item', 'link'],
          date:  ['rss', 'channel', 'item', 'pubDate']
        },
        display: '
last.fm: {{title}}
',
      }
    }),

    twitter: Maker(JsonGetter(), function (opts) {
      return {
        url:  "https://api.twitter.com/1/statuses/user_timeline/" + opts.user + ".json?count=1&include_rts=1&callback=?",
        vars: {
          text: [0, 'text'],
          id:   [0, 'id'],
          date: [0, 'created_at']
        },
        display: '
twitter: {{text}}
'
      }
    }),

    blog: Maker(XmlGetter(), function(opts) {
      var name = opts.name || 'blog';

      return {
        url: opts.feed,
        vars: {
          title: ['rss', 'channel', 'item', 0, 'title'],
          link:  ['rss', 'channel', 'item', 0, 'link'],
          date:  ['rss', 'channel', 'item', 0, 'pubDate'],
          text:  ['rss', 'channel', 'item', 0, 'description']
        },
        display: '
' + name + ': {{title}}

{{{text}}}
'
      }
    }),

    xml: Maker(XmlGetter(), function(opts) {
      return {}
    }),

    json: Maker(JsonGetter(), function(opts) {
      return {}
    }),
  }

  $.fn.myLast = function(config) {
    var list = $(this);

    $.each(config, function(i, obj) {
      var provider = Providers[obj.type];

      if (provider == null) {
        console.log("ERROR: No provider '" + obj.type + "'");
      } else {
        provider(obj).appendTo(list);
      }
    });
  };

})(jQuery);<|endoftext|>


<commit_before>/* globals Couch */

/*

This library exports the following functions:

login: function(username,password,notifier)
uuids: function(count)
logout: function(notifier)
database: function(database)

  retrieve: function(id,notifier)
  retrieve: function([id1,id2],notifier)
  all: function(notifier)
  all: function(opts,notifier)
  save: function(id,rec,notifier)
  save: function(rec,notifier)
  save: function(id,rev,rec,notifier)
  save: function([rec1,rec2],notifier)
  // not copying the save view guessing behaviour!
  create: function(id,rec,notifier)
  destroy: function(notifier)
  remove: function(id,notifier)
  exists: function(notifier)
  view: function(id,notifier)
  view: function(id,opts,notifier) (opts: reduce,group,startkey,endkey)
  //merge: function(id,objtomerge,notifier)
  //changes: function(notifier) // one time
  //changes: function(opts,notifier) //opts: { since: 32 } one time
  //changes: function(opts) // no notifier
  //saveAttachment: function(idData,attachmentData,notifier)
  //getAttachment: function(id,attachmentId,notifier)
  // removeAttachment: function(id,attachmentId,notifier)

  notifier is either a string or a function. If the notifier is a function it will be called,
  if it is a string, it will be sent as an event to the defaultResponder set to the
  defaultResponder property.
  Extra arguments are allowed and are passed on to the notifier all functions.

  If the notifier is a function, the arguments are patched through.
  Because the defaultResponder argument signature is limited by the statechart to a maximum of two arguments
  at the time of writing, the signature is different:
  [eventName]: function( { err: err, result: result }, [array,of,extra,arguments]);

*/

Couch = SC.Object.create({

});

// extending SC.Request to also include a head call
SC.mixin(SC.Request,{
  headUrl: function(address){
    return this.create().set('address','address').set('type','HEAD');
  }
});

// we have to monkeypatch XHRResponse to allow upload progress

SC.mixin(SC.XHRResponse.prototype, {
  uploadProgress: function(evt){
    var e = evt.originalEvent;
    var done = e.position || e.loaded, total = e.totalSize || e.total;
    e.percentage = (done/total*1000)/10;
    this.get('originalRequest').set('progress',e);
    //console.log('xhr.upload progress: ' + done + '/' + total + "=" + Math.floor(done/total*1000)/10 + "%");
  },

  invokeTransport: function() {
    var rawRequest, transport, handleReadyStateChange, async, headers;

    rawRequest = this.createRequest();

    // save it
    this.set('rawRequest', rawRequest);

    // configure async callback - differs per browser...
    async = !!this.getPath('request.isAsynchronous') ;
    if (async) {
      if (!SC.browser.msie && !SC.browser.opera ) {
        SC.Event.add(rawRequest, 'readystatechange', this,
                     this.finishRequest, rawRequest) ;
        if(rawRequest.upload){
          console.log('attaching upload.onprogress');
          SC.Event.add(rawRequest.upload, 'progress', this, this.uploadProgress, rawRequest);
          // transport = this;
          // rawRequest.upload.onprogress = function(e){
          //   transport.uploadProgress(e);
          // };

        }
      } else {
        transport=this;
        handleReadyStateChange = function() {
          if (!transport) return null ;
          var ret = transport.finishRequest();
          if (ret) transport = null ; // cleanup memory
          return ret ;
        };
        rawRequest.onreadystatechange = handleReadyStateChange;
        if(rawRequest.upload){
          rawRequest.upload.onprogress = function(e){
            console.log('onprogess');
            if(!transport) return null;
            var ret = transport.uploadProgress(e);
            if (ret) transport = null;
            return ret;
          };
        }
      }
    }

    // initiate request.
    rawRequest.open(this.get('type'), this.get('address'), async ) ;

    // headers need to be set *after* the open call.
    headers = this.getPath('request.headers') ;
    for (var headerKey in headers) {
      rawRequest.setRequestHeader(headerKey, headers[headerKey]) ;
    }

    // now send the actual request body - for sync requests browser will
    // block here
    rawRequest.send(this.getPath('request.encodedBody')) ;
    if (!async) this.finishRequest() ; // not async

    return rawRequest ;
  }
});

<commit_msg>adding runloop trigger in uploadProgress, also monkeypatch finishRequest to remove the event listener after the request is done<commit_after>/* globals Couch */

/*

This library exports the following functions:

login: function(username,password,notifier)
uuids: function(count)
logout: function(notifier)
database: function(database)

  retrieve: function(id,notifier)
  retrieve: function([id1,id2],notifier)
  all: function(notifier)
  all: function(opts,notifier)
  save: function(id,rec,notifier)
  save: function(rec,notifier)
  save: function(id,rev,rec,notifier)
  save: function([rec1,rec2],notifier)
  // not copying the save view guessing behaviour!
  create: function(id,rec,notifier)
  destroy: function(notifier)
  remove: function(id,notifier)
  exists: function(notifier)
  view: function(id,notifier)
  view: function(id,opts,notifier) (opts: reduce,group,startkey,endkey)
  //merge: function(id,objtomerge,notifier)
  //changes: function(notifier) // one time
  //changes: function(opts,notifier) //opts: { since: 32 } one time
  //changes: function(opts) // no notifier
  //saveAttachment: function(idData,attachmentData,notifier)
  //getAttachment: function(id,attachmentId,notifier)
  // removeAttachment: function(id,attachmentId,notifier)

  notifier is either a string or a function. If the notifier is a function it will be called,
  if it is a string, it will be sent as an event to the defaultResponder set to the
  defaultResponder property.
  Extra arguments are allowed and are passed on to the notifier all functions.

  If the notifier is a function, the arguments are patched through.
  Because the defaultResponder argument signature is limited by the statechart to a maximum of two arguments
  at the time of writing, the signature is different:
  [eventName]: function( { err: err, result: result }, [array,of,extra,arguments]);

*/

Couch = SC.Object.create({

});

// extending SC.Request to also include a head call
SC.mixin(SC.Request,{
  headUrl: function(address){
    return this.create().set('address','address').set('type','HEAD');
  }
});

// we have to monkeypatch XHRResponse to allow upload progress

SC.mixin(SC.XHRResponse.prototype, {
  uploadProgress: function(evt){
    SC.RunLoop.begin();
    var e = evt.originalEvent;
    var done = e.position || e.loaded, total = e.totalSize || e.total;
    e.percentage = (done/total*1000)/10;
    this.get('originalRequest').set('progress',e);
    SC.RunLoop.end();
    //console.log('xhr.upload progress: ' + done + '/' + total + "=" + Math.floor(done/total*1000)/10 + "%");
  },

  invokeTransport: function() {
    var rawRequest, transport, handleReadyStateChange, async, headers;

    rawRequest = this.createRequest();

    // save it
    this.set('rawRequest', rawRequest);

    // configure async callback - differs per browser...
    async = !!this.getPath('request.isAsynchronous') ;
    if (async) {
      if (!SC.browser.msie && !SC.browser.opera ) {
        SC.Event.add(rawRequest, 'readystatechange', this,
                     this.finishRequest, rawRequest) ;
        if(rawRequest.upload){
          console.log('attaching upload.onprogress');
          SC.Event.add(rawRequest.upload, 'progress', this, this.uploadProgress, rawRequest);
          // transport = this;
          // rawRequest.upload.onprogress = function(e){
          //   transport.uploadProgress(e);
          // };

        }
      } else {
        transport=this;
        handleReadyStateChange = function() {
          if (!transport) return null ;
          var ret = transport.finishRequest();
          if (ret) transport = null ; // cleanup memory
          return ret ;
        };
        rawRequest.onreadystatechange = handleReadyStateChange;
        if(rawRequest.upload){
          rawRequest.upload.onprogress = function(e){
            if(!transport) return null;
            var ret = transport.uploadProgress(e);
            if (ret) transport = null;
            return ret;
          };
        }
      }
    }

    // initiate request.
    rawRequest.open(this.get('type'), this.get('address'), async ) ;

    // headers need to be set *after* the open call.
    headers = this.getPath('request.headers') ;
    for (var headerKey in headers) {
      rawRequest.setRequestHeader(headerKey, headers[headerKey]) ;
    }

    // now send the actual request body - for sync requests browser will
    // block here
    rawRequest.send(this.getPath('request.encodedBody')) ;
    if (!async) this.finishRequest() ; // not async

    return rawRequest ;
  },

  finishRequest: function(evt) {
    var rawRequest = this.get('rawRequest'),
        readyState = rawRequest.readyState,
        error, status, msg;

    if (readyState === 4 && !this.get('timedOut')) {
      this.receive(function(proceed) {
        if (!proceed) return ; // skip receiving...

        // collect the status and decide if we're in an error state or not
        status = -1 ;
        try {
          status = rawRequest.status || 0;
        } catch (e) {}

        // if there was an error - setup error and save it
        if ((status < 200) || (status >= 300)) {

          try {
            msg = rawRequest.statusText || '';
          } catch(e2) {
            msg = '';
          }

          error = SC.$error(msg || "HTTP Request failed", "Request", status) ;
          error.set("errorValue", this) ;
          this.set('isError', YES);
          this.set('errorObject', error);
        }

        // set the status - this will trigger changes on relatedp properties
        this.set('status', status);

      }, this);

      // Avoid memory leaks
      if (!SC.browser.msie && !SC.browser.opera) {
        SC.Event.remove(rawRequest, 'readystatechange', this, this.finishRequest);
        if(rawRequest.upload){
          SC.Event.remove(rawRequest.upload, 'progress', this, this.uploadProgress);
        }
      } else {
        rawRequest.onreadystatechange = null;
        if(rawRequest.upload){
          rawRequest.upload.onprogress = null;
        }
      }

      return YES;
    }
    return NO;
  }
});

<|endoftext|>


<commit_before>/*
* Simulazione del problema degli n-corpi applicata ad una parte del sistema solare (sole, mercurio, venere, terra, marte)
* tramite metodo di Eulero, con un dt di 1 ora.
*/

//Costante di Gravitazione
var G = 6.67408e-11;

class Vector{
  constructor(x, y){
    this.x = x;
    this.y = y;
  }
}

//la classe rappresenta un corpo nello spazio, la dicitura pianeta non è del tutto corretta
class Planet {
  constructor(x, y, mass, velocity, stage, planetsList, color) {
    //Posizione x e y del pianeta
    this.x = x;
    this.y = y;
    //Incremento tra uno step e l'altro delle componenti x e y
    this.dx = 0;
    this.dy = 0;
    //Massa del pianeta
    this.mass = mass;
    //Vettore velocità
    this.velocity = velocity;

    this.stage = stage;

    //Traccia dell'orbita
    this.orbitStroke = new createjs.Shape();
    this.stage.addChild(this.orbitStroke);

    //Rappresentazione del pianeta
    this.shape = new createjs.Shape();
    this.shape.graphics.beginFill(color).drawCircle(0, 0, 10);
    this.stage.addChild(this.shape);

    this.planetsList = planetsList;

  }
  update(){
    //Per ogni pianeta che influisce nel sistema calcolo l'attrazione gravitazionale
    //si potrebbe ottimizzare questa parte (anche perchè calcola due volte la stessa forza per 2 pianeti)

    //Elenco delle forze agenti sul pianeta
    var forzeAgenti = [];
    //Per ogni pianeta presente
    this.planetsList.forEach(function(planet) {
      if(planet != this){
        //Distanza tra i due pianeti
        var r = Math.sqrt(Math.pow(this.x - planet.x, 2) + Math.pow(this.y - planet.y, 2));
        //Forza di attrazione tra i due pianeti (intensità del vettore F)
        var Fg = -G * ((this.mass * planet.mass) / Math.pow(r, 2));
        //trovo l'angolo in radianti tra i due pianeti (direzione del vettore F)
        var deltaX = this.x - planet.x;
        var deltaY = this.y - planet.y;
        var angle = Math.atan2(deltaY, deltaX);
        //trovo le componenti x e y della forza
        var Fx = Fg * Math.cos(angle);
        var Fy = Fg * Math.sin(angle);
        //Aggiungo la forza nell'elenco di tutte le forze agenti
        forzeAgenti.push(new Vector(Fx, Fy));
      }
    }, this);

    //Trovo la forza risultante sommando i vettori di forza agenti sul pianeta
    var Fx = 0;
    var Fy = 0;
    forzeAgenti.forEach(function(forza) {
      Fx += forza.x;
      Fy += forza.y;
    });
    var Frisultante = new Vector(Fx, Fy);

    //Calcolo le componenti dell'accelerazione
    var Ax = Frisultante.x / this.mass;
    var Ay = Frisultante.y / this.mass;

    //dt in secondi, ovvero l'incremento dell'integratore di eulero
    var dt = 60*60*1; //1h
    //Calcolo la variazione di posizione
    //l'accelerazione viene aggiornata step by step quindi per un dt di tempo il pianeta avanza con una accelerazione = 0 (moto rettilineo uniforme)
    this.dx = (this.velocity.x * dt); //+ ((1/2) * Ax * Math.pow(dt, 2));
    this.dy = (this.velocity.y * dt); //+ ((1/2) * Ay * Math.pow(dt, 2));
    //metodo alternativo migliore è quello di fare una media tra accelerazione iniziale e quella stimata senza perturbazioni
    //approfondimento: https://en.wikipedia.org/wiki/Numerical_model_of_the_Solar_System

    //Calcolo la nuova velocità del pianeta basandomi sull'accelerazione
    this.velocity.x = this.velocity.x + (Ax * dt);
    this.velocity.y = this.velocity.y + (Ay * dt);
  }
  //Viene eseguito dopo che tutti i corpi hanno calcolato le loro forze, altrimenti se modificassi la posizione in istanti diversi dei vari corpi il calcolo risulta errato
  afterUpdate(){
    //Sposto il pianeta nella sua nuova posizione
    this.x += this.dx;
    this.y += this.dy;

    //Utilizzo un fattore di divisione pari a 1*10^9 per scalare le dimensioni della posizione, per farle rientrare su schermo
    var newshapeX = Math.round((stage.canvas.width/2) + (this.x/1e9));
    var newshapeY = Math.round((stage.canvas.height/2) + (this.y/1e9));

    //Traccio l'orbita
    if(this.shape.x != 0 && this.shape.y != 0){
      this.orbitStroke.graphics.setStrokeStyle(2);
      this.orbitStroke.graphics.beginStroke("red");
      this.orbitStroke.graphics.moveTo(this.shape.x,this.shape.y);
      this.orbitStroke.graphics.lineTo(newshapeX, newshapeY);
      this.orbitStroke.graphics.endStroke();
    }

    //Sposto il pianeta a livello grafico
    this.shape.x = newshapeX;
    this.shape.y = newshapeY;

    //console.log(this.shape.x + ", " + this.shape.y);
  }

}

stage = new createjs.Stage("appCanvas");
background = new createjs.Shape();
background.graphics.beginFill("black").drawRect(0, 0, stage.canvas.width, stage.canvas.height);
stage.addChild(background);

//Lista dei pianeti
planetsList = [];

//Tutti i pianeti sono presi al Perielio con la loro velocità max, fonte dei dati Wikipedia
const sole = new Planet(0, 0, 1.98855e30 , new Vector(0,0), stage, planetsList, "#ffff36");
const mercurio = new Planet(4.6001272e10, 0, 3.302e23 , new Vector(0,-5.8980e4), stage, planetsList, "#808080");
const venere = new Planet(1.07476002e11, 0, 4.8685e24 , new Vector(0,-3.5259e4), stage, planetsList, "#b94646");
const terra = new Planet(1.47098074e11, 0, 5.9726e24 , new Vector(0,-3.02865e4), stage, planetsList, "#19a3ff");
const marte = new Planet(2.06644545e11, 0, 6.4185e23 , new Vector(0,-2.6499e4), stage, planetsList, "#b94646");

planetsList.push(sole);
planetsList.push(mercurio);
planetsList.push(venere);
planetsList.push(terra);
planetsList.push(marte);

//Contatore delle ore
var elapsedHours = 0;

//I seguenti timeout possono essere migliorati inserendo all'interno un ciclo for che esegua tot step e solo poi aggiorni a schermo la posizione
//Calcolo le posizioni dei pianeti nel tempo ogni 10ms
function timeout() {
  window.setTimeout(function (){
    planetsList.forEach(function (planet){
      planet.update();
    });
    planetsList.forEach(function (planet){
      planet.afterUpdate();
    });
    elapsedHours++;
    timeout();

  }, 10); //1gg = 1sec
}
timeout();

//Mostro a schermo la posizione dei nuovi pianeti a circa 30FPS
function timeout2() {
  window.setTimeout(function (){

    stage.update();
    timeout2();

  }, 33);
}
timeout2();

//Aggiorno il testo che mostra il giorno ogni 200ms
var text = new createjs.Text("Giorno: 0", "20px Arial", "#ff7700");
text.x = 10;
text.y = 10;
stage.addChild(text);
function timeout3() {
  window.setTimeout(function (){
    text.text = "Giorno: " + Math.round(elapsedHours/24);
    timeout3();
  }, 200);
}
timeout3();
<commit_msg>aggiunti commenti e migliorate le performance<commit_after>/*
* Simulazione del problema degli n-corpi applicata ad una parte del sistema solare (sole, mercurio, venere, terra, marte)
* tramite metodo di Eulero, con un dt di 1 ora.
*/

//Costante di Gravitazione
var G = 6.67408e-11;

var fps = 30;
var calcoliPerFrame = 200;
var h = 60*10; //10 minuti - Integratore di Eulero

class Vector{
  constructor(x, y){
    this.x = x;
    this.y = y;
  }
}

//la classe rappresenta un corpo nello spazio, la dicitura pianeta non è del tutto corretta
class Planet {
  constructor(x, y, mass, velocity, stage, planetsList, color) {
    //Posizione x e y del pianeta
    this.x = x;
    this.y = y;
    //Incremento tra uno step e l'altro delle componenti x e y
    this.dx = 0;
    this.dy = 0;
    //Massa del pianeta
    this.mass = mass;
    //Vettore velocità
    this.velocity = velocity;

    this.stage = stage;

    //Traccia dell'orbita
    this.orbitStroke = new createjs.Shape();
    this.stage.addChild(this.orbitStroke);

    //Rappresentazione del pianeta
    this.shape = new createjs.Shape();
    this.shape.graphics.beginFill(color).drawCircle(0, 0, 10);
    this.stage.addChild(this.shape);

    this.planetsList = planetsList;

  }
  update(){
    //Per ogni pianeta che influisce nel sistema calcolo l'attrazione gravitazionale
    //si potrebbe ottimizzare questa parte (anche perchè calcola due volte la stessa forza per 2 pianeti)

    //Elenco delle forze agenti sul pianeta
    var forzeAgenti = [];
    //Per ogni pianeta presente
    this.planetsList.forEach(function(planet) {
      if(planet != this){
        //Distanza tra i due pianeti
        var r = Math.sqrt(Math.pow(this.x - planet.x, 2) + Math.pow(this.y - planet.y, 2));
        //Forza di attrazione tra i due pianeti (intensità del vettore F)
        var Fg = -G * ((this.mass * planet.mass) / Math.pow(r, 2));
        //trovo l'angolo in radianti tra i due pianeti (direzione del vettore F)
        var deltaX = this.x - planet.x;
        var deltaY = this.y - planet.y;
        var angle = Math.atan2(deltaY, deltaX);
        //trovo le componenti x e y della forza
        var Fx = Fg * Math.cos(angle);
        var Fy = Fg * Math.sin(angle);
        //Aggiungo la forza nell'elenco di tutte le forze agenti
        forzeAgenti.push(new Vector(Fx, Fy));
      }
    }, this);

    //Trovo la forza risultante sommando i vettori di forza agenti sul pianeta
    var Fx = 0;
    var Fy = 0;
    forzeAgenti.forEach(function(forza) {
      Fx += forza.x;
      Fy += forza.y;
    });
    var Frisultante = new Vector(Fx, Fy);

    //Calcolo le componenti dell'accelerazione
    var Ax = Frisultante.x / this.mass;
    var Ay = Frisultante.y / this.mass;

    //dt in secondi, ovvero l'incremento dell'integratore di eulero
    //var dt = 60*60*1; //1h
    //var dt = 60*10; //10min
    var dt = h;
    //Calcolo la variazione di posizione
    //l'accelerazione viene aggiornata step by step quindi per un dt di tempo il pianeta avanza con una accelerazione = 0 (moto rettilineo uniforme)
    // Legge del moto:
    // v = dx/dt; a = dv/dt;
    // quindi: dx = v * dt; dv = a * dt;
    // Abbiamo due equazioni ODE (equazioni differenziali ordinarie) che si possono risolvere con le "integrazioni numeriche"
    // Metodo di Eulero:
    // x(n+1) = x(n) + h * f(t(n), x(n))
    // f(t(n), x(n)) = velocità (v)
    this.dx = (this.velocity.x * dt);
    this.dy = (this.velocity.y * dt);
    //metodo alternativo migliore è quello di fare una media tra accelerazione iniziale e quella stimata senza perturbazioni
    //approfondimento: https://en.wikipedia.org/wiki/Numerical_model_of_the_Solar_System

    //Calcolo la nuova velocità del pianeta basandomi sull'accelerazione
    // Metodo di Eulero:
    // v(n+1) = v(n) + h * f(t(n), v(n))
    // f(t(n), v(n)) = accelerazione (a)
    this.velocity.x = this.velocity.x + (Ax * dt);
    this.velocity.y = this.velocity.y + (Ay * dt);
  }
  //Viene eseguito dopo che tutti i corpi hanno calcolato le loro forze, altrimenti se modificassi la posizione in istanti diversi dei vari corpi il calcolo risulta errato
  afterUpdate(){
    //Sposto il pianeta nella sua nuova posizione
    this.x += this.dx;
    this.y += this.dy;

    //Utilizzo un fattore di divisione pari a 1*10^9 per scalare le dimensioni della posizione, per farle rientrare su schermo
    var newshapeX = Math.round((stage.canvas.width/2) + (this.x/1e9));
    var newshapeY = Math.round((stage.canvas.height/2) + (this.y/1e9));

    //Traccio l'orbita
    if(this.shape.x != 0 && this.shape.y != 0 && (this.shape.x != newshapeX || this.shape.y != newshapeY )){
      this.orbitStroke.graphics.setStrokeStyle(2);
      this.orbitStroke.graphics.beginStroke("red");
      this.orbitStroke.graphics.moveTo(this.shape.x,this.shape.y);
      this.orbitStroke.graphics.lineTo(newshapeX, newshapeY);
      this.orbitStroke.graphics.endStroke();
      //this.orbitStroke.cache(0,0,1000,1000);
    }

    //Sposto il pianeta a livello grafico
    this.shape.x = newshapeX;
    this.shape.y = newshapeY;

    //console.log(this.shape.x + ", " + this.shape.y);
  }

}

stage = new createjs.Stage("appCanvas");
background = new createjs.Shape();
background.graphics.beginFill("black").drawRect(0, 0, stage.canvas.width, stage.canvas.height);
stage.addChild(background);

//Lista dei pianeti
planetsList = [];

//Tutti i pianeti sono presi al Perielio con la loro velocità max, fonte dei dati Wikipedia
const sole = new Planet(0, 0, 1.98855e30 , new Vector(0,0), stage, planetsList, "#ffff36");
const mercurio = new Planet(4.6001272e10, 0, 3.302e23 , new Vector(0,-5.8980e4), stage, planetsList, "#808080");
const venere = new Planet(1.07476002e11, 0, 4.8685e24 , new Vector(0,-3.5259e4), stage, planetsList, "#b94646");
const terra = new Planet(1.47098074e11, 0, 5.9726e24 , new Vector(0,-3.02865e4), stage, planetsList, "#19a3ff");
const marte = new Planet(2.06644545e11, 0, 6.4185e23 , new Vector(0,-2.6499e4), stage, planetsList, "#b94646");

planetsList.push(sole);
planetsList.push(mercurio);
planetsList.push(venere);
planetsList.push(terra);
planetsList.push(marte);

var frameCalcolati = 0;

var text = new createjs.Text("Giorno: 0", "20px Arial", "#ff7700");
text.x = 10;
text.y = 10;
stage.addChild(text);
//Mostro a schermo la posizione dei nuovi pianeti a circa 30FPS
function timeout() {
  window.setTimeout(function (){

    for ( var i = 0; i < calcoliPerFrame; i++) {
      planetsList.forEach(function (planet){
        planet.update();
      });
      planetsList.forEach(function (planet){
        planet.afterUpdate();
      });

    }
    frameCalcolati++;
    text.text = "Giorno: " + Math.round(frameCalcolati * calcoliPerFrame * h / 60 / 60 / 24);
    stage.update();
    timeout();

  }, 1000/fps);
}
timeout();
<|endoftext|>


<commit_before>// App-specific back-end Webpack config should be here
const server = {
     entry: {
       index: [
        './src/setup/app.ts'
       ]
     }
};

// App-specific web front-end Webpack config should be here
const web = {
    entry: {
        index: [
            './src/index.tsx'
        ]
    }
};

// App-specific Android React Native front-end Webpack config should be here
const android = {
    //  entry: {
    //    'index.mobile.bundle': [
    //      require.resolve('./react-native-polyfill.js'),
    //      './src/mobile/index.js'
    //    ]
    //  }
};

// App-specific iOS React Native front-end Webpack config should be here
const ios = {
    //  entry: {
    //    'index.mobile.bundle': [
    //      require.resolve('./react-native-polyfill.js'),
    //      './src/mobile/index.js'
    //    ]
    //  }
};

const dependencyPlatforms = {
    "@cdm-logger/server": 'server',
    "bunyan": 'server',
    "export-dir": 'server',
    "express": 'server',
    'body-parser': 'server',
    express: 'server',
    'graphql-server-express': 'server',
    'graphql-subscriptions': 'server',
    'graphql-tools': 'server',
    "graphql-tag": ['server', 'web'],
    'immutability-helper': ['ios', 'android', 'web'],
    'isomorphic-fetch': 'server',
    knex: 'server',
    mysql2: 'server',
    persistgraphql: ['server', 'web'],
    "graphql-nats-subscriptions": 'server',
    "graphql-server-core": 'server',
    "graphql-server-express": 'server',
    "graphql-subscriptions": 'web',
    "graphql-tools": 'server',
    "helmet": 'server',
    "hemera-joi": 'server',
    "hemera-plugin": 'server',
    "immutability-helper": 'web',
    "inversify": 'server',
    "morgan": 'server',
    "nats": 'server',
    "nats-hemera":'server',
    "nconf": 'server',
    "node-pre-gyp": 'server',
    "prop-types": 'web',
    "ramda": "^0.25.0",
    "react": "^15.5.4",
    "react-apollo": 'web',
    "redux": "^3.6.0",
    "reflect-metadata": 'server',
    "sequelize": 'server',
    'react-dom': 'web',
    'react-helmet': 'web',
    'react-hot-loader': 'web',
    'react-native': ['ios', 'android'],
    'react-navigation': ['ios', 'android'],
    'react-redux': 'web',
    'react-router': 'web',
    'react-router-dom': 'web',
    reactstrap: 'web',
    'redux-devtools-extension': 'web',
    'redux-form': 'web',
    'serialize-javascript': 'server',
    'source-map-support': 'server',
    sqlite3: 'server',
    'styled-components': ['server', 'web'],
    'subscriptions-transport-ws': ['ios', 'android', 'web'],
    'ws': ['server']
};

module.exports = { server, web, android, ios, dependencyPlatforms };<commit_msg>udpated typo<commit_after>// App-specific back-end Webpack config should be here
const server = {
     entry: {
       index: [
        './src/setup/app.ts'
       ]
     }
};

// App-specific web front-end Webpack config should be here
const web = {
    entry: {
        index: [
            './src/index.tsx'
        ]
    }
};

// App-specific Android React Native front-end Webpack config should be here
const android = {
    //  entry: {
    //    'index.mobile.bundle': [
    //      require.resolve('./react-native-polyfill.js'),
    //      './src/mobile/index.js'
    //    ]
    //  }
};

// App-specific iOS React Native front-end Webpack config should be here
const ios = {
    //  entry: {
    //    'index.mobile.bundle': [
    //      require.resolve('./react-native-polyfill.js'),
    //      './src/mobile/index.js'
    //    ]
    //  }
};

const dependencyPlatforms = {
    "@cdm-logger/server": 'server',
    "bunyan": 'server',
    "export-dir": 'server',
    "express": 'server',
    'body-parser': 'server',
    express: 'server',
    'graphql-server-express': 'server',
    'graphql-subscriptions': 'server',
    'graphql-tools': 'server',
    "graphql-tag": ['server', 'web'],
    'immutability-helper': ['ios', 'android', 'web'],
    'isomorphic-fetch': 'server',
    knex: 'server',
    mysql2: 'server',
    persistgraphql: ['server', 'web'],
    "graphql-nats-subscriptions": 'server',
    "graphql-server-core": 'server',
    "graphql-server-express": 'server',
    "graphql-subscriptions": 'web',
    "graphql-tools": 'server',
    "helmet": 'server',
    "hemera-joi": 'server',
    "hemera-plugin": 'server',
    "immutability-helper": 'web',
    "inversify": 'server',
    "morgan": 'server',
    "nats": 'server',
    "nats-hemera":'server',
    "nconf": 'server',
    "node-pre-gyp": 'server',
    "prop-types": 'web',
    "ramda": ['web', 'server'],
    "react": "web",
    "react-apollo": 'web',
    "redux": "web",
    "reflect-metadata": 'server',
    "sequelize": 'server',
    'react-dom': 'web',
    'react-helmet': 'web',
    'react-hot-loader': 'web',
    'react-native': ['ios', 'android'],
    'react-navigation': ['ios', 'android'],
    'react-redux': 'web',
    'react-router': 'web',
    'react-router-dom': 'web',
    reactstrap: 'web',
    'redux-devtools-extension': 'web',
    'redux-form': 'web',
    'serialize-javascript': 'server',
    'source-map-support': 'server',
    sqlite3: 'server',
    'styled-components': ['server', 'web'],
    'subscriptions-transport-ws': ['ios', 'android', 'web'],
    'ws': ['server']
};

module.exports = { server, web, android, ios, dependencyPlatforms };<|endoftext|>


<commit_before><commit_msg>ensure only 1 disappearance timeout is active<commit_after><|endoftext|>


<commit_before><commit_msg>fix bug<commit_after><|endoftext|>


<commit_before>/**
 * Dashboard Details page stories.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import { storiesOf } from '@storybook/react';

/**
 * Internal dependencies
 */
import DashboardDetailsEntityNotFoundView from '../assets/js/components/dashboard-details/DashboardDetailsEntityNotFoundView';

storiesOf( 'Dashboard Details', module )
	.add( 'Not Found Entity', () => (
		<DashboardDetailsEntityNotFoundView permalink="https://example.com/test-page" />
	) )
;
<commit_msg>Add a storybook for an existing entity.<commit_after>/**
 * Dashboard Details page stories.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import { storiesOf } from '@storybook/react';

/**
 * Internal dependencies
 */
import { STORE_NAME as CORE_SITE } from '../assets/js/googlesitekit/datastore/site/constants';
import { STORE_NAME as CORE_USER } from '../assets/js/googlesitekit/datastore/user/constants';
import { WithTestRegistry } from '../tests/js/utils';
import DashboardDetailsApp from '../assets/js/components/dashboard-details/dashboard-details-app';
import DashboardDetailsEntityNotFoundView from '../assets/js/components/dashboard-details/DashboardDetailsEntityNotFoundView';

storiesOf( 'Dashboard Details', module )
	.add( 'Existing Entity', () => {
		global.featureFlags = {
			widgets: {
				pageDashboard: {
					enabled: false,
				},
			},
		};

		const setupRegistry = ( { dispatch } ) => {
			dispatch( CORE_SITE ).receiveSiteInfo( {
				usingProxy: true,
				proxySetupURL: 'https://sitekit.withgoogle.com/site-management/setup/',
				proxyPermissionsURL: 'https://sitekit.withgoogle.com/site-management/permissions/',
				adminURL: 'http://example.com/wp-admin/',
				referenceSiteURL: 'http://example.com',
				currentEntityTitle: 'Test Page',
				currentEntityURL: 'https://example.com/test-page',
				siteName: 'My Site Name',
			} );

			dispatch( CORE_USER ).receiveGetAuthentication( {
				authenticated: true,
				requiredScopes: [],
				grantedScopes: [],
			} );
		};

		return (
			<WithTestRegistry callback={ setupRegistry }>
				<DashboardDetailsApp />
			</WithTestRegistry>
		);
	} )
	.add( 'Not Found Entity', () => (
		<DashboardDetailsEntityNotFoundView permalink="https://example.com/test-page" />
	) )
;
<|endoftext|>


<commit_before><commit_msg>prevent IE9 issues by wrapping handler in try catch<commit_after><|endoftext|>


<commit_before><commit_msg>Remove hardcoded websocket connection.<commit_after><|endoftext|>


<commit_before>//Importing Data Models
var Student = require('./../models/student');

module.exports = function(app) {

    //CRUD for student
    app.get('/api/getStudents', function(req, res) {
        Student.find({}, function(err, data) {
            if (err) res.send(err);
            res.json(data);
        });
    });

    app.get('/api/getStudent/:uni', function(req, res) {
        Student.find({uni : req.params.uni}, function(err, data) {
            if (err) res.send(err);
            res.json(data);
        });
    });

    app.post('/api/createStudent', function(req, res) {
        console.log(req.body);

        Student.create({firstName:req.body.firstName, lastName:req.body.lastName, dob : new Date(req.body.dob), enrolled:req.body.enrolled,waitListed:req.body.waitListed}, function(err, data) {
            if (err) res.send(err);
            res.json(data);
        });
    });

    app.put('/api/updateStudent/:uni', function(req, res) {

    });

    app.delete('/api/deleteStudent/:uni', function(req, res) {

    });

    //ADMIN APIs

    //DataModel Changes API

    //Rest all requests
	app.get('/*', function(req, res){

		res.sendfile('public/html/home.html');

	});

};
<commit_msg>Basic crud complete<commit_after>//Importing Data Models
var Student = require('./../models/student');

module.exports = function(app) {

    //CRUD for student
    app.get('/api/getStudents', function(req, res) {
        Student.find({}, function(err, data) {
            if (err) res.send(err);
            res.json(data);
        });
    });

    app.get('/api/getStudent/:uni', function(req, res) {
        Student.find({uni : req.params.uni}, function(err, data) {
            if (err) res.send(err);
            res.json(data);
        });
    });

    app.post('/api/createStudent', function(req, res) {
        console.log(req.body);

        Student.create({firstName:req.body.firstName, lastName:req.body.lastName, dob : new Date(req.body.dob), enrolled:req.body.enrolled,waitListed:req.body.waitListed}, function(err, data) {
            if (err) res.send(err);
            res.json(data);
        });
    });

    app.put('/api/updateStudent/:uni', function(req, res) {
        //Data to be updated
        var newData = req.body.updatedData;
        newData['lastUpdated'] = new Date();

        Student.update({uni:req.params.uni},{$set: newData }, function(err,data) {
            if (err) res.send(err);
            res.json(data);
        });
    });

    app.delete('/api/deleteStudent/:uni', function(req, res) {
        Student.remove({uni:req.params.uni}, function(err,data) {
            if(err) res.send(err);
            res.json(data);
        });
    });

    //ADMIN APIs

    //DataModel Changes API

    //Rest all requests
	app.get('/*', function(req, res){

		res.sendfile('public/html/home.html');

	});

};
<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
 * analyze-css entry point
 *
 * @see https://github.com/macbre/analyze-css
 */
"use strict";

const { program } = require("commander");

var analyzer = require("./../lib/index"),
  debug = require("debug")("analyze-css:bin"),
  runner = require("./../lib/runner"),
  runnerOpts = {};

// parse options
program
  .version(analyzer.version)
  .usage("--url <url> [options]")
  // https://www.npmjs.com/package/commander#common-option-types-boolean-and-value
  .option("--url <url>", "Set URL of CSS to analyze")
  .option("--file <file>", "Set local CSS file to analyze")
  .option(
    "--ignore-ssl-errors",
    "Ignores SSL errors, such as expired or self-signed certificate errors"
  )
  .option("-p, --pretty", "Causes JSON with the results to be pretty-printed")
  .option(
    "-N, --no-offenders",
    "Show only the metrics without the offenders part"
  )
  .option(
    "--auth-user <user>",
    "Sets the user name used for HTTP authentication"
  )
  .option(
    "--auth-pass <pass>",
    "Sets the password used for HTTP authentication"
  )
  .option("-x, --proxy <proxy>", "Sets the HTTP proxy");

// parse it
program.parse(process.argv);

debug("analyze-css v%s", analyzer.version);
debug("argv %j", process.argv);
debug("opts %j", program.opts());

// support stdin (issue #28)
if (process.argv.indexOf("-") > -1) {
  runnerOpts.stdin = true;
}
// --url
else if (program.url) {
  runnerOpts.url = program.url;
}
// --file
else if (program.file) {
  runnerOpts.file = program.file;
}
// either --url or --file or - (stdin) needs to be provided
else {
  console.log(program.helpInformation());
  process.exitCode = analyzer.EXIT_NEED_OPTIONS;
  return;
}

runnerOpts.ignoreSslErrors = program["ignore-ssl-errors"];
runnerOpts.noOffenders = program.offenders === false;
runnerOpts.authUser = program["auth-user"];
runnerOpts.authPass = program["auth-pass"];
runnerOpts.proxy = program.proxy;

debug("opts: %j", runnerOpts);

// run the analyzer
runner(runnerOpts, function (err, res) {
  var output, exitCode;

  // emit an error and die
  if (err) {
    exitCode = err.code || 1;
    debug("Exiting with exit code #%d", exitCode);

    console.error(err.toString());
    process.exitCode = exitCode;
    return;
  }

  // make offenders flat (and append position if possible - issue #25)
  if (typeof res.offenders !== "undefined") {
    Object.keys(res.offenders).forEach(function (metricName) {
      res.offenders[metricName] = res.offenders[metricName].map(function (
        offender
      ) {
        var position = offender.position && offender.position.start;
        return (
          offender.message +
          (position ? " @ " + position.line + ":" + position.column : "")
        );
      });
    });
  }

  // format the results
  if (program.pretty === true) {
    output = JSON.stringify(res, null, "  ");
  } else {
    output = JSON.stringify(res);
  }

  process.stdout.write(output);
});
<commit_msg>Fix commander options handling + debug logging<commit_after>#!/usr/bin/env node

/**
 * analyze-css entry point
 *
 * @see https://github.com/macbre/analyze-css
 */
"use strict";

const { program } = require("commander");

var analyzer = require("./../lib/index"),
  debug = require("debug")("analyze-css:bin"),
  runner = require("./../lib/runner"),
  runnerOpts = {};

// parse options
program
  .version(analyzer.version)
  .usage("--url <url> [options]")
  // https://www.npmjs.com/package/commander#common-option-types-boolean-and-value
  .option("--url <url>", "Set URL of CSS to analyze")
  .option("--file <file>", "Set local CSS file to analyze")
  .option(
    "--ignore-ssl-errors",
    "Ignores SSL errors, such as expired or self-signed certificate errors"
  )
  .option("-p, --pretty", "Causes JSON with the results to be pretty-printed")
  .option(
    "-N, --no-offenders",
    "Show only the metrics without the offenders part"
  )
  .option(
    "--auth-user <user>",
    "Sets the user name used for HTTP authentication"
  )
  .option(
    "--auth-pass <pass>",
    "Sets the password used for HTTP authentication"
  )
  .option("-x, --proxy <proxy>", "Sets the HTTP proxy");

// parse it
program.parse(process.argv);
const options = program.opts();

debug("analyze-css v%s", analyzer.version);
debug("argv %j", process.argv);
debug("opts %j", options);

// support stdin (issue #28)
if (process.argv.indexOf("-") > -1) {
  runnerOpts.stdin = true;
}
// --url
else if (options.url) {
  runnerOpts.url = options.url;
}
// --file
else if (options.file) {
  runnerOpts.file = options.file;
}
// either --url or --file or - (stdin) needs to be provided
else {
  console.log(program.helpInformation());
  process.exitCode = analyzer.EXIT_NEED_OPTIONS;
  return;
}

runnerOpts.ignoreSslErrors = program["ignore-ssl-errors"];
runnerOpts.noOffenders = program.offenders === false;
runnerOpts.authUser = program["auth-user"];
runnerOpts.authPass = program["auth-pass"];
runnerOpts.proxy = program.proxy;

debug("runner opts: %j", runnerOpts);

// run the analyzer
runner(runnerOpts, function (err, res) {
  var output, exitCode;

  // emit an error and die
  if (err) {
    exitCode = err.code || 1;
    debug("Exiting with exit code #%d", exitCode);

    console.error(err.toString());
    process.exitCode = exitCode;
    return;
  }

  // make offenders flat (and append position if possible - issue #25)
  if (typeof res.offenders !== "undefined") {
    Object.keys(res.offenders).forEach(function (metricName) {
      res.offenders[metricName] = res.offenders[metricName].map(function (
        offender
      ) {
        var position = offender.position && offender.position.start;
        return (
          offender.message +
          (position ? " @ " + position.line + ":" + position.column : "")
        );
      });
    });
  }

  // format the results
  if (program.pretty === true) {
    output = JSON.stringify(res, null, "  ");
  } else {
    output = JSON.stringify(res);
  }

  process.stdout.write(output);
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs = require('fs'),
    file = process.argv[2];

function parse (stream) {
  var text = '';
  stream.resume();
  stream.on('data', function (chunk) { text += chunk; });
  stream.on('end', function () {
    console.log(text);
    var data = JSON.stringify({
          text: text,
          meta: { mode: 'read' }
        }),
        b64 = new Buffer(data).toString('base64');
    console.log('http://icetan.github.io/dr-markdown/v1/#base64/'+b64);
  });
}

if (file !== undefined) {
  parse(fs.createReadStream(file));
} else {
  parse(process.stdin);
}
<commit_msg>Removed debug output<commit_after>#!/usr/bin/env node

var fs = require('fs'),
    file = process.argv[2];

function parse (stream) {
  var text = '';
  stream.resume();
  stream.on('data', function (chunk) { text += chunk; });
  stream.on('end', function () {
    var data = JSON.stringify({
          text: text,
          meta: { mode: 'read' }
        }),
        b64 = new Buffer(data).toString('base64');
    console.log('http://icetan.github.io/dr-markdown/v1/#base64/'+b64);
  });
}

if (file !== undefined) {
  parse(fs.createReadStream(file));
} else {
  parse(process.stdin);
}
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2014 Glayzzle (BSD3 License)
 * @authors https://github.com/glayzzle/php-parser/graphs/contributors
 * @url http://glayzzle.com
 */

var fs      = require('fs');
var util 	= require('util');

module.exports = {
  handles: function(filename, ext) {
    return ext == '.php';
  }
  // runs the specified filename
  ,run: function(filename, engine) {
  	var ast = engine.parseCode(
  		fs.readFileSync(filename).toString()
  	);
  	if (engine.parser.debug) {
      console.log(
        util.inspect(
          ast, {
            showHidden: false,
            depth: 10,
            colors: true
          }
        )
      );
  	}
    if (ast[0] === 'program' && ast[1].length > 0) {
      console.log('v - Passed AST parsing');
      return true;
    } else {
      console.error('x - Warning : the AST tree is empty');
      return false;
    }
  }
};<commit_msg>avoid error if php document is really empty<commit_after>/**
 * Copyright (C) 2014 Glayzzle (BSD3 License)
 * @authors https://github.com/glayzzle/php-parser/graphs/contributors
 * @url http://glayzzle.com
 */

var fs      = require('fs');
var util 	= require('util');

module.exports = {
  handles: function(filename, ext) {
    return ext == '.php' || ext === '.phtml';
  }
  // runs the specified filename
  ,run: function(filename, engine) {
  	var ast = engine.parseCode(
  		fs.readFileSync(filename).toString()
  	);
  	if (engine.parser.debug) {
      console.log(
        util.inspect(
          ast, {
            showHidden: false,
            depth: 10,
            colors: true
          }
        )
      );
  	}
    if (ast[0] === 'program') {
      console.log('v - Passed AST parsing');
      return true;
    } else {
      console.error('x - Warning : the AST tree is empty');
      return false;
    }
  }
};<|endoftext|>