<commit_before>/*
 * Copyright (C) 2014 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

// @ts-nocheck
// TODO(crbug.com/1011811): Enable TypeScript compiler checks

export const HeapSnapshotProgressEvent = {
  Update: 'ProgressUpdate',
  BrokenSnapshot: 'BrokenSnapshot'
};

export const baseSystemDistance = 100000000;

/**
 * @unrestricted
 */
export class AllocationNodeCallers {
  /**
   * @param {!Array.<!SerializedAllocationNode>} nodesWithSingleCaller
   * @param {!Array.<!SerializedAllocationNode>} branchingCallers
   */
  constructor(nodesWithSingleCaller, branchingCallers) {
    /** @type {!Array.<!SerializedAllocationNode>} */
    this.nodesWithSingleCaller = nodesWithSingleCaller;
    /** @type {!Array.<!SerializedAllocationNode>} */
    this.branchingCallers = branchingCallers;
  }
}

/**
 * @unrestricted
 */
export class SerializedAllocationNode {
  /**
   * @param {number} nodeId
   * @param {string} functionName
   * @param {string} scriptName
   * @param {number} scriptId
   * @param {number} line
   * @param {number} column
   * @param {number} count
   * @param {number} size
   * @param {number} liveCount
   * @param {number} liveSize
   * @param {boolean} hasChildren
   */
  constructor(nodeId, functionName, scriptName, scriptId, line, column, count, size, liveCount, liveSize, hasChildren) {
    /** @type {number} */
    this.id = nodeId;
    /** @type {string} */
    this.name = functionName;
    /** @type {string} */
    this.scriptName = scriptName;
    /** @type {number} */
    this.scriptId = scriptId;
    /** @type {number} */
    this.line = line;
    /** @type {number} */
    this.column = column;
    /** @type {number} */
    this.count = count;
    /** @type {number} */
    this.size = size;
    /** @type {number} */
    this.liveCount = liveCount;
    /** @type {number} */
    this.liveSize = liveSize;
    /** @type {boolean} */
    this.hasChildren = hasChildren;
  }
}

/**
 * @unrestricted
 */
export class AllocationStackFrame {
  /**
   * @param {string} functionName
   * @param {string} scriptName
   * @param {number} scriptId
   * @param {number} line
   * @param {number} column
   */
  constructor(functionName, scriptName, scriptId, line, column) {
    /** @type {string} */
    this.functionName = functionName;
    /** @type {string} */
    this.scriptName = scriptName;
    /** @type {number} */
    this.scriptId = scriptId;
    /** @type {number} */
    this.line = line;
    /** @type {number} */
    this.column = column;
  }
}

/**
 * @unrestricted
 */
export class Node {
  /**
   * @param {number} id
   * @param {string} name
   * @param {number} distance
   * @param {number} nodeIndex
   * @param {number} retainedSize
   * @param {number} selfSize
   * @param {string} type
   */
  constructor(id, name, distance, nodeIndex, retainedSize, selfSize, type) {
    this.id = id;
    this.name = name;
    this.distance = distance;
    this.nodeIndex = nodeIndex;
    this.retainedSize = retainedSize;
    this.selfSize = selfSize;
    this.type = type;

    this.canBeQueried = false;
    this.detachedDOMTreeNode = false;
  }
}

/**
 * @unrestricted
 */
export class Edge {
  /**
   * @param {string} name
   * @param {!Node} node
   * @param {string} type
   * @param {number} edgeIndex
   */
  constructor(name, node, type, edgeIndex) {
    this.name = name;
    this.node = node;
    this.type = type;
    this.edgeIndex = edgeIndex;
  }
}

/**
 * @unrestricted
 */
export class Aggregate {
  constructor() {
    /** @type {number} */
    this.count;
    /** @type {number} */
    this.distance;
    /** @type {number} */
    this.self;
    /** @type {number} */
    this.maxRet;
    /** @type {number} */
    this.type;
    /** @type {string} */
    this.name;
    /** @type {!Array.<number>} */
    this.idxs;
  }
}

/**
 * @unrestricted
 */
export class AggregateForDiff {
  constructor() {
    /** @type {!Array.<number>} */
    this.indexes = [];
    /** @type {!Array.<string>} */
    this.ids = [];
    /** @type {!Array.<number>} */
    this.selfSizes = [];
  }
}

/**
 * @unrestricted
 */
export class Diff {
  constructor() {
    /** @type {number} */
    this.addedCount = 0;
    /** @type {number} */
    this.removedCount = 0;
    /** @type {number} */
    this.addedSize = 0;
    /** @type {number} */
    this.removedSize = 0;
    /** @type {!Array.<number>} */
    this.deletedIndexes = [];
    /** @type {!Array.<number>} */
    this.addedIndexes = [];
  }
}

/**
 * @unrestricted
 */
export class DiffForClass {
  constructor() {
    /** @type {number} */
    this.addedCount;
    /** @type {number} */
    this.removedCount;
    /** @type {number} */
    this.addedSize;
    /** @type {number} */
    this.removedSize;
    /** @type {!Array.<number>} */
    this.deletedIndexes;
    /** @type {!Array.<number>} */
    this.addedIndexes;

    /** @type {number} */
    this.countDelta;
    /** @type {number} */
    this.sizeDelta;
  }
}

/**
 * @unrestricted
 */
export class ComparatorConfig {
  constructor() {
    /** @type {string} */
    this.fieldName1;
    /** @type {boolean} */
    this.ascending1;
    /** @type {string} */
    this.fieldName2;
    /** @type {boolean} */
    this.ascending2;
  }
}

/**
 * @unrestricted
 */
export class WorkerCommand {
  constructor() {
    /** @type {number} */
    this.callId;
    /** @type {string} */
    this.disposition;
    /** @type {number} */
    this.objectId;
    /** @type {number} */
    this.newObjectId;
    /** @type {string} */
    this.methodName;
    /** @type {!Array.<*>} */
    this.methodArguments;
    /** @type {string} */
    this.source;
  }
}

/**
 * @unrestricted
 */
export class ItemsRange {
  /**
   * @param {number} startPosition
   * @param {number} endPosition
   * @param {number} totalLength
   * @param {!Array.<*>} items
   */
  constructor(startPosition, endPosition, totalLength, items) {
    /** @type {number} */
    this.startPosition = startPosition;
    /** @type {number} */
    this.endPosition = endPosition;
    /** @type {number} */
    this.totalLength = totalLength;
    /** @type {!Array.<*>} */
    this.items = items;
  }
}

/**
 * @unrestricted
 */
export class StaticData {
  /**
   * @param {number} nodeCount
   * @param {number} rootNodeIndex
   * @param {number} totalSize
   * @param {number} maxJSObjectId
   */
  constructor(nodeCount, rootNodeIndex, totalSize, maxJSObjectId) {
    /** @type {number} */
    this.nodeCount = nodeCount;
    /** @type {number} */
    this.rootNodeIndex = rootNodeIndex;
    /** @type {number} */
    this.totalSize = totalSize;
    /** @type {number} */
    this.maxJSObjectId = maxJSObjectId;
  }
}

/**
 * @unrestricted
 */
export class Statistics {
  constructor() {
    /** @type {number} */
    this.total;
    /** @type {number} */
    this.v8heap;
    /** @type {number} */
    this.native;
    /** @type {number} */
    this.code;
    /** @type {number} */
    this.jsArrays;
    /** @type {number} */
    this.strings;
    /** @type {number} */
    this.system;
  }
}

/**
 * @unrestricted
 */
export class NodeFilter {
  /**
   * @param {number=} minNodeId
   * @param {number=} maxNodeId
   */
  constructor(minNodeId, maxNodeId) {
    /** @type {number|undefined} */
    this.minNodeId = minNodeId;
    /** @type {number|undefined} */
    this.maxNodeId = maxNodeId;
    /** @type {number|undefined} */
    this.allocationNodeId;
  }

  /**
   * @param {!NodeFilter} o
   * @return {boolean}
   */
  equals(o) {
    return this.minNodeId === o.minNodeId && this.maxNodeId === o.maxNodeId &&
        this.allocationNodeId === o.allocationNodeId;
  }
}

/**
 * @unrestricted
 */
export class SearchConfig {
  /**
   * @param {string} query
   * @param {boolean} caseSensitive
   * @param {boolean} isRegex
   * @param {boolean} shouldJump
   * @param {boolean} jumpBackward
   */
  constructor(query, caseSensitive, isRegex, shouldJump, jumpBackward) {
    this.query = query;
    this.caseSensitive = caseSensitive;
    this.isRegex = isRegex;
    this.shouldJump = shouldJump;
    this.jumpBackward = jumpBackward;
  }
}

/**
 * @unrestricted
 */
export class Samples {
  /**
   * @param {!Array.<number>} timestamps
   * @param {!Array.<number>} lastAssignedIds
   * @param {!Array.<number>} sizes
   */
  constructor(timestamps, lastAssignedIds, sizes) {
    this.timestamps = timestamps;
    this.lastAssignedIds = lastAssignedIds;
    this.sizes = sizes;
  }
}

/**
 * @unrestricted
 */
export class Location {
  /**
   * @param {number} scriptId
   * @param {number} lineNumber
   * @param {number} columnNumber
   */
  constructor(scriptId, lineNumber, columnNumber) {
    this.scriptId = scriptId;
    this.lineNumber = lineNumber;
    this.columnNumber = columnNumber;
  }
}
<commit_msg>[TS] TypeScriptify HeapSnapshotModel<commit_after>/*
 * Copyright (C) 2014 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

export const HeapSnapshotProgressEvent = {
  Update: 'ProgressUpdate',
  BrokenSnapshot: 'BrokenSnapshot'
};

export const baseSystemDistance = 100000000;

/**
 * @unrestricted
 */
export class AllocationNodeCallers {
  /**
   * @param {!Array.<!SerializedAllocationNode>} nodesWithSingleCaller
   * @param {!Array.<!SerializedAllocationNode>} branchingCallers
   */
  constructor(nodesWithSingleCaller, branchingCallers) {
    /** @type {!Array.<!SerializedAllocationNode>} */
    this.nodesWithSingleCaller = nodesWithSingleCaller;
    /** @type {!Array.<!SerializedAllocationNode>} */
    this.branchingCallers = branchingCallers;
  }
}

/**
 * @unrestricted
 */
export class SerializedAllocationNode {
  /**
   * @param {number} nodeId
   * @param {string} functionName
   * @param {string} scriptName
   * @param {number} scriptId
   * @param {number} line
   * @param {number} column
   * @param {number} count
   * @param {number} size
   * @param {number} liveCount
   * @param {number} liveSize
   * @param {boolean} hasChildren
   */
  constructor(nodeId, functionName, scriptName, scriptId, line, column, count, size, liveCount, liveSize, hasChildren) {
    /** @type {number} */
    this.id = nodeId;
    /** @type {string} */
    this.name = functionName;
    /** @type {string} */
    this.scriptName = scriptName;
    /** @type {number} */
    this.scriptId = scriptId;
    /** @type {number} */
    this.line = line;
    /** @type {number} */
    this.column = column;
    /** @type {number} */
    this.count = count;
    /** @type {number} */
    this.size = size;
    /** @type {number} */
    this.liveCount = liveCount;
    /** @type {number} */
    this.liveSize = liveSize;
    /** @type {boolean} */
    this.hasChildren = hasChildren;
  }
}

/**
 * @unrestricted
 */
export class AllocationStackFrame {
  /**
   * @param {string} functionName
   * @param {string} scriptName
   * @param {number} scriptId
   * @param {number} line
   * @param {number} column
   */
  constructor(functionName, scriptName, scriptId, line, column) {
    /** @type {string} */
    this.functionName = functionName;
    /** @type {string} */
    this.scriptName = scriptName;
    /** @type {number} */
    this.scriptId = scriptId;
    /** @type {number} */
    this.line = line;
    /** @type {number} */
    this.column = column;
  }
}

/**
 * @unrestricted
 */
export class Node {
  /**
   * @param {number} id
   * @param {string} name
   * @param {number} distance
   * @param {number} nodeIndex
   * @param {number} retainedSize
   * @param {number} selfSize
   * @param {string} type
   */
  constructor(id, name, distance, nodeIndex, retainedSize, selfSize, type) {
    this.id = id;
    this.name = name;
    this.distance = distance;
    this.nodeIndex = nodeIndex;
    this.retainedSize = retainedSize;
    this.selfSize = selfSize;
    this.type = type;

    this.canBeQueried = false;
    this.detachedDOMTreeNode = false;
  }
}

/**
 * @unrestricted
 */
export class Edge {
  /**
   * @param {string} name
   * @param {!Node} node
   * @param {string} type
   * @param {number} edgeIndex
   */
  constructor(name, node, type, edgeIndex) {
    this.name = name;
    this.node = node;
    this.type = type;
    this.edgeIndex = edgeIndex;
  }
}

/**
 * @unrestricted
 */
export class Aggregate {
  constructor() {
    /** @type {number} */
    this.count;
    /** @type {number} */
    this.distance;
    /** @type {number} */
    this.self;
    /** @type {number} */
    this.maxRet;
    /** @type {number} */
    this.type;
    /** @type {string} */
    this.name;
    /** @type {!Array.<number>} */
    this.idxs;
  }
}

/**
 * @unrestricted
 */
export class AggregateForDiff {
  constructor() {
    /** @type {!Array.<number>} */
    this.indexes = [];
    /** @type {!Array.<string>} */
    this.ids = [];
    /** @type {!Array.<number>} */
    this.selfSizes = [];
  }
}

/**
 * @unrestricted
 */
export class Diff {
  constructor() {
    /** @type {number} */
    this.addedCount = 0;
    /** @type {number} */
    this.removedCount = 0;
    /** @type {number} */
    this.addedSize = 0;
    /** @type {number} */
    this.removedSize = 0;
    /** @type {!Array.<number>} */
    this.deletedIndexes = [];
    /** @type {!Array.<number>} */
    this.addedIndexes = [];
  }
}

/**
 * @unrestricted
 */
export class DiffForClass {
  constructor() {
    /** @type {number} */
    this.addedCount;
    /** @type {number} */
    this.removedCount;
    /** @type {number} */
    this.addedSize;
    /** @type {number} */
    this.removedSize;
    /** @type {!Array.<number>} */
    this.deletedIndexes;
    /** @type {!Array.<number>} */
    this.addedIndexes;

    /** @type {number} */
    this.countDelta;
    /** @type {number} */
    this.sizeDelta;
  }
}

/**
 * @unrestricted
 */
export class ComparatorConfig {
  constructor() {
    /** @type {string} */
    this.fieldName1;
    /** @type {boolean} */
    this.ascending1;
    /** @type {string} */
    this.fieldName2;
    /** @type {boolean} */
    this.ascending2;
  }
}

/**
 * @unrestricted
 */
export class WorkerCommand {
  constructor() {
    /** @type {number} */
    this.callId;
    /** @type {string} */
    this.disposition;
    /** @type {number} */
    this.objectId;
    /** @type {number} */
    this.newObjectId;
    /** @type {string} */
    this.methodName;
    /** @type {!Array.<*>} */
    this.methodArguments;
    /** @type {string} */
    this.source;
  }
}

/**
 * @unrestricted
 */
export class ItemsRange {
  /**
   * @param {number} startPosition
   * @param {number} endPosition
   * @param {number} totalLength
   * @param {!Array.<*>} items
   */
  constructor(startPosition, endPosition, totalLength, items) {
    /** @type {number} */
    this.startPosition = startPosition;
    /** @type {number} */
    this.endPosition = endPosition;
    /** @type {number} */
    this.totalLength = totalLength;
    /** @type {!Array.<*>} */
    this.items = items;
  }
}

/**
 * @unrestricted
 */
export class StaticData {
  /**
   * @param {number} nodeCount
   * @param {number} rootNodeIndex
   * @param {number} totalSize
   * @param {number} maxJSObjectId
   */
  constructor(nodeCount, rootNodeIndex, totalSize, maxJSObjectId) {
    /** @type {number} */
    this.nodeCount = nodeCount;
    /** @type {number} */
    this.rootNodeIndex = rootNodeIndex;
    /** @type {number} */
    this.totalSize = totalSize;
    /** @type {number} */
    this.maxJSObjectId = maxJSObjectId;
  }
}

/**
 * @unrestricted
 */
export class Statistics {
  constructor() {
    /** @type {number} */
    this.total;
    /** @type {number} */
    this.v8heap;
    /** @type {number} */
    this.native;
    /** @type {number} */
    this.code;
    /** @type {number} */
    this.jsArrays;
    /** @type {number} */
    this.strings;
    /** @type {number} */
    this.system;
  }
}

/**
 * @unrestricted
 */
export class NodeFilter {
  /**
   * @param {number=} minNodeId
   * @param {number=} maxNodeId
   */
  constructor(minNodeId, maxNodeId) {
    /** @type {number|undefined} */
    this.minNodeId = minNodeId;
    /** @type {number|undefined} */
    this.maxNodeId = maxNodeId;
    /** @type {number|undefined} */
    this.allocationNodeId;
  }

  /**
   * @param {!NodeFilter} o
   * @return {boolean}
   */
  equals(o) {
    return this.minNodeId === o.minNodeId && this.maxNodeId === o.maxNodeId &&
        this.allocationNodeId === o.allocationNodeId;
  }
}

/**
 * @unrestricted
 */
export class SearchConfig {
  /**
   * @param {string} query
   * @param {boolean} caseSensitive
   * @param {boolean} isRegex
   * @param {boolean} shouldJump
   * @param {boolean} jumpBackward
   */
  constructor(query, caseSensitive, isRegex, shouldJump, jumpBackward) {
    this.query = query;
    this.caseSensitive = caseSensitive;
    this.isRegex = isRegex;
    this.shouldJump = shouldJump;
    this.jumpBackward = jumpBackward;
  }
}

/**
 * @unrestricted
 */
export class Samples {
  /**
   * @param {!Array.<number>} timestamps
   * @param {!Array.<number>} lastAssignedIds
   * @param {!Array.<number>} sizes
   */
  constructor(timestamps, lastAssignedIds, sizes) {
    this.timestamps = timestamps;
    this.lastAssignedIds = lastAssignedIds;
    this.sizes = sizes;
  }
}

/**
 * @unrestricted
 */
export class Location {
  /**
   * @param {number} scriptId
   * @param {number} lineNumber
   * @param {number} columnNumber
   */
  constructor(scriptId, lineNumber, columnNumber) {
    this.scriptId = scriptId;
    this.lineNumber = lineNumber;
    this.columnNumber = columnNumber;
  }
}
<|endoftext|>


<commit_before>/*
 *  Minimal ES2015+ Promise polyfill
 *
 *  Limitations:
 *
 *    - Caller must manually call Promise.runQueue() to process pending jobs.
 *    - No Promise subclassing or non-subclass foreign Promises yet.
 *    - Promise.all() and Promise.race() assume a plain array, not iterator.
 *    - Doesn't handle errors from core operations, e.g. out-of-memory or
 *      internal error when queueing/running jobs.  These are implementation
 *      defined for the most part.
 *    - See XXX in source for more.
 *
 *  This polyfill was originally used to gain a better understanding of the
 *  ES2015 specification algorithms, before implementing Promises natively.
 *  As such this polyfill may not be production quality.
 *
 *  See also: https://github.com/stefanpenner/es6-promise#readme
 */

(function () {
    if ('Promise' in this) { return; }

    // Job queue to simulate ES2015 job queues, linked list, 'next' reference.
    // LIFO implementation, FIFO would probably be preferable by users.
    var queueHead = null;
    function queueJob(job) { job.next = queueHead; queueHead = job; }

    // Helper to define non-enumerable properties.
    function def(obj, key, val) {
        Object.defineProperty(obj, key, {
            value: val, writable: true, enumerable: false, configurable: true
        });
    }

    // Promise detection (plain or subclassed Promise), in spec has [[PromiseState]]
    // internal slot which isn't affected by Proxy behaviors etc.
    var symMarker = Symbol('promise');
    function isPromise(p) { return p !== null && typeof p === 'object' && symMarker in p; }
    function requirePromise(p) { if (!isPromise(p)) { throw new TypeError('Promise required'); } }

    // Raw fulfill/reject operations, assume resolution processing done.
    function doFulfill(p, val) {
        if (p.state !== void 0) { return; }  // should not happen
        p.state = true; p.value = val;
        var reactions = p.fulfillReactions;
        delete p.fulfillReactions; delete p.rejectReactions;
        reactions.forEach(function (r) {
            queueJob({ handler: r.handler, resolve: r.resolve, reject: r.reject, value: val });  // only value is new
        });
    }
    function doReject(p, val) {
        if (p.state !== void 0) { return; }  // should not happen
        p.state = false; p.value = val;
        var reactions = p.rejectReactions;
        delete p.fulfillReactions; delete p.rejectReactions;
        reactions.forEach(function (r) {
            queueJob({ handler: r.handler, resolve: r.resolve, reject: r.reject, value: val });  // only value is new
        });
    }

    // Create a new resolve/reject pair for a Promise.  Multiple pairs are
    // needed in thenable handling, with all but the most recent pair being
    // neutralized ('alreadyResolved').  Because Promises are resolved only
    // via this resolution process, it shouldn't be possible for the Promise
    // to be settled but check it anyway: it may be useful for e.g. the C API
    // to forcibly resolve/fulfill/reject a Promise regardless of extant
    // resolve/reject functions.
    function getResolutionFunctions(p) {
        var reject = function (err) {
            if (reject.state.alreadyResolved) { return; }
            reject.state.alreadyResolved = true;  // neutralize this resolve/reject pair
            if (p.state !== void 0) { return; }
            doReject(p, err);
        };
        var resolve = function (val) {
            if (resolve.state.alreadyResolved) { return; }
            resolve.state.alreadyResolved = true;  // neutralize this resolve/reject pair
            if (p.state !== void 0) { return; }
            if (val === p) { return doReject(p, new TypeError('self resolution')); }
            try {
                var then = (val !== null && typeof val === 'object' && val.then);
                if (typeof then === 'function') {
                    var t = getResolutionFunctions(p);
                    return queueJob({ thenable: val, then: then, resolve: t.resolve, reject: t.reject });
                    // old resolve/reject is neutralized, only the new pair is live
                }
                return doFulfill(p, val);
            } catch (e) {
                return doReject(p, e);
            }
        };
        reject.state = resolve.state = {};  // shared state for [[AlreadyResolved]]
        return { resolve: resolve, reject: reject };
    }

    // Job queue simulation.
    function runQueueEntry() {
        var res;
        if (!queueHead) { return false; }
        var job = queueHead; queueHead = job.next;
        if (!job) { return false; }
        if (job.then && job.resolve && job.reject) {
            try {
                void job.then.call(job.thenable, job.resolve, job.reject);
            } catch (e) {
                job.reject(e);
            }
        } else if (job.handler && job.resolve && job.reject) {
            try {
                if (job.handler === 'Identity') {
                    res = job.value;
                } else if (job.handler === 'Thrower') {
                    throw job.value;
                } else {
                    res = job.handler.call(void 0, job.value);
                }
                job.resolve(res);
            } catch (e) {
                job.reject(e);
            }
        } else {
            throw new Error('internal error');  // unknown job
        }
        return true;
    }

    // %Promise% constructor.
    var cons = function Promise(executor) {
        if (!new.target) { throw new TypeError('Promise must be called as a constructor'); }
        if (typeof executor !== 'function') { throw new TypeError('executor must be callable'); }
        var _this = this;
        this[symMarker] = true;
        def(this, 'state', void 0);   // undefined (pending), true (fulfilled), false (rejected)
        def(this, 'value', void 0);
        def(this, 'fulfillReactions', []);
        def(this, 'rejectReactions', []);
        var t = getResolutionFunctions(this);
        try {
            void executor(t.resolve, t.reject);
        } catch (e) {
            t.reject(e);
        }
    };
    var proto = cons.prototype;
    Object.defineProperty(cons, 'prototype', { writable: false, enumerable: false, configurable: false });

    // %Promise%.then(), also used for .catch().
    function then(onFulfilled, onRejected) {
        // No subclassing support here now, no NewPromiseCapability() handling.
        requirePromise(this);
        var resolveFn, rejectFn;
        var p = new Promise(function (resolve, reject) { resolveFn = resolve; rejectFn = reject; });
        onFulfilled = (typeof onFulfilled === 'function' ? onFulfilled : 'Identity');
        onRejected = (typeof onRejected === 'function' ? onRejected : 'Thrower');
        if (this.state === void 0) {  // pending
            this.fulfillReactions.push({ handler: onFulfilled, resolve: resolveFn, reject: rejectFn });
            this.rejectReactions.push({ handler: onRejected, resolve: resolveFn, reject: rejectFn });
        } else if (this.state) {  // fulfilled
            queueJob({ handler: onFulfilled, resolve: resolveFn, reject: rejectFn, value: this.value });
        } else {  // rejected
            queueJob({ handler: onRejected, resolve: resolveFn, reject: rejectFn, value: this.value });
        }
        return p;
    }

    // %Promise%.all().
    function all(list) {
        var resolveFn, rejectFn;
        var p = new Promise(function (resolve, reject) { resolveFn = resolve; rejectFn = reject; });
        var state = { values: [], remaining: 1, resolve: resolveFn, reject: rejectFn };  // remaining intentionally 1, not 0
        var index = 0;
        list.forEach(function (x) {  // XXX: no iterator support
            var t = Promise.resolve(x);
            var f = function promiseAllElement(val) {
                var F = promiseAllElement;
                var S = F.state;
                if (F.alreadyCalled) { return; }
                F.alreadyCalled = true;
                S.values[F.index] = val;
                if (--S.remaining === 0) {
                    S.resolve.call(void 0, S.values);
                }
            }
            f.state = state;
            f.index = index++;
            state.remaining++;
            t.then(f, rejectFn);
        });
        if (--state.remaining === 0) {
            resolveFn.call(void 0, state.values);
        }
        return p;
    }

    // %Promise%.race().
    function race(list) {
        var resolveFn, rejectFn;
        var p = new Promise(function (resolve, reject) { resolveFn = resolve; rejectFn = reject; });
        list.forEach(function (x) {  // XXX: no iterator support
            var t = Promise.resolve(x);
            t.then(resolveFn, rejectFn);
        });
        return p;
    }

    // %Promise%.try(), https://github.com/tc39/proposal-promise-try,
    // simple polyfill-style implementation.
    function _try(func) {
        // XXX: check 'this' for callability, or Promise / subclass.
        return new this(function (resolve, reject) { resolve(func()); });
    }

    // Define visible objects and properties.
    (function () {
        def(this, 'Promise', cons);
        def(cons, 'resolve', function resolve(val) {  // XXX: direct handling
            if (isPromise(val) && val.constructor === this) { return val; }
            return new Promise(function (resolve, reject) { resolve(val); });
        });
        def(cons, 'reject', function reject(val) {  // XXX: direct handling
            return new Promise(function (resolve, reject) { reject(val); });
        });
        def(cons, 'all', all);
        def(cons, 'race', race);
        def(cons, 'try', _try);  // XXX: name should be 'try'
        def(proto, 'then', then);
        def(proto, 'catch', function _catch(onRejected) {  // XXX: name should be 'catch'
            return this.then.call(this, void 0, onRejected);
        });
        def(proto, Symbol.toStringTag, 'Promise');

        // Not part of the actual Promise API, but used to drive the "job queue".
        def(cons, 'runQueue', function _runQueueUntilEmpty() {
            while (runQueueEntry()) {}
        });
    }());
}());
<commit_msg>Fix Promise polyfill FIFO ordering<commit_after>/*
 *  Minimal ES2015+ Promise polyfill
 *
 *  Limitations:
 *
 *    - Caller must manually call Promise.runQueue() to process pending jobs.
 *    - No Promise subclassing or non-subclass foreign Promises yet.
 *    - Promise.all() and Promise.race() assume a plain array, not iterator.
 *    - Doesn't handle errors from core operations, e.g. out-of-memory or
 *      internal error when queueing/running jobs.  These are implementation
 *      defined for the most part.
 *    - See XXX in source for more.
 *
 *  This polyfill was originally used to gain a better understanding of the
 *  ES2015 specification algorithms, before implementing Promises natively.
 *  As such this polyfill may not be production quality.
 *
 *  See also: https://github.com/stefanpenner/es6-promise#readme
 */

(function () {
    if ('Promise' in this) { return; }

    // Job queue to simulate ES2015 job queues, linked list, 'next' reference.
    // While ES2015 doesn't guarantee the relative order of jobs in different
    // job queues, within a certain queue strict FIFO is required.  See ES5.1
    // https://www.ecma-international.org/ecma-262/6.0/#sec-jobs-and-job-queues:
    // "The PendingJob records from a single Job Queue are always initiated in
    // FIFO order. This specification does not define the order in which multiple
    // Job Queues are serviced."
    var queueHead = null;
    var queueTail = null;
    function queueJob(job) {
        if (queueHead) {
            queueTail.next = job;
            queueTail = job;
        } else {
            queueHead = queueTail = job;
        }
    }
    function unqueueJob() {
        var ret = queueHead;
        if (ret) {
            queueHead = ret.next;
            if (!queueHead) {
                queueTail = null;
            }
        }
        return ret;
    }

    // Helper to define non-enumerable properties.
    function def(obj, key, val) {
        Object.defineProperty(obj, key, {
            value: val, writable: true, enumerable: false, configurable: true
        });
    }

    // Promise detection (plain or subclassed Promise), in spec has [[PromiseState]]
    // internal slot which isn't affected by Proxy behaviors etc.
    var symMarker = Symbol('promise');
    function isPromise(p) { return p !== null && typeof p === 'object' && symMarker in p; }
    function requirePromise(p) { if (!isPromise(p)) { throw new TypeError('Promise required'); } }

    // Raw fulfill/reject operations, assume resolution processing done.
    function doFulfill(p, val) {
        if (p.state !== void 0) { return; }  // should not happen
        p.state = true; p.value = val;
        var reactions = p.fulfillReactions;
        delete p.fulfillReactions; delete p.rejectReactions;
        reactions.forEach(function (r) {
            queueJob({ handler: r.handler, resolve: r.resolve, reject: r.reject, value: val });  // only value is new
        });
    }
    function doReject(p, val) {
        if (p.state !== void 0) { return; }  // should not happen
        p.state = false; p.value = val;
        var reactions = p.rejectReactions;
        delete p.fulfillReactions; delete p.rejectReactions;
        reactions.forEach(function (r) {
            queueJob({ handler: r.handler, resolve: r.resolve, reject: r.reject, value: val });  // only value is new
        });
    }

    // Create a new resolve/reject pair for a Promise.  Multiple pairs are
    // needed in thenable handling, with all but the most recent pair being
    // neutralized ('alreadyResolved').  Because Promises are resolved only
    // via this resolution process, it shouldn't be possible for the Promise
    // to be settled but check it anyway: it may be useful for e.g. the C API
    // to forcibly resolve/fulfill/reject a Promise regardless of extant
    // resolve/reject functions.
    function getResolutionFunctions(p) {
        var reject = function (err) {
            if (reject.state.alreadyResolved) { return; }
            reject.state.alreadyResolved = true;  // neutralize this resolve/reject pair
            if (p.state !== void 0) { return; }
            doReject(p, err);
        };
        var resolve = function (val) {
            if (resolve.state.alreadyResolved) { return; }
            resolve.state.alreadyResolved = true;  // neutralize this resolve/reject pair
            if (p.state !== void 0) { return; }
            if (val === p) { return doReject(p, new TypeError('self resolution')); }
            try {
                var then = (val !== null && typeof val === 'object' && val.then);
                if (typeof then === 'function') {
                    var t = getResolutionFunctions(p);
                    return queueJob({ thenable: val, then: then, resolve: t.resolve, reject: t.reject });
                    // old resolve/reject is neutralized, only the new pair is live
                }
                return doFulfill(p, val);
            } catch (e) {
                return doReject(p, e);
            }
        };
        reject.state = resolve.state = {};  // shared state for [[AlreadyResolved]]
        return { resolve: resolve, reject: reject };
    }

    // Job queue simulation.
    function runQueueEntry() {
        var job = unqueueJob();
        if (!job) { return false; }
        if (job.then && job.resolve && job.reject) {
            try {
                void job.then.call(job.thenable, job.resolve, job.reject);
            } catch (e) {
                job.reject(e);
            }
        } else if (job.handler && job.resolve && job.reject) {
            try {
                if (job.handler === 'Identity') {
                    res = job.value;
                } else if (job.handler === 'Thrower') {
                    throw job.value;
                } else {
                    res = job.handler.call(void 0, job.value);
                }
                job.resolve(res);
            } catch (e) {
                job.reject(e);
            }
        } else {
            throw new Error('internal error');  // unknown job
        }
        return true;
    }

    // %Promise% constructor.
    var cons = function Promise(executor) {
        if (!new.target) { throw new TypeError('Promise must be called as a constructor'); }
        if (typeof executor !== 'function') { throw new TypeError('executor must be callable'); }
        var _this = this;
        this[symMarker] = true;
        def(this, 'state', void 0);   // undefined (pending), true (fulfilled), false (rejected)
        def(this, 'value', void 0);
        def(this, 'fulfillReactions', []);
        def(this, 'rejectReactions', []);
        var t = getResolutionFunctions(this);
        try {
            void executor(t.resolve, t.reject);
        } catch (e) {
            t.reject(e);
        }
    };
    var proto = cons.prototype;
    Object.defineProperty(cons, 'prototype', { writable: false, enumerable: false, configurable: false });

    // %Promise%.then(), also used for .catch().
    function then(onFulfilled, onRejected) {
        // No subclassing support here now, no NewPromiseCapability() handling.
        requirePromise(this);
        var resolveFn, rejectFn;
        var p = new Promise(function (resolve, reject) { resolveFn = resolve; rejectFn = reject; });
        onFulfilled = (typeof onFulfilled === 'function' ? onFulfilled : 'Identity');
        onRejected = (typeof onRejected === 'function' ? onRejected : 'Thrower');
        if (this.state === void 0) {  // pending
            this.fulfillReactions.push({ handler: onFulfilled, resolve: resolveFn, reject: rejectFn });
            this.rejectReactions.push({ handler: onRejected, resolve: resolveFn, reject: rejectFn });
        } else if (this.state) {  // fulfilled
            queueJob({ handler: onFulfilled, resolve: resolveFn, reject: rejectFn, value: this.value });
        } else {  // rejected
            queueJob({ handler: onRejected, resolve: resolveFn, reject: rejectFn, value: this.value });
        }
        return p;
    }

    // %Promise%.all().
    function all(list) {
        var resolveFn, rejectFn;
        var p = new Promise(function (resolve, reject) { resolveFn = resolve; rejectFn = reject; });
        var state = { values: [], remaining: 1, resolve: resolveFn, reject: rejectFn };  // remaining intentionally 1, not 0
        var index = 0;
        list.forEach(function (x) {  // XXX: no iterator support
            var t = Promise.resolve(x);
            var f = function promiseAllElement(val) {
                var F = promiseAllElement;
                var S = F.state;
                if (F.alreadyCalled) { return; }
                F.alreadyCalled = true;
                S.values[F.index] = val;
                if (--S.remaining === 0) {
                    S.resolve.call(void 0, S.values);
                }
            }
            f.state = state;
            f.index = index++;
            state.remaining++;
            t.then(f, rejectFn);
        });
        if (--state.remaining === 0) {
            resolveFn.call(void 0, state.values);
        }
        return p;
    }

    // %Promise%.race().
    function race(list) {
        var resolveFn, rejectFn;
        var p = new Promise(function (resolve, reject) { resolveFn = resolve; rejectFn = reject; });
        list.forEach(function (x) {  // XXX: no iterator support
            var t = Promise.resolve(x);
            t.then(resolveFn, rejectFn);
        });
        return p;
    }

    // %Promise%.try(), https://github.com/tc39/proposal-promise-try,
    // simple polyfill-style implementation.
    function _try(func) {
        // XXX: check 'this' for callability, or Promise / subclass.
        return new this(function (resolve, reject) { resolve(func()); });
    }

    // Define visible objects and properties.
    (function () {
        def(this, 'Promise', cons);
        def(cons, 'resolve', function resolve(val) {  // XXX: direct handling
            if (isPromise(val) && val.constructor === this) { return val; }
            return new Promise(function (resolve, reject) { resolve(val); });
        });
        def(cons, 'reject', function reject(val) {  // XXX: direct handling
            return new Promise(function (resolve, reject) { reject(val); });
        });
        def(cons, 'all', all);
        def(cons, 'race', race);
        def(cons, 'try', _try);  // XXX: name should be 'try'
        def(proto, 'then', then);
        def(proto, 'catch', function _catch(onRejected) {  // XXX: name should be 'catch'
            return this.then.call(this, void 0, onRejected);
        });
        def(proto, Symbol.toStringTag, 'Promise');

        // Not part of the actual Promise API, but used to drive the "job queue".
        def(cons, 'runQueue', function _runQueueUntilEmpty() {
            while (runQueueEntry()) {}
        });
    }());
}());
<|endoftext|>


<commit_before>const aws = require('aws-sdk');
const Maybe = require('liftjs').Maybe;

module.exports = (log, region) => {
  return new Promise((resolve, reject) => {
    var cf = new aws.CloudFormation({ region: region });
    cf.listStacks({}, function (error, data) {
      if (error) {
        reject(error);
      }
      data.StackSummaries
        .filter(s => s.StackStatus != 'DELETE_COMPLETE')
        .map(s => { return { name: s.StackName, status: s.StackStatus }; })
        .map(s => `${s.name}  ${s.status}`)
        .map(log.cyan);
    });
  });
};<commit_msg>removed unused promise<commit_after>const aws = require('aws-sdk');
const Maybe = require('liftjs').Maybe;

module.exports = (log, region) => {
  var cf = new aws.CloudFormation({ region: region });
  cf.listStacks({}, function (error, data) {
    if (error) {
      reject(error);
    }
    data && data.StackSummaries && data.StackSummaries
      .filter(s => s.StackStatus != 'DELETE_COMPLETE')
      .map(s => { return { name: s.StackName, status: s.StackStatus }; })
      .map(s => `${s.name}  ${s.status}`)
      .map(log.cyan);
  });
};<|endoftext|>


<commit_before>var CronJob = require('cron').CronJob;
var request = require("request");
var mongoose = require("mongoose");
mongoose.Promise = require('bluebird');

var url = "https://poloniex.com/public?command=returnTicker";

var mongodbUri = "mongodb://localhost/jpdanta";
var mongodbOptions = {
  useMongoClient: true,
  socketTimeoutMS: 0,
  keepAlive: true,
  reconnectTries: 30
};

function log(msg) {
    var date = new Date();
    console.log(date.toLocaleString() + " " + msg);
}

function transform_ticker(whenFetched, tickerjson) {
    var t_ticker = [];
//    var colnames = ["", "last", "lowestAsk", "highestBid", "percentChange", "baseVolume", "quoteVolume", "high24hr", "low24hr"]
    var colnames = ["", "last", "lowestAsk", "highestBid"]

    // var coinids = [];
    // var measureids = [];

    // colnames.forEach(function(value, x) {
    //     if (value != "") {
    //         measureids.push({"id": x, "name": value});
    //     }
    // });

    for (var i in tickerjson) {
        // per coin
        // coinids.push({"id": tickerjson[i]["id"], "name": i});
        colnames.forEach(function (value, x) {
            if (value != "") {
                t_ticker.push({
                    a: tickerjson[i]["id"], // coin id
                    b: x, // measure
                    c: tickerjson[i][value], // value
                    d: whenFetched // whenFetched
                });

            }
        });
    }

    // {
    //     var fs = require('fs');
    //     console.log(measureids);
    //     console.log(coinids);
    //     fs.writeFileSync("measureids.txt", JSON.stringify(measureids));
    //     fs.writeFileSync("coinids.txt", JSON.stringify(coinids));
    // }
    return t_ticker;
}

var Schema = mongoose.Schema;
var tickerSchema = new Schema({
    a: {
        type: Number,
        required: true
    },
    b: {
        type: Number,
        required: true
    },
    c: {
        type: Number,
        required: true
    },
    d: {
        type: Date,
        required: true
    },
});

module.exports = mongoose.model('ticker', tickerSchema);

function requestfn(error, response, body) {
    // log("got into response");
    if (error) {
        throw error;
    }
    var date = new Date();
    var ticker2 = transform_ticker(date, JSON.parse(body));

    var db = mongoose.connection;
    // db.on('error', console.error);
    // db.once('open', function () {
    //     //console.log("Connected to mongodb");
    // });

    mongoose.connect(mongodbUri, mongodbOptions);
    // log("mongoose connected");
    var Ticker = mongoose.model('ticker', tickerSchema);

    ticker2.forEach(function (aTicker, x) {
        var aTickerObj = new Ticker(aTicker);
        aTickerObj.save(function (err, doc) {
            if (err) throw err;
        });
    });

    mongoose.disconnect();
    // log("mongoose disconnected");
}

new CronJob('*/3 * * * * *', function () {
    // log("start");
    request(url, requestfn);
    // log("finish");
}, null, true);<commit_msg>change error export method<commit_after>var CronJob = require('cron').CronJob;
var request = require("request");
var mongoose = require("mongoose");
mongoose.Promise = require('bluebird');

var url = "https://poloniex.com/public?command=returnTicker";

var mongodbUri = "mongodb://localhost/jpdanta";
var mongodbOptions = {
  useMongoClient: true,
  socketTimeoutMS: 0,
  keepAlive: true,
  reconnectTries: 30
};

function log(msg) {
    var date = new Date();
    console.log(date.toLocaleString() + " " + msg);
}

function transform_ticker(whenFetched, tickerjson) {
    var t_ticker = [];
//    var colnames = ["", "last", "lowestAsk", "highestBid", "percentChange", "baseVolume", "quoteVolume", "high24hr", "low24hr"]
    var colnames = ["", "last", "lowestAsk", "highestBid"]

    // var coinids = [];
    // var measureids = [];

    // colnames.forEach(function(value, x) {
    //     if (value != "") {
    //         measureids.push({"id": x, "name": value});
    //     }
    // });

    for (var i in tickerjson) {
        // per coin
        // coinids.push({"id": tickerjson[i]["id"], "name": i});
        colnames.forEach(function (value, x) {
            if (value != "") {
                t_ticker.push({
                    a: tickerjson[i]["id"], // coin id
                    b: x, // measure
                    c: tickerjson[i][value], // value
                    d: whenFetched // whenFetched
                });

            }
        });
    }

    // {
    //     var fs = require('fs');
    //     console.log(measureids);
    //     console.log(coinids);
    //     fs.writeFileSync("measureids.txt", JSON.stringify(measureids));
    //     fs.writeFileSync("coinids.txt", JSON.stringify(coinids));
    // }
    return t_ticker;
}

var Schema = mongoose.Schema;
var tickerSchema = new Schema({
    a: {
        type: Number,
        required: true
    },
    b: {
        type: Number,
        required: true
    },
    c: {
        type: Number,
        required: true
    },
    d: {
        type: Date,
        required: true
    },
});

module.exports = mongoose.model('ticker', tickerSchema);

function requestfn(error, response, body) {
    // log("got into response");
    if (error) {
        console.error(error);
    }
    var date = new Date();
    var ticker2 = transform_ticker(date, JSON.parse(body));

    var db = mongoose.connection;
    // db.on('error', console.error);
    // db.once('open', function () {
    //     //console.log("Connected to mongodb");
    // });

    mongoose.connect(mongodbUri, mongodbOptions);
    // log("mongoose connected");
    var Ticker = mongoose.model('ticker', tickerSchema);

    ticker2.forEach(function (aTicker, x) {
        var aTickerObj = new Ticker(aTicker);
        aTickerObj.save(function (err, doc) {
            if (err) throw err;
        });
    });

    mongoose.disconnect();
    // log("mongoose disconnected");
}

new CronJob('*/3 * * * * *', function () {
    // log("start");
    request(url, requestfn);
    // log("finish");
}, null, true);<|endoftext|>


<commit_before>'use strict'

import React, {
  Component,
  DatePickerAndroid,
  Image,
  StyleSheet,
  Switch,
  Text,
  TextInput,
  TouchableWithoutFeedback,
  TimePickerAndroid,
  View
} from 'react-native';

import Button from '../components/button';
import Header from '../components/header';

import ButtonStyles from '../styles/button-styles';

class CreateEvent extends Component {

  constructor(props) {
    super(props);
    this.state = {
      loaded: true,

      title: '',
      publicEvent: true,
      dateStart: 'pick a start date',
      dateEnd: 'pick an end date',
      timeStart: 'pick a start time',
      timeEnd: 'pick an end time',
      description: ''
    }
  }

  async showDatePicker(stateKey, options, start) {
    try {
      var newState = {};
      var tempDate = new Date();
      var tempDateStr = tempDate.toLocaleDateString();
      const {action, year, month, day} = await DatePickerAndroid.open(options);

      if (action === DatePickerAndroid.dismissedAction) {
        if(start) {
          tempDateStr = this.state.dateStart;
        } else {
          tempDateStr = this.state.dateEnd;
        }
      } else {
        tempDate = new Date(year, month, day);
        tempDateStr = tempDate.toLocaleDateString();
      }
      if(start) {
        this.setState({dateStart: tempDateStr});
      } else {
        this.setState({dateEnd: tempDateStr});
      }
    } catch ({code, message}) {
      console.warn(`Error in example '${stateKey}': `, message);
    }
  }

  async showTimePicker(stateKey, start) {
    try {
      const {action, m, h} = await TimePickerAndroid.open();
      tempMin = m;
      tempHour = h;
      var tempTimeStr = '';

      if (action === TimePickerAndroid.dismissedAction) {
        if(start) {
          tempTimeStr = this.state.timeStart;
        } else {
          tempTimeStr = this.state.timeEnd;
        }
      } else if(action === TimePickerAndroid.timeSetAction){
        alert('poo');
        tempTimeStr = this.formatTime(h, m);

      }
      if(start) {
        this.setState({timeStart: tempTimeStr});
      } else {
        this.setState({timeEnd: tempTimeStr});
      }
    } catch ({code, message}) {
      console.warn(`Error in example '${stateKey}': `, message);
    }
  }

  formatTime(hour, minute) {
    return hour + ':' + (minute < 10 ? '0' + minute : minute);
  }

  render(){
    return(
      <View style = {{flex: 1}}>
        {this.renderPageTitle()}
        {this.renderToggle()}
        {this.renderTitleInput()}
        {this.renderDateTimeInput()}
        {this.renderDescriptionInput()}
        {this.renderButtons()}
      </View>
    );
  }

  renderPageTitle(){
    return(
      <Header
        navigator = {this.props.navigator}
        text = "Create a New Event"
        hasBack = {true}
      />
    );
  }

  renderToggle(){
    return(
      <View style = {{flexDirection:'row'}}>
        <Switch
          onTintColor = "#0000ff"
          onValueChange = {(value) => this.setState({publicEvent: value})}
          style = {{marginBottom: 10}}
          value = {this.state.publicEvent}
        />
        <Text>
          {this.state.publicEvent ? ' Public Event' : 'Private Event'}
        </Text>
      </View>
    );
  }

  renderTitleInput(){
    return(
      <TextInput
        blurOnSubmit = {true}
        onChangeText = {(text) => this.setState({title: text})}
        value = {this.state.title}
        placeholder = {"Give Your Event a Title."}
        placeholderTextColor = 'black'
        underlineColorAndroid = 'black'
      />
    );
  }

  renderDateTimeInput(){
    return (
      <View>

        <Text style = {{color:'white'}}>
          Start:
        </Text>

        <View style = {{ flexDirection:'row'}}>
          <TouchableWithoutFeedback onPress = {
            this.showDatePicker.bind(this, 'min', {
              date: this.state.minDate,
              minDate: new Date(),
            }, true)
          }>
            <Text style = {{color:'black'}}>
              {this.state.dateStart}
            </Text>
          </TouchableWithoutFeedback>

          <TouchableWithoutFeedback
            onPress = {this.showTimePicker.bind(this, true)}>
            <Text style = {{color:'black'}}>{this.state.timeStart}</Text>
          </TouchableWithoutFeedback>

        </View>

        <Text style = {{color:'white'}}>
          End:
        </Text>
        <View style = {{ flexDirection:'row'}}>
          <View style = {{ flexDirection:'row'}}>
            <TouchableWithoutFeedback onPress = {
              this.showDatePicker.bind(this, 'min', {
                date: this.state.minDate,
                minDate: new Date(this.state.dateStart),
              }, false )
            }>
              <Text style = {{color:'black'}}>
                {this.state.dateEnd}
              </Text>
            </TouchableWithoutFeedback>
          </View>
        </View>
      </View>
    );
  }

  renderDescriptionInput(){
    var limit = 100;
    var remainder = limit - this.state.description.length;
    var remainderColor = remainder > 5 ? 'blue' : 'red';

    return (
      <View>
        <TextInput
          maxLength = {limit}
          multiline = {true}
          style = {Header.body, {color:'black'}}
          onChangeText = {(text) => this.setState({description: text})}
          value = {this.state.description}
          placeholder = {"Leave a short description of your event for your guests:"}
          placeholderTextColor = 'black'
          underlineColorAndroid = 'black'
        />
        <Text style = {{color: remainderColor}}>
          {remainder}
        </Text>
      </View>
    );
  }

  renderButtons(){
    return (
      <View style = {{alignItems: 'center'}}>
        <Button
          text = "Invite Friends!"
          onPress = {this.createGuestList.bind(this)}
          button_styles = {ButtonStyles.primary_button}
          button_text_styles = {ButtonStyles.primary_button_text}
        />

        <Button
          text = "Create Event!"
          onPress = {this.createEvent.bind(this)}
          button_styles = {ButtonStyles.primary_button}
          button_text_styles = {ButtonStyles.primary_button_text}
        />

      <Button
        text = "Clear"
        onPress = {this.clearEvent.bind(this)}
        button_styles = {ButtonStyles.primary_button}
        button_text_styles = {ButtonStyles.primary_button_text}
      />

    </View>
    );
  }

  createGuestList(){
    alert('friends list unimplemented')
  }

  createEvent(){

    alert(this.state.title)
    alert('this event is a public event: ' + this.state.publicEvent);
    alert('start: ' + this.state.dateStart + ' end: ' + this.state.dateEnd);
    alert(this.state.description);
  }

  clearEvent(){
    alert('Cleared :(');
    this.setState({
      title: '',
      publicEvent: true,
      dateStart: 'pick a start date',
      dateEnd: 'pick an end date',
      timeStart: 'pick a start time',
      timeEnd: 'pick an end time',
      description: ''
    })

  }
}

module.exports = CreateEvent;
<commit_msg>fixed the start time to appear on the app<commit_after>'use strict'

import React, {
  Component,
  DatePickerAndroid,
  Image,
  StyleSheet,
  Switch,
  Text,
  TextInput,
  TouchableWithoutFeedback,
  TimePickerAndroid,
  View
} from 'react-native';

import Button from '../components/button';
import Header from '../components/header';

import ButtonStyles from '../styles/button-styles';

class CreateEvent extends Component {

  constructor(props) {
    super(props);
    this.state = {
      loaded: true,

      title: '',
      publicEvent: true,
      dateStart: 'pick a start date',
      dateEnd: 'pick an end date',
      timeStart: 'pick a start time',
      timeEnd: 'pick an end time',
      description: ''
    }
  }

  async showDatePicker(stateKey, options, start) {
    try {
      var newState = {};
      var tempDate = new Date();
      var tempDateStr = tempDate.toLocaleDateString();
      const {action, year, month, day} = await DatePickerAndroid.open(options);

      if (action === DatePickerAndroid.dismissedAction) {
        if(start) {
          tempDateStr = this.state.dateStart;
        } else {
          tempDateStr = this.state.dateEnd;
        }
      } else {
        tempDate = new Date(year, month, day);
        tempDateStr = tempDate.toLocaleDateString();
      }
      if(start) {
        this.setState({dateStart: tempDateStr});
      } else {
        this.setState({dateEnd: tempDateStr});
      }
    } catch ({code, message}) {
      console.warn(`Error in example '${stateKey}': `, message);
    }
  }

  async showTimePicker(stateKey, start) {
    var tempMin, tempHour;
    try {
      const {action, minute, hour} = await TimePickerAndroid.open();
      tempMin = minute;
      tempHour = hour;
      var tempTimeStr = '';

      if (action === TimePickerAndroid.dismissedAction) {
        if(start) {
          tempTimeStr = this.state.timeStart;
        } else {
          tempTimeStr = this.state.timeEnd;
        }
      } else if(action === TimePickerAndroid.timeSetAction){
        tempTimeStr = this.formatTime(hour, minute);

      }
      if(start) {
        this.setState({timeStart: tempTimeStr});
      } else {
        this.setState({timeEnd: tempTimeStr});
      }
    } catch ({code, message}) {
      console.warn(`Error in example '${stateKey}': `, message);
    }
  }

  formatTime(hour, minute) {
    return hour + ':' + (minute < 10 ? '0' + minute : minute);
  }

  render(){
    return(
      <View style = {{flex: 1}}>
        {this.renderPageTitle()}
        {this.renderToggle()}
        {this.renderTitleInput()}
        {this.renderDateTimeInput()}
        {this.renderDescriptionInput()}
        {this.renderButtons()}
      </View>
    );
  }

  renderPageTitle(){
    return(
      <Header
        navigator = {this.props.navigator}
        text = "Create a New Event"
        hasBack = {true}
      />
    );
  }

  renderToggle(){
    return(
      <View style = {{flexDirection:'row'}}>
        <Switch
          onTintColor = "#0000ff"
          onValueChange = {(value) => this.setState({publicEvent: value})}
          style = {{marginBottom: 10}}
          value = {this.state.publicEvent}
        />
        <Text>
          {this.state.publicEvent ? ' Public Event' : 'Private Event'}
        </Text>
      </View>
    );
  }

  renderTitleInput(){
    return(
      <TextInput
        blurOnSubmit = {true}
        onChangeText = {(text) => this.setState({title: text})}
        value = {this.state.title}
        placeholder = {"Give Your Event a Title."}
        placeholderTextColor = 'black'
        underlineColorAndroid = 'black'
      />
    );
  }

  renderDateTimeInput(){
    return (
      <View>

        <Text style = {{color:'white'}}>
          Start:
        </Text>

        <View style = {{ flexDirection:'row'}}>
          <TouchableWithoutFeedback onPress = {
            this.showDatePicker.bind(this, 'min', {
              date: this.state.minDate,
              minDate: new Date(),
            }, true)
          }>
            <Text style = {{color:'black'}}>
              {this.state.dateStart}
            </Text>
          </TouchableWithoutFeedback>

          <TouchableWithoutFeedback
            onPress = {this.showTimePicker.bind(this, true)}>
            <Text style = {{color:'black'}}>{this.state.timeStart}</Text>
          </TouchableWithoutFeedback>

        </View>

        <Text style = {{color:'white'}}>
          End:
        </Text>
        <View style = {{ flexDirection:'row'}}>
          <View style = {{ flexDirection:'row'}}>
            <TouchableWithoutFeedback onPress = {
              this.showDatePicker.bind(this, 'min', {
                date: this.state.minDate,
                minDate: new Date(this.state.dateStart),
              }, false )
            }>
              <Text style = {{color:'black'}}>
                {this.state.dateEnd}
              </Text>
            </TouchableWithoutFeedback>
          </View>
        </View>
      </View>
    );
  }

  renderDescriptionInput(){
    var limit = 100;
    var remainder = limit - this.state.description.length;
    var remainderColor = remainder > 5 ? 'blue' : 'red';

    return (
      <View>
        <TextInput
          maxLength = {limit}
          multiline = {true}
          style = {Header.body, {color:'black'}}
          onChangeText = {(text) => this.setState({description: text})}
          value = {this.state.description}
          placeholder = {"Leave a short description of your event for your guests:"}
          placeholderTextColor = 'black'
          underlineColorAndroid = 'black'
        />
        <Text style = {{color: remainderColor}}>
          {remainder}
        </Text>
      </View>
    );
  }

  renderButtons(){
    return (
      <View style = {{alignItems: 'center'}}>
        <Button
          text = "Invite Friends!"
          onPress = {this.createGuestList.bind(this)}
          button_styles = {ButtonStyles.primary_button}
          button_text_styles = {ButtonStyles.primary_button_text}
        />

        <Button
          text = "Create Event!"
          onPress = {this.createEvent.bind(this)}
          button_styles = {ButtonStyles.primary_button}
          button_text_styles = {ButtonStyles.primary_button_text}
        />

      <Button
        text = "Clear"
        onPress = {this.clearEvent.bind(this)}
        button_styles = {ButtonStyles.primary_button}
        button_text_styles = {ButtonStyles.primary_button_text}
      />

    </View>
    );
  }

  createGuestList(){
    alert('friends list unimplemented')
  }

  createEvent(){

    alert(this.state.title)
    alert('this event is a public event: ' + this.state.publicEvent);
    alert('start: ' + this.state.dateStart + ' end: ' + this.state.dateEnd);
    alert(this.state.description);
  }

  clearEvent(){
    alert('Cleared :(');
    this.setState({
      title: '',
      publicEvent: true,
      dateStart: 'pick a start date',
      dateEnd: 'pick an end date',
      timeStart: 'pick a start time',
      timeEnd: 'pick an end time',
      description: ''
    })

  }
}

module.exports = CreateEvent;
<|endoftext|>


<commit_before>(function() {

    var model = {
        searchResults: ko.observableArray([]),

        searchValue: ko.observable(""),

        searchType: ko.observable("all"), //indicators, countries

        selectIndicator: function(obj) {

            if (obj.type == "countries") {

                window.location.href = "data-visualization#f=1990|2014&i=gdp_per_capita&c=line&r=" + obj.id

            }

            if (obj.type == "indicators") {

                window.location.href = "data-visualization#f=1990|2014&i=" + obj.id + "&c=line&r=dos_region:all";

            }
            //alert(obj.id)
        }
    }

    ko.applyBindings(model);

    var searchKeyUpHandler = function(e) {

		if (e.keyCode == 13) {
			$(".main-search-results span").first().click();
		} else {

            var value = $(".main-search")[0].value;

            var url = "/api/3/search/countries";

            switch (model.searchType()) {

                case "countries":
                    url = "/api/3/search/countries";
                    break;

                case "indicators":
                    url = "/api/3/search/indicators";
                    break;

                default:
                    url = "/api/3/search";
                    break;
            }

            model.searchValue(value);
            if (value.length < 2) {
                model.searchResults.removeAll();
                return;
            }

            $.ajax({
                url: url,
                jsonp: "callback",
                dataType: "jsonp",
                //dataType: "json",
                data: {
                    q: value
                },
                success: function(response) {
					//test data for dev
					//response = {"totaldatasets": 2, "totalcountries": 0, "data": {"indicators": {"gdp_growth": "GDP Growth", "gdp_total": "GDP, total"}, "countries": {}}};
					searchHandler(response, value);
                }
            });
		}
    }
        //search event
    $(".main-search").keyup(searchKeyUpHandler);

    $("input:radio[name=searchGroup]").change(function() {

        var value = $(this)[0].value;

        model.searchResults.removeAll();
        model.searchType(value);
        searchKeyUpHandler();

    });

    var searchHandler = function(response, value) {

		//current search type
        var searchType = model.searchType();

        model.searchResults.removeAll();

        var searchLevel = ["countries", "indicators"];

        if (searchType != "all") {
            searchLevel = [searchType];
        }

        var valuesArr = value.split(" ");

        _.forEach(searchLevel, function(responseType) {

            for (id in response.data[responseType]) {

                var resultItem = {
                    id: id,
                    label: "",
                    type: responseType
                }

                var originalLabel = response.data[responseType][id];
                var label = originalLabel;

                _.forEach(valuesArr, function(v) {
                    var regex = new RegExp('(' + v + ')', 'gi');

                    label = label.replace(regex, "$1")
                })

                resultItem.label = label;

                model.searchResults.push(resultItem);
            }

        })

    }

}())<commit_msg>front page search bug fixes #258<commit_after>(function() {

    var model = {
        searchResults: ko.observableArray([]),

        searchValue: ko.observable(""),

        searchType: ko.observable("all"), //indicators, countries

        selectIndicator: function(obj) {

            if (obj.type == "countries") {

                window.location.href = "data-visualization#f=1990|2014&i=gdp_per_capita&c=line&r=" + obj.id

            }

            if (obj.type == "indicators") {

                window.location.href = "data-visualization#f=1990|2014&i=" + obj.id + "&c=line&r=dos_region:all";

            }
            //alert(obj.id)
        }
    }

    ko.applyBindings(model);

    var searchKeyUpHandler = function(e) {
		if (e.keyCode == 13) {
			$(".main-search-results span").first().click();
		} else {
			searchAjax();
		}
    }
        //search event
    $(".main-search").keyup(searchKeyUpHandler);

    $("input:radio[name=searchGroup]").change(function() {

        var value = $(this)[0].value;

        model.searchResults.removeAll();
        model.searchType(value);
        searchAjax();

    });

	var searchAjax = function(){

		var value = $(".main-search")[0].value;

		var url = "/api/3/search/countries";

		switch (model.searchType()) {

			case "countries":
				url = "/api/3/search/countries";
				break;

			case "indicators":
				url = "/api/3/search/indicators";
				break;

			default:
				url = "/api/3/search";
				break;
		}

		model.searchValue(value);
		if (value.length < 2) {
			model.searchResults.removeAll();
			return;
		}

		$.ajax({
			url: url,
			jsonp: "callback",
			dataType: "jsonp",
			//dataType: "json",
			data: {
				q: value
			},
			success: function(response) {
				//test data for dev
				//response = {"totaldatasets": 2, "totalcountries": 0, "data": {"indicators": {"gdp_growth": "GDP Growth", "gdp_total": "GDP, total"}, "countries": {}}};
				searchHandler(response, value);
			}
		});
	}

    var searchHandler = function(response, value) {

		//current search type
        var searchType = model.searchType();

        model.searchResults.removeAll();

        var searchLevel = ["countries", "indicators"];

        if (searchType != "all") {
            searchLevel = [searchType];
        }

        var valuesArr = value.split(" ");

        _.forEach(searchLevel, function(responseType) {

            for (id in response.data[responseType]) {

                var resultItem = {
                    id: id,
                    label: "",
                    type: responseType
                }

                var originalLabel = response.data[responseType][id];
                var label = originalLabel;

                _.forEach(valuesArr, function(v) {
                    var regex = new RegExp('(' + v + ')', 'gi');

                    label = label.replace(regex, "$1")
                })

                resultItem.label = label;

                model.searchResults.push(resultItem);
            }

        })

    }

}())<|endoftext|>


<commit_before>
var AST    = require('../ast'),
    repeat = require('../util').repeat

function Context () {
  // Keeping track of names that conflict and need to be munged/aliased.
  this.conflicts = {}
  this._indent = 0
}
Context.prototype.incrementIndent = function () { this._indent += 2 }
Context.prototype.decrementIndent = function () { this._indent -= 2 }
Context.prototype.indent = function () {
  return repeat(' ', this._indent)
}

function wrapContextIndent(func) {
  return function (context) {
    context.incrementIndent()
    var ret = func.call(this, context)
    context.decrementIndent()
    return ret
  }
}

AST.Root.prototype.compile = function () {
  // Compilation context
  var context = new Context()
  return this.statements.map(function compile_statements(stmt) {
    return stmt.compile(context)
  }).join('')
}

AST.Binary.prototype.compile = function (context) {
  var lexpr = this.lexpr.compile(context)
  var rexpr = this.rexpr.compile(context)
  return lexpr+' '+this.op+' '+rexpr
}

AST.Literal.prototype.compile  = function (context) {
  return this.value.toString()
}

AST.Assignment.prototype.compile = function (context, opts) {
  var term = ";\n"
  if (opts && opts.omitTerminator === true) { term = '' }
  if (this.type === 'var' || this.type === 'let') {
    // TODO: Register name in context scope and check for conflicts.
    var lvalue = this.lvalue.name
    var rvalue = this.rvalue.compile(context)
    return 'var '+lvalue+' = '+rvalue+term
  } else {
    // TODO: Handle more complex path assignments
    // throw new Error('Compilation of path-assignments not yet implemented')
    var lvalue = this.lvalue.name
    var rvalue = this.rvalue.compile(context)
    return lvalue+' = '+rvalue+term
  }
}

AST.Function.prototype.compile = function (context) {
  var args = this.args.map(function (arg) { return arg.name })
  var body = this.block.compile(context)
  var ret = 'function ('+args.join(',')+") {\n"
  ret += body
  ret += "}"
  return ret
}

AST.Call.prototype.compile = function (context) {
  var args = this.args.map(function (arg) {
    return arg.compile(context)
  })
  return '('+args.join(', ')+')'
}

AST.If.prototype.compile = function (context) {
  var ind = context.indent()
  var ret = 'if ('+this.cond.compile()+") {\n"
  ret += this.block.compile(context)
  ret += ind+"}\n"
  return ret
}

AST.While.prototype.compile = function (context) {
  var ind = context.indent()
  var ret = 'while ('
  ret += this.expr.compile(context, {omitTerminator: true})
  ret += ') {\n'
  ret += this.block.compile(context)
  ret += ind + "}\n"
  return ret
}

AST.For.prototype.compile = function (context) {
  var ind = context.indent()
  var ret = 'for ('
  ret += this.init.compile(context, {omitTerminator: true})+'; '
  ret += this.cond.compile(context)+'; '
  ret += this.after.compile(context)+") {\n"
  ret += this.block.compile(context)
  ret += ind+"}\n"
  return ret
}

AST.Chain.prototype.compile = function (context) {
  var ret = this.name
  this.tail.forEach(function (item) {
    ret += item.compile(context)
  })
  return ret
}

AST.Return.prototype.compile  = function (context) {
  return 'return '+this.expr.compile(context)+";\n"
}

AST.Block.prototype.compile = wrapContextIndent(function (context) {
  var ret = []
  var ind = context.indent()
  this.statements.forEach(function (stmt) {
    ret.push(ind+stmt.compile(context))
  })
  return ret.join('')
})
<commit_msg>Compilation of binary-op statements<commit_after>
var AST    = require('../ast'),
    repeat = require('../util').repeat

function Context () {
  // Keeping track of names that conflict and need to be munged/aliased.
  this.conflicts = {}
  this._indent = 0
}
Context.prototype.incrementIndent = function () { this._indent += 2 }
Context.prototype.decrementIndent = function () { this._indent -= 2 }
Context.prototype.indent = function () {
  return repeat(' ', this._indent)
}

function wrapContextIndent(func) {
  return function (context) {
    context.incrementIndent()
    var ret = func.call(this, context)
    context.decrementIndent()
    return ret
  }
}

AST.Root.prototype.compile = function () {
  // Compilation context
  var context = new Context()
  return this.statements.map(function compile_statements(stmt) {
    return stmt.compile(context)
  }).join('')
}

AST.Binary.prototype.compile = function (context, opts) {
  var lexpr = this.lexpr.compile(context)
  var rexpr = this.rexpr.compile(context)
  var ret   = lexpr+' '+this.op+' '+rexpr
  if (opts && opts.statement === true) { ret += ";\n" }
  return ret
}

AST.Literal.prototype.compile  = function (context) {
  return this.value.toString()
}

AST.Assignment.prototype.compile = function (context, opts) {
  var term = ";\n"
  if (opts && opts.omitTerminator === true) { term = '' }
  if (this.type === 'var' || this.type === 'let') {
    // TODO: Register name in context scope and check for conflicts.
    var lvalue = this.lvalue.name
    var rvalue = this.rvalue.compile(context)
    return 'var '+lvalue+' = '+rvalue+term
  } else {
    // TODO: Handle more complex path assignments
    // throw new Error('Compilation of path-assignments not yet implemented')
    var lvalue = this.lvalue.name
    var rvalue = this.rvalue.compile(context)
    return lvalue+' = '+rvalue+term
  }
}

AST.Function.prototype.compile = function (context) {
  var args = this.args.map(function (arg) { return arg.name })
  var body = this.block.compile(context)
  var ret = 'function ('+args.join(',')+") {\n"
  ret += body
  ret += "}"
  return ret
}

AST.Call.prototype.compile = function (context) {
  var args = this.args.map(function (arg) {
    return arg.compile(context)
  })
  return '('+args.join(', ')+')'
}

AST.If.prototype.compile = function (context) {
  var ind = context.indent()
  var ret = 'if ('+this.cond.compile()+") {\n"
  ret += this.block.compile(context)
  ret += ind+"}\n"
  return ret
}

AST.While.prototype.compile = function (context) {
  var ind = context.indent()
  var ret = 'while ('
  ret += this.expr.compile(context, {omitTerminator: true})
  ret += ') {\n'
  ret += this.block.compile(context)
  ret += ind + "}\n"
  return ret
}

AST.For.prototype.compile = function (context) {
  var ind = context.indent()
  var ret = 'for ('
  ret += this.init.compile(context, {omitTerminator: true})+'; '
  ret += this.cond.compile(context)+'; '
  ret += this.after.compile(context)+") {\n"
  ret += this.block.compile(context)
  ret += ind+"}\n"
  return ret
}

AST.Chain.prototype.compile = function (context) {
  var ret = this.name
  this.tail.forEach(function (item) {
    ret += item.compile(context)
  })
  return ret
}

AST.Return.prototype.compile  = function (context) {
  return 'return '+this.expr.compile(context)+";\n"
}

AST.Block.prototype.compile = wrapContextIndent(function (context) {
  var ret = []
  var ind = context.indent()
  this.statements.forEach(function (stmt) {
    var opts = {}
    if (stmt instanceof AST.Binary) {
      opts.statement = true
    }
    ret.push(ind+stmt.compile(context, opts))
  })
  return ret.join('')
})
<|endoftext|>