<commit_before>const utils = require("../utils");
const web3Utils = require("web3-utils");

module.exports = {
  contract_name: {
    get: function() {
      return this.contractName;
    },
    set: function(val) {
      this.contractName = val;
    }
  },
  contractName: {
    get: function() {
      return this._json.contractName || "Contract";
    },
    set: function(val) {
      this._json.contractName = val;
    }
  },

  gasMultiplier: {
    get: function() {
      if (this._json.gasMultiplier === undefined) {
        this._json.gasMultiplier = 1.25;
      }
      return this._json.gasMultiplier;
    },
    set: function(val) {
      this._json.gasMultiplier = val;
    }
  },
  timeoutBlocks: {
    get: function() {
      return this._json.timeoutBlocks;
    },
    set: function(val) {
      this._json.timeoutBlocks = val;
    }
  },
  autoGas: {
    get: function() {
      if (this._json.autoGas === undefined) {
        this._json.autoGas = true;
      }
      return this._json.autoGas;
    },
    set: function(val) {
      this._json.autoGas = val;
    }
  },
  numberFormat: {
    get: function() {
      if (this._json.numberFormat === undefined) {
        this._json.numberFormat = "BN";
      }
      return this._json.numberFormat;
    },
    set: function(val) {
      const allowedFormats = ["BigNumber", "BN", "String"];

      const msg =
        `Invalid number format setting: "${val}": ` +
        `valid formats are: ${JSON.stringify(allowedFormats)}.`;

      if (!allowedFormats.includes(val)) throw new Error(msg);

      this._json.numberFormat = val;
    }
  },
  abi: {
    get: function() {
      return this._json.abi;
    },
    set: function(val) {
      this._json.abi = val;
    }
  },
  metadata: function() {
    return this._json.metadata;
  },
  network: function() {
    var network_id = this.network_id;

    if (network_id == null) {
      var error =
        this.contractName +
        " has no network id set, cannot lookup artifact data." +
        " Either set the network manually using " +
        this.contractName +
        ".setNetwork(), run " +
        this.contractName +
        ".detectNetwork(), or use new()," +
        " at() or deployed() as a thenable which will detect the network automatically.";

      throw new Error(error);
    }

    // TODO: this might be bad; setting a value on a get.
    if (this._json.networks[network_id] == null) {
      var error =
        this.contractName +
        " has no network configuration" +
        " for its current network id (" +
        network_id +
        ").";

      throw new Error(error);
    }

    var returnVal = this._json.networks[network_id];

    // Normalize output
    if (returnVal.links == null) {
      returnVal.links = {};
    }

    if (returnVal.events == null) {
      returnVal.events = {};
    }

    return returnVal;
  },
  networks: function() {
    return this._json.networks;
  },
  address: {
    get: function() {
      var address = this.network.address;

      if (address == null) {
        var error =
          "Cannot find deployed address: " +
          this.contractName +
          " not deployed or address not set.";
        throw new Error(error);
      }

      return address;
    },
    set: function(val) {
      if (val == null) {
        throw new Error("Cannot set deployed address; malformed value: " + val);
      }

      var network_id = this.network_id;

      if (network_id == null) {
        var error =
          this.contractName +
          " has no network id set, cannot lookup artifact data." +
          " Either set the network manually using " +
          this.contractName +
          ".setNetwork(), run " +
          this.contractName +
          ".detectNetwork()," +
          " or use new(), at() or deployed() as a thenable which will" +
          " detect the network automatically.";

        throw new Error(error);
      }

      // Create a network if we don't have one.
      if (this._json.networks[network_id] == null) {
        this._json.networks[network_id] = {
          events: {},
          links: {}
        };
      }

      // Finally, set the address.
      this.network.address = val;
    }
  },
  transactionHash: {
    get: function() {
      return this.network.transactionHash;
    },
    set: function(val) {
      this.network.transactionHash = val;
    }
  },
  links: function() {
    if (!this.network_id) {
      var error =
        this.contractName +
        " has no network id set, cannot lookup artifact data." +
        " Either set the network manually using " +
        this.contractName +
        ".setNetwork()," +
        " run " +
        this.contractName +
        ".detectNetwork(), or use new(), at()" +
        " or deployed() as a thenable which will detect the network automatically.";

      throw new Error(error);
    }

    if (this._json.networks[this.network_id] == null) {
      return {};
    }

    return this.network.links || {};
  },
  events: function() {
    var events;

    if (this._json.networks[this.network_id] == null) {
      events = {};
    } else {
      events = this.network.events || {};
    }

    // Merge abi events with whatever's returned.
    var abi = this.abi;

    abi.forEach(function(item) {
      if (item.type !== "event") return;

      if (item.signature) {
        events[item.signature] = item;
      } else {
        var signature = item.name + "(";

        item.inputs.forEach(function(input, index) {
          signature += input.type;

          if (index < item.inputs.length - 1) {
            signature += ",";
          }
        });

        signature += ")";

        var topic = web3Utils.keccak256(signature);

        events[topic] = item;
      }
    });

    return events;
  },
  binary: function() {
    return utils.linkBytecode(this.bytecode, this.links);
  },
  deployedBinary: function() {
    return utils.linkBytecode(this.deployedBytecode, this.links);
  },

  // deprecated; use bytecode
  unlinked_binary: {
    get: function() {
      return this.bytecode;
    },
    set: function(val) {
      this.bytecode = val;
    }
  },
  // alias for unlinked_binary; unlinked_binary will eventually be deprecated
  bytecode: {
    get: function() {
      return this._json.bytecode;
    },
    set: function(val) {
      this._json.bytecode = val;
    }
  },
  deployedBytecode: {
    get: function() {
      var code = this._json.deployedBytecode;

      if (code.indexOf("0x") !== 0) {
        code = "0x" + code;
      }

      return code;
    },
    set: function(val) {
      var code = val;

      if (val.indexOf("0x") !== 0) {
        code = "0x" + code;
      }

      this._json.deployedBytecode = code;
    }
  },
  sourceMap: {
    get: function() {
      return this._json.sourceMap;
    },
    set: function(val) {
      this._json.sourceMap = val;
    }
  },
  deployedSourceMap: {
    get: function() {
      return this._json.deployedSourceMap;
    },
    set: function(val) {
      this._json.deployedSourceMap = val;
    }
  },
  source: {
    get: function() {
      return this._json.source;
    },
    set: function(val) {
      this._json.source = val;
    }
  },
  sourcePath: {
    get: function() {
      return this._json.sourcePath;
    },
    set: function(val) {
      this._json.sourcePath = val;
    }
  },
  legacyAST: {
    get: function() {
      return this._json.legacyAST;
    },
    set: function(val) {
      this._json.legacyAST = val;
    }
  },
  ast: {
    get: function() {
      return this._json.ast;
    },
    set: function(val) {
      this._json.ast = val;
    }
  },
  compiler: {
    get: function() {
      return this._json.compiler;
    },
    set: function(val) {
      this._json.compiler = val;
    }
  },
  // Deprecated
  schema_version: function() {
    return this.schemaVersion;
  },
  schemaVersion: function() {
    return this._json.schemaVersion;
  },
  // deprecated
  updated_at: function() {
    return this.updatedAt;
  },
  updatedAt: function() {
    try {
      return this.network.updatedAt || this._json.updatedAt;
    } catch (e) {
      return this._json.updatedAt;
    }
  },
  userdoc: function() {
    return this._json.userdoc;
  },
  devdoc: function() {
    return this._json.devdoc;
  }
};
<commit_msg>add networkType prop (contract/lib/contract/properties)<commit_after>const utils = require("../utils");
const web3Utils = require("web3-utils");

module.exports = {
  contract_name: {
    get: function() {
      return this.contractName;
    },
    set: function(val) {
      this.contractName = val;
    }
  },
  contractName: {
    get: function() {
      return this._json.contractName || "Contract";
    },
    set: function(val) {
      this._json.contractName = val;
    }
  },

  gasMultiplier: {
    get: function() {
      if (this._json.gasMultiplier === undefined) {
        this._json.gasMultiplier = 1.25;
      }
      return this._json.gasMultiplier;
    },
    set: function(val) {
      this._json.gasMultiplier = val;
    }
  },
  timeoutBlocks: {
    get: function() {
      return this._json.timeoutBlocks;
    },
    set: function(val) {
      this._json.timeoutBlocks = val;
    }
  },
  autoGas: {
    get: function() {
      if (this._json.autoGas === undefined) {
        this._json.autoGas = true;
      }
      return this._json.autoGas;
    },
    set: function(val) {
      this._json.autoGas = val;
    }
  },
  numberFormat: {
    get: function() {
      if (this._json.numberFormat === undefined) {
        this._json.numberFormat = "BN";
      }
      return this._json.numberFormat;
    },
    set: function(val) {
      const allowedFormats = ["BigNumber", "BN", "String"];

      const msg =
        `Invalid number format setting: "${val}": ` +
        `valid formats are: ${JSON.stringify(allowedFormats)}.`;

      if (!allowedFormats.includes(val)) throw new Error(msg);

      this._json.numberFormat = val;
    }
  },
  abi: {
    get: function() {
      return this._json.abi;
    },
    set: function(val) {
      this._json.abi = val;
    }
  },
  metadata: function() {
    return this._json.metadata;
  },
  network: function() {
    var network_id = this.network_id;

    if (network_id == null) {
      var error =
        this.contractName +
        " has no network id set, cannot lookup artifact data." +
        " Either set the network manually using " +
        this.contractName +
        ".setNetwork(), run " +
        this.contractName +
        ".detectNetwork(), or use new()," +
        " at() or deployed() as a thenable which will detect the network automatically.";

      throw new Error(error);
    }

    // TODO: this might be bad; setting a value on a get.
    if (this._json.networks[network_id] == null) {
      var error =
        this.contractName +
        " has no network configuration" +
        " for its current network id (" +
        network_id +
        ").";

      throw new Error(error);
    }

    var returnVal = this._json.networks[network_id];

    // Normalize output
    if (returnVal.links == null) {
      returnVal.links = {};
    }

    if (returnVal.events == null) {
      returnVal.events = {};
    }

    return returnVal;
  },
  networks: function() {
    return this._json.networks;
  },
  address: {
    get: function() {
      var address = this.network.address;

      if (address == null) {
        var error =
          "Cannot find deployed address: " +
          this.contractName +
          " not deployed or address not set.";
        throw new Error(error);
      }

      return address;
    },
    set: function(val) {
      if (val == null) {
        throw new Error("Cannot set deployed address; malformed value: " + val);
      }

      var network_id = this.network_id;

      if (network_id == null) {
        var error =
          this.contractName +
          " has no network id set, cannot lookup artifact data." +
          " Either set the network manually using " +
          this.contractName +
          ".setNetwork(), run " +
          this.contractName +
          ".detectNetwork()," +
          " or use new(), at() or deployed() as a thenable which will" +
          " detect the network automatically.";

        throw new Error(error);
      }

      // Create a network if we don't have one.
      if (this._json.networks[network_id] == null) {
        this._json.networks[network_id] = {
          events: {},
          links: {}
        };
      }

      // Finally, set the address.
      this.network.address = val;
    }
  },
  transactionHash: {
    get: function() {
      return this.network.transactionHash;
    },
    set: function(val) {
      this.network.transactionHash = val;
    }
  },
  links: function() {
    if (!this.network_id) {
      var error =
        this.contractName +
        " has no network id set, cannot lookup artifact data." +
        " Either set the network manually using " +
        this.contractName +
        ".setNetwork()," +
        " run " +
        this.contractName +
        ".detectNetwork(), or use new(), at()" +
        " or deployed() as a thenable which will detect the network automatically.";

      throw new Error(error);
    }

    if (this._json.networks[this.network_id] == null) {
      return {};
    }

    return this.network.links || {};
  },
  events: function() {
    var events;

    if (this._json.networks[this.network_id] == null) {
      events = {};
    } else {
      events = this.network.events || {};
    }

    // Merge abi events with whatever's returned.
    var abi = this.abi;

    abi.forEach(function(item) {
      if (item.type !== "event") return;

      if (item.signature) {
        events[item.signature] = item;
      } else {
        var signature = item.name + "(";

        item.inputs.forEach(function(input, index) {
          signature += input.type;

          if (index < item.inputs.length - 1) {
            signature += ",";
          }
        });

        signature += ")";

        var topic = web3Utils.keccak256(signature);

        events[topic] = item;
      }
    });

    return events;
  },
  binary: function() {
    return utils.linkBytecode(this.bytecode, this.links);
  },
  deployedBinary: function() {
    return utils.linkBytecode(this.deployedBytecode, this.links);
  },

  // deprecated; use bytecode
  unlinked_binary: {
    get: function() {
      return this.bytecode;
    },
    set: function(val) {
      this.bytecode = val;
    }
  },
  // alias for unlinked_binary; unlinked_binary will eventually be deprecated
  bytecode: {
    get: function() {
      return this._json.bytecode;
    },
    set: function(val) {
      this._json.bytecode = val;
    }
  },
  deployedBytecode: {
    get: function() {
      var code = this._json.deployedBytecode;

      if (code.indexOf("0x") !== 0) {
        code = "0x" + code;
      }

      return code;
    },
    set: function(val) {
      var code = val;

      if (val.indexOf("0x") !== 0) {
        code = "0x" + code;
      }

      this._json.deployedBytecode = code;
    }
  },
  sourceMap: {
    get: function() {
      return this._json.sourceMap;
    },
    set: function(val) {
      this._json.sourceMap = val;
    }
  },
  deployedSourceMap: {
    get: function() {
      return this._json.deployedSourceMap;
    },
    set: function(val) {
      this._json.deployedSourceMap = val;
    }
  },
  source: {
    get: function() {
      return this._json.source;
    },
    set: function(val) {
      this._json.source = val;
    }
  },
  sourcePath: {
    get: function() {
      return this._json.sourcePath;
    },
    set: function(val) {
      this._json.sourcePath = val;
    }
  },
  legacyAST: {
    get: function() {
      return this._json.legacyAST;
    },
    set: function(val) {
      this._json.legacyAST = val;
    }
  },
  ast: {
    get: function() {
      return this._json.ast;
    },
    set: function(val) {
      this._json.ast = val;
    }
  },
  compiler: {
    get: function() {
      return this._json.compiler;
    },
    set: function(val) {
      this._json.compiler = val;
    }
  },
  // Deprecated
  schema_version: function() {
    return this.schemaVersion;
  },
  schemaVersion: function() {
    return this._json.schemaVersion;
  },
  // deprecated
  updated_at: function() {
    return this.updatedAt;
  },
  updatedAt: function() {
    try {
      return this.network.updatedAt || this._json.updatedAt;
    } catch (e) {
      return this._json.updatedAt;
    }
  },
  userdoc: function() {
    return this._json.userdoc;
  },
  devdoc: function() {
    return this._json.devdoc;
  },
  networkType: {
    get: function() {
      return this._json.networkType || "ethereum";
    },
    set: function(_networkType) {
      this._json.networkType = _networkType;
    }
  }
};
<|endoftext|>


<commit_before>require("ember-bootstrap/mixins/type_support");
require("ember-bootstrap/mixins/size_support");

var get = Ember.get;

Bootstrap.Button = Ember.Button.extend(Bootstrap.TypeSupport, Bootstrap.SizeSupport, {
  classNames: ['btn'],
  classNameBindings: ['disabled'],
  baseClassName: 'btn'
});
<commit_msg>Update Button class<commit_after>require("ember-bootstrap/mixins/type_support");
require("ember-bootstrap/mixins/size_support");

var get = Ember.get;

Bootstrap.Button = Ember.Button.extend(Bootstrap.TypeSupport, Bootstrap.SizeSupport, {
  classNames: ['btn'],
  classNameBindings: ['typeClass', 'sizeClass', 'disabled'],

  typeClass: Ember.computed(function() {
    var type = get(this, 'type');
    return type ? 'btn-' + type : null;
  }).property('type').cacheable(),

  sizeClass: Ember.computed(function() {
    var size = get(this, 'size');
    return size ? 'btn-' + size : null;
  }).property('size').cacheable(),

  baseClassName: 'btn'
});
<|endoftext|>


<commit_before>declare module "chai" {

    declare type ExpectChain<T> = {
        and: ExpectChain<T>,
        at: ExpectChain<T>,
        be: ExpectChain<T>,
        been: ExpectChain<T>,
        have: ExpectChain<T>,
        has: ExpectChain<T>,
        is: ExpectChain<T>,
        of: ExpectChain<T>,
        same: ExpectChain<T>,
        that: ExpectChain<T>,
        to: ExpectChain<T>,
        which: ExpectChain<T>,
        with: ExpectChain<T>,

        not: ExpectChain<T>,
        deep: ExpectChain<T>,
        any: ExpectChain<T>,
        all: ExpectChain<T>,

        a: ExpectChain<T> & (type: string) => ExpectChain<T>,
        an: ExpectChain<T> & (type: string) => ExpectChain<T>,

        include: ExpectChain<T> & (value: mixed) => ExpectChain<T>,
        includes: ExpectChain<T> & (value: mixed) => ExpectChain<T>,
        contain: ExpectChain<T> & (value: mixed) => ExpectChain<T>,
        contains: ExpectChain<T> & (value: mixed) => ExpectChain<T>,

        eql: (value: T) => ExpectChain<T>,
        equal: (value: T) => ExpectChain<T>,
        equals: (value: T) => ExpectChain<T>,

        above: (value: T & number) => ExpectChain<T>,
        least: (value: T & number) => ExpectChain<T>,
        below: (value: T & number) => ExpectChain<T>,
        most: (value: T & number) => ExpectChain<T>,
        within: (start: T & number, finish: T & number) => ExpectChain<T>,

        instanceof: (constructor: mixed) => ExpectChain<T>,
        property: (

(name: string, value?: P) => ExpectChain

          & (name: string) => ExpectChain<mixed>
        ),

        length: (value: number) => ExpectChain<T> | ExpectChain<number>,
        lengthOf: (value: number) => ExpectChain<T>,

        match: (regex: RegExp) => ExpectChain<T>,
        string: (string: string) => ExpectChain<T>,

        key: (key: string) => ExpectChain<T>,
        keys: (key: string | Array<string>, ...keys: Array<string>) => ExpectChain<T>,

        throw: <E>(
            err: Class<E> | Error | RegExp | string,
            errMsgMatcher?: RegExp | string,
            msg?: string) => ExpectChain<T>,

        respondTo: (method: string) => ExpectChain<T>,
        itself: ExpectChain<T>,

        satisfy: (method: (value: T) => bool) => ExpectChain<T>,

        closeTo: (expected: T & number, delta: number) => ExpectChain<T>,

        members: (set: mixed) => ExpectChain<T>,
        oneOf: (list: Array<T>) => ExpectChain<T>,

        change: (obj: mixed, key: string) => ExpectChain<T>,
        increase: (obj: mixed, key: string) => ExpectChain<T>,
        decrease: (obj: mixed, key: string) => ExpectChain<T>,

        // dirty-chai
        ok: () => ExpectChain<T>,
        true: () => ExpectChain<T>,
        false: () => ExpectChain<T>,
        null: () => ExpectChain<T>,
        undefined: () => ExpectChain<T>,
        exist: () => ExpectChain<T>,
        empty: () => ExpectChain<T>,

        // chai-immutable
        size: (n: number) => ExpectChain<T>,

        // sinon-chai
        called: () => ExpectChain<T>,
        callCount: (n: number) => ExpectChain<T>,
        calledOnce: () => ExpectChain<T>,
        calledBefore: (spy: mixed) => ExpectChain<T>,
        calledAfter: (spy: mixed) => ExpectChain<T>,
        calledWith: (...args: Array<mixed>) => ExpectChain<T>,
        calledWithMatch: (...args: Array<mixed>) => ExpectChain<T>,
        calledWithExactly: (...args: Array<mixed>) => ExpectChain<T>,

        // chai-as-promised
        eventually: ExpectChain<T>,
        resolvedWith: (value: mixed) => Promise<mixed> & ExpectChain<T>,
        resolved: () => Promise<mixed> & ExpectChain<T>,
        rejectedWith: (value: mixed) => Promise<mixed> & ExpectChain<T>,
        rejected: () => Promise<mixed> & ExpectChain<T>,
        notify: (callback: () => mixed) => ExpectChain<T>,

        // chai-subset
        containSubset: (obj: Object | Object[]) => ExpectChain<T>
    };

    declare function expect<T>(actual: T): ExpectChain<T>;

    declare function use(plugin: (chai: Object, utils: Object) => void): void;

    declare class assert {
      static(expression: mixed, message?: string): void;
      static fail(actual: mixed, expected: mixed, message?: string, operator?: string): void;

      static isOk(object: mixed, message?: string): void;
      static isNotOk(object: mixed, message?: string): void;

      static equal(actual: mixed, expected: mixed, message?: string): void;
      static notEqual(actual: mixed, expected: mixed, message?: string): void;

      static strictEqual(act: mixed, exp: mixed, msg?: string): void;
      static notStrictEqual(act: mixed, exp: mixed, msg?: string): void;

      static deepEqual(act: mixed, exp: mixed, msg?: string): void;
      static notDeepEqual(act: mixed, exp: mixed, msg?: string): void;

      static ok(val: mixed, msg?: string): void;
      static isTrue(val: mixed, msg?: string): void;
      static isNotTrue(val: mixed, msg?: string): void;
      static isFalse(val: mixed, msg?: string): void;
      static isNotFalse(val: mixed, msg?: string): void;

      static isNull(val: mixed, msg?: string): void;
      static isNotNull(val: mixed, msg?: string): void;

      static isUndefined(val: mixed, msg?: string): void;
      static isDefined(val: mixed, msg?: string): void;

      static isNaN(val: mixed, msg?: string): void;
      static isNotNaN(val: mixed, msg?: string): void;

      static isAbove(val: number, abv: number, msg?: string): void;
      static isBelow(val: number, blw: number, msg?: string): void;

      static isAtMost(val: number, atmst: number, msg?: string): void;
      static isAtLeast(val: number, atlst: number, msg?: string): void;

      static isFunction(val: mixed, msg?: string): void;
      static isNotFunction(val: mixed, msg?: string): void;

      static isObject(val: mixed, msg?: string): void;
      static isNotObject(val: mixed, msg?: string): void;

      static isArray(val: mixed, msg?: string): void;
      static isNotArray(val: mixed, msg?: string): void;

      static isString(val: mixed, msg?: string): void;
      static isNotString(val: mixed, msg?: string): void;

      static isNumber(val: mixed, msg?: string): void;
      static isNotNumber(val: mixed, msg?: string): void;

      static isBoolean(val: mixed, msg?: string): void;
      static isNotBoolean(val: mixed, msg?: string): void;

      static typeOf(val: mixed, type: string, msg?: string): void;
      static notTypeOf(val: mixed, type: string, msg?: string): void;

      static instanceOf(val: mixed, constructor: Function, msg?: string): void;
      static notInstanceOf(val: mixed, constructor: Function, msg?: string): void;

      static include(exp: string, inc: mixed, msg?: string): void;
      static include<T>(exp: Array<T>, inc: T, msg?: string): void;

      static notInclude(exp: string, inc: mixed, msg?: string): void;
      static notInclude<T>(exp: Array<T>, inc: T, msg?: string): void;

      static match(exp: mixed, re: RegExp, msg?: string): void;
      static notMatch(exp: mixed, re: RegExp, msg?: string): void;

      static property(obj: Object, prop: string, msg?: string): void;
      static notProperty(obj: Object, prop: string, msg?: string): void;
      static deepProperty(obj: Object, prop: string, msg?: string): void;
      static notDeepProperty(obj: Object, prop: string, msg?: string): void;

      static propertyVal(obj: Object, prop: string, val: mixed, msg?: string): void;
      static propertyNotVal(obj: Object, prop: string, val: mixed, msg?: string): void;

      static deepPropertyVal(obj: Object, prop: string, val: mixed, msg?: string): void;
      static deepPropertyNotVal(obj: Object, prop: string, val: mixed, msg?: string): void;

      static lengthOf(exp: mixed, len: number, msg?: string): void;

      static throws<E>(
          func: () => any,
          err?: Class<E> | Error | RegExp | string,
          errorMsgMatcher?: string | RegExp,
          msg?: string): void;
      static doesNotThrow<E>(
          func: () => any,
          err?: Class<E> | Error | RegExp | string,
          errorMsgMatcher?: string | RegExp,
          msg?: string): void;
    }

    declare var config: {
        includeStack: boolean,
        showDiff: boolean,
        truncateThreshold: number
    };
}
<commit_msg>Added missing properties to chai definition (#534)<commit_after>declare module "chai" {

    declare type ExpectChain<T> = {
        and: ExpectChain<T>,
        at: ExpectChain<T>,
        be: ExpectChain<T>,
        been: ExpectChain<T>,
        have: ExpectChain<T>,
        has: ExpectChain<T>,
        is: ExpectChain<T>,
        of: ExpectChain<T>,
        same: ExpectChain<T>,
        that: ExpectChain<T>,
        to: ExpectChain<T>,
        which: ExpectChain<T>,
        with: ExpectChain<T>,

        not: ExpectChain<T>,
        deep: ExpectChain<T>,
        any: ExpectChain<T>,
        all: ExpectChain<T>,

        a: ExpectChain<T> & (type: string) => ExpectChain<T>,
        an: ExpectChain<T> & (type: string) => ExpectChain<T>,

        include: ExpectChain<T> & (value: mixed) => ExpectChain<T>,
        includes: ExpectChain<T> & (value: mixed) => ExpectChain<T>,
        contain: ExpectChain<T> & (value: mixed) => ExpectChain<T>,
        contains: ExpectChain<T> & (value: mixed) => ExpectChain<T>,

        eql: (value: T) => ExpectChain<T>,
        equal: (value: T) => ExpectChain<T>,
        equals: (value: T) => ExpectChain<T>,

        above: (value: T & number) => ExpectChain<T>,
        least: (value: T & number) => ExpectChain<T>,
        below: (value: T & number) => ExpectChain<T>,
        most: (value: T & number) => ExpectChain<T>,
        within: (start: T & number, finish: T & number) => ExpectChain<T>,

        instanceof: (constructor: mixed) => ExpectChain<T>,
        property: (

(name: string, value?: P) => ExpectChain

          & (name: string) => ExpectChain<mixed>
        ),

        length: (value: number) => ExpectChain<T> | ExpectChain<number>,
        lengthOf: (value: number) => ExpectChain<T>,

        match: (regex: RegExp) => ExpectChain<T>,
        string: (string: string) => ExpectChain<T>,

        key: (key: string) => ExpectChain<T>,
        keys: (key: string | Array<string>, ...keys: Array<string>) => ExpectChain<T>,

        throw: <E>(
            err: Class<E> | Error | RegExp | string,
            errMsgMatcher?: RegExp | string,
            msg?: string) => ExpectChain<T>,

        respondTo: (method: string) => ExpectChain<T>,
        itself: ExpectChain<T>,

        satisfy: (method: (value: T) => bool) => ExpectChain<T>,

        closeTo: (expected: T & number, delta: number) => ExpectChain<T>,

        members: (set: mixed) => ExpectChain<T>,
        oneOf: (list: Array<T>) => ExpectChain<T>,

        change: (obj: mixed, key: string) => ExpectChain<T>,
        increase: (obj: mixed, key: string) => ExpectChain<T>,
        decrease: (obj: mixed, key: string) => ExpectChain<T>,

        // dirty-chai
        ok: () => ExpectChain<T>,
        true: () => ExpectChain<T>,
        false: () => ExpectChain<T>,
        null: () => ExpectChain<T>,
        undefined: () => ExpectChain<T>,
        exist: () => ExpectChain<T>,
        empty: () => ExpectChain<T>,

        extensible: () => ExpectChain<T>,
        sealed: () => ExpectChain<T>,
        frozen: () => ExpectChain<T>,

        // chai-immutable
        size: (n: number) => ExpectChain<T>,

        // sinon-chai
        called: () => ExpectChain<T>,
        callCount: (n: number) => ExpectChain<T>,
        calledOnce: () => ExpectChain<T>,
        calledBefore: (spy: mixed) => ExpectChain<T>,
        calledAfter: (spy: mixed) => ExpectChain<T>,
        calledWith: (...args: Array<mixed>) => ExpectChain<T>,
        calledWithMatch: (...args: Array<mixed>) => ExpectChain<T>,
        calledWithExactly: (...args: Array<mixed>) => ExpectChain<T>,

        // chai-as-promised
        eventually: ExpectChain<T>,
        resolvedWith: (value: mixed) => Promise<mixed> & ExpectChain<T>,
        resolved: () => Promise<mixed> & ExpectChain<T>,
        rejectedWith: (value: mixed) => Promise<mixed> & ExpectChain<T>,
        rejected: () => Promise<mixed> & ExpectChain<T>,
        notify: (callback: () => mixed) => ExpectChain<T>,

        // chai-subset
        containSubset: (obj: Object | Object[]) => ExpectChain<T>
    };

    declare function expect<T>(actual: T): ExpectChain<T>;

    declare function use(plugin: (chai: Object, utils: Object) => void): void;

    declare class assert {
      static(expression: mixed, message?: string): void;
      static fail(actual: mixed, expected: mixed, message?: string, operator?: string): void;

      static isOk(object: mixed, message?: string): void;
      static isNotOk(object: mixed, message?: string): void;

      static equal(actual: mixed, expected: mixed, message?: string): void;
      static notEqual(actual: mixed, expected: mixed, message?: string): void;

      static strictEqual(act: mixed, exp: mixed, msg?: string): void;
      static notStrictEqual(act: mixed, exp: mixed, msg?: string): void;

      static deepEqual(act: mixed, exp: mixed, msg?: string): void;
      static notDeepEqual(act: mixed, exp: mixed, msg?: string): void;

      static ok(val: mixed, msg?: string): void;
      static isTrue(val: mixed, msg?: string): void;
      static isNotTrue(val: mixed, msg?: string): void;
      static isFalse(val: mixed, msg?: string): void;
      static isNotFalse(val: mixed, msg?: string): void;

      static isNull(val: mixed, msg?: string): void;
      static isNotNull(val: mixed, msg?: string): void;

      static isUndefined(val: mixed, msg?: string): void;
      static isDefined(val: mixed, msg?: string): void;

      static isNaN(val: mixed, msg?: string): void;
      static isNotNaN(val: mixed, msg?: string): void;

      static isAbove(val: number, abv: number, msg?: string): void;
      static isBelow(val: number, blw: number, msg?: string): void;

      static isAtMost(val: number, atmst: number, msg?: string): void;
      static isAtLeast(val: number, atlst: number, msg?: string): void;

      static isFunction(val: mixed, msg?: string): void;
      static isNotFunction(val: mixed, msg?: string): void;

      static isObject(val: mixed, msg?: string): void;
      static isNotObject(val: mixed, msg?: string): void;

      static isArray(val: mixed, msg?: string): void;
      static isNotArray(val: mixed, msg?: string): void;

      static isString(val: mixed, msg?: string): void;
      static isNotString(val: mixed, msg?: string): void;

      static isNumber(val: mixed, msg?: string): void;
      static isNotNumber(val: mixed, msg?: string): void;

      static isBoolean(val: mixed, msg?: string): void;
      static isNotBoolean(val: mixed, msg?: string): void;

      static typeOf(val: mixed, type: string, msg?: string): void;
      static notTypeOf(val: mixed, type: string, msg?: string): void;

      static instanceOf(val: mixed, constructor: Function, msg?: string): void;
      static notInstanceOf(val: mixed, constructor: Function, msg?: string): void;

      static include(exp: string, inc: mixed, msg?: string): void;
      static include<T>(exp: Array<T>, inc: T, msg?: string): void;

      static notInclude(exp: string, inc: mixed, msg?: string): void;
      static notInclude<T>(exp: Array<T>, inc: T, msg?: string): void;

      static match(exp: mixed, re: RegExp, msg?: string): void;
      static notMatch(exp: mixed, re: RegExp, msg?: string): void;

      static property(obj: Object, prop: string, msg?: string): void;
      static notProperty(obj: Object, prop: string, msg?: string): void;
      static deepProperty(obj: Object, prop: string, msg?: string): void;
      static notDeepProperty(obj: Object, prop: string, msg?: string): void;

      static propertyVal(obj: Object, prop: string, val: mixed, msg?: string): void;
      static propertyNotVal(obj: Object, prop: string, val: mixed, msg?: string): void;

      static deepPropertyVal(obj: Object, prop: string, val: mixed, msg?: string): void;
      static deepPropertyNotVal(obj: Object, prop: string, val: mixed, msg?: string): void;

      static lengthOf(exp: mixed, len: number, msg?: string): void;

      static throws<E>(
          func: () => any,
          err?: Class<E> | Error | RegExp | string,
          errorMsgMatcher?: string | RegExp,
          msg?: string): void;
      static doesNotThrow<E>(
          func: () => any,
          err?: Class<E> | Error | RegExp | string,
          errorMsgMatcher?: string | RegExp,
          msg?: string): void;
    }

    declare var config: {
        includeStack: boolean,
        showDiff: boolean,
        truncateThreshold: number
    };
}
<|endoftext|>


<commit_before>// Copyright 2019 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.
//

'use strict';

module.exports = {
  opts: {
    readme: './README.md',
    package: './package.json',
    template: './node_modules/jsdoc-fresh',
    recurse: true,
    verbose: true,
    destination: './docs/'
  },
  plugins: [
    'plugins/markdown',
    'jsdoc-region-tag'
  ],
  source: {
    excludePattern: '(^|\\/|\\\\)[._]',
    include: [
      'build/src'
    ],
    includePattern: '\\.js$'
  },
  templates: {
    copyright: 'Copyright 2019 Google, LLC.',
    includeDate: false,
    sourceFiles: false,
    systemName: '@google-cloud/datalabeling',
    theme: 'lumen',
    default: {
      "outputSourceFiles": false
    }
  },
  markdown: {
    idInHeadings: true
  }
};
<commit_msg>chore: update jsdoc with macro license (#144)<commit_after>// Copyright 2019 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.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **

'use strict';

module.exports = {
  opts: {
    readme: './README.md',
    package: './package.json',
    template: './node_modules/jsdoc-fresh',
    recurse: true,
    verbose: true,
    destination: './docs/'
  },
  plugins: [
    'plugins/markdown',
    'jsdoc-region-tag'
  ],
  source: {
    excludePattern: '(^|\\/|\\\\)[._]',
    include: [
      'build/src'
    ],
    includePattern: '\\.js$'
  },
  templates: {
    copyright: 'Copyright 2019 Google, LLC.',
    includeDate: false,
    sourceFiles: false,
    systemName: '@google-cloud/datalabeling',
    theme: 'lumen',
    default: {
      "outputSourceFiles": false
    }
  },
  markdown: {
    idInHeadings: true
  }
};
<|endoftext|>


<commit_before>/**
 * window.c.ProjectDataStats component
 * render a row with project stats info like:
 * state / total_contributions / total_pledged / elapsed | remaning time
 *
 * Example:
 * m.component(c.ProjectDataStats, {project: project})
 * */
import m from 'mithril';
import _ from 'underscore';
import h from '../h';

const projectDataStats = {
    view: function({attrs}) {
        const project = attrs.project(),
            visitorsTotal = attrs.visitorsTotal(),
            statusTextObj = h.projectStateTextClass(project.state, project.has_cancelation_request),
            remainingTextObj = h.translatedTime(project.remaining_time),
            elapsedTextObj = h.translatedTime(project.elapsed_time),
            contributorsByVisitors = project.total_contributors / visitorsTotal,
            contributorsByVisitorsValue = isNaN(contributorsByVisitors) ? contributorsByVisitors : 0;

        return m('', [
            m('.w-row.u-marginbottom-60.u-margintop-30.u-text-center', [
                m('.w-col.w-col-2'),
                m('.w-col.w-col-4', [
                    m('.fontsize-large', [
                        m('span.fontcolor-secondary', 'Status: '),
                        m('span', { class: statusTextObj.cssClass }, statusTextObj.text)
                    ])
                ]),
                m('.w-col.w-col-4', [
                    m('.fontsize-large.fontweight-semibold', [
                        m('span.fa.fa-clock-o'),
                        (_.isNull(project.expires_at) ?
                            ` Iniciado há ${elapsedTextObj.total} ${elapsedTextObj.unit}`
                            :
                            ` ${remainingTextObj.total} ${remainingTextObj.unit} ${(remainingTextObj.total > 1 ? 'restantes' : 'restante')}`
                        )
                    ])
                ]),
                m('.w-col.w-col-2')
            ]),
            m('.card.medium.u-marginbottom-60.u-radius.u-text-center', { style: { 'white-space': 'nowrap' } }, [
                m('.w-row', [
                    m('.w-col.w-col-6', [
                        m('.w-row.u-marginbottom-30.u-margintop-30', [
                            m('.w-col.w-col-4.w-col-small-4.w-col-tiny-4', [
                                m('.fontsize-larger.fontweight-semibold', `${visitorsTotal}`),
                                'Visitantes'
                            ]),
                            m('.w-col.w-col-4.w-col-small-4.w-col-tiny-4', [
                                m('.bg-triangle-funnel.fontcolor-secondary.fontsize-base', `${h.formatNumber(contributorsByVisitorsValue, 2)}%`)
                            ]),
                            m('.w-col.w-col-4.w-col-small-4.w-col-tiny-4', [
                                m('.fontsize-larger.fontweight-semibold', `${project.total_contributors}`),
                                'Apoiadores'
                            ])
                        ])
                    ]),
                    m('.w-col.w-col-6', [
                        m('.w-row.u-marginbottom-30.u-margintop-30', [
                            m('.w-col.w-col-9.w-col-small-6.w-col-tiny-6', [
                                m('.fontsize-larger.fontweight-semibold', `R$ ${h.formatNumber(project.pledged, 2)}`),
                                'Arrecadados'
                            ]),
                            m('.w-col.w-col-3.w-col-small-6.w-col-tiny-6', [
                                m('.fontsize-larger.fontweight-semibold', `${h.formatNumber(project.progress, 2)}%`),
                                'da Meta'
                            ])
                        ])
                    ])
                ]),
                m('.fontcolor-secondary.fontsize-smallest.u-margintop-20', [
                    'Os dados podem levar até 24 horas para serem atualizados.',
                    m('a.alt-link', { href: 'https://suporte.catarse.me/hc/pt-br/articles/115002214463-projeto-ONLINE#visitante', target: '_blank' }, ' Saiba mais'),
                    '.'
                ])
            ])
        ]);
    }
};

export default projectDataStats;
<commit_msg>[finishes #167808335] Fix contributors by visits calc<commit_after>/**
 * window.c.ProjectDataStats component
 * render a row with project stats info like:
 * state / total_contributions / total_pledged / elapsed | remaning time
 *
 * Example:
 * m.component(c.ProjectDataStats, {project: project})
 * */
import m from 'mithril';
import _ from 'underscore';
import h from '../h';

const projectDataStats = {
    view: function({attrs}) {
        const project = attrs.project(),
            visitorsTotal = attrs.visitorsTotal(),
            statusTextObj = h.projectStateTextClass(project.state, project.has_cancelation_request),
            remainingTextObj = h.translatedTime(project.remaining_time),
            elapsedTextObj = h.translatedTime(project.elapsed_time),
            contributorsByVisitors = project.total_contributors / visitorsTotal,
            contributorsByVisitorsValue = isNaN(contributorsByVisitors) || !isFinite(contributorsByVisitors) ? 0 : contributorsByVisitors * 100;

        return m('', [
            m('.w-row.u-marginbottom-60.u-margintop-30.u-text-center', [
                m('.w-col.w-col-2'),
                m('.w-col.w-col-4', [
                    m('.fontsize-large', [
                        m('span.fontcolor-secondary', 'Status: '),
                        m('span', { class: statusTextObj.cssClass }, statusTextObj.text)
                    ])
                ]),
                m('.w-col.w-col-4', [
                    m('.fontsize-large.fontweight-semibold', [
                        m('span.fa.fa-clock-o'),
                        (_.isNull(project.expires_at) ?
                            ` Iniciado há ${elapsedTextObj.total} ${elapsedTextObj.unit}`
                            :
                            ` ${remainingTextObj.total} ${remainingTextObj.unit} ${(remainingTextObj.total > 1 ? 'restantes' : 'restante')}`
                        )
                    ])
                ]),
                m('.w-col.w-col-2')
            ]),
            m('.card.medium.u-marginbottom-60.u-radius.u-text-center', { style: { 'white-space': 'nowrap' } }, [
                m('.w-row', [
                    m('.w-col.w-col-6', [
                        m('.w-row.u-marginbottom-30.u-margintop-30', [
                            m('.w-col.w-col-4.w-col-small-4.w-col-tiny-4', [
                                m('.fontsize-larger.fontweight-semibold', `${visitorsTotal}`),
                                'Visitantes'
                            ]),
                            m('.w-col.w-col-4.w-col-small-4.w-col-tiny-4', [
                                m('.bg-triangle-funnel.fontcolor-secondary.fontsize-base', `${h.formatNumber(contributorsByVisitorsValue, 2)}%`)
                            ]),
                            m('.w-col.w-col-4.w-col-small-4.w-col-tiny-4', [
                                m('.fontsize-larger.fontweight-semibold', `${project.total_contributors}`),
                                'Apoiadores'
                            ])
                        ])
                    ]),
                    m('.w-col.w-col-6', [
                        m('.w-row.u-marginbottom-30.u-margintop-30', [
                            m('.w-col.w-col-9.w-col-small-6.w-col-tiny-6', [
                                m('.fontsize-larger.fontweight-semibold', `R$ ${h.formatNumber(project.pledged, 2)}`),
                                'Arrecadados'
                            ]),
                            m('.w-col.w-col-3.w-col-small-6.w-col-tiny-6', [
                                m('.fontsize-larger.fontweight-semibold', `${h.formatNumber(project.progress, 2)}%`),
                                'da Meta'
                            ])
                        ])
                    ])
                ]),
                m('.fontcolor-secondary.fontsize-smallest.u-margintop-20', [
                    'Os dados podem levar até 24 horas para serem atualizados.',
                    m('a.alt-link', { href: 'https://suporte.catarse.me/hc/pt-br/articles/115002214463-projeto-ONLINE#visitante', target: '_blank' }, ' Saiba mais'),
                    '.'
                ])
            ])
        ]);
    }
};

export default projectDataStats;
<|endoftext|>


<commit_before>/* -*- mode: espresso; espresso-indent-level: 2; indent-tabs-mode: nil -*- */
/* vim: set softtabstop=2 shiftwidth=2 tabstop=2 expandtab: */

"use strict";

var CircuitGraphPlot = function() {
  this.widgetID = this.registerInstance();
  this.registerSource();

	// SkeletonModel instances
	this.skeletons = {};
  // Skeleton IDs, each has a model in this.skeletons
  // and the order corresponds with that of the adjacency matrix.
  this.skeleton_ids = [];

	// From CircuitGraphAnalysis, first array entry is Signal Flow, rest are
	// the sorted pairs of [eigenvalue, eigenvector].
	this.vectors = null;

  this.names_visible = true;

  // Skeleton ID vs true
  this.selected = {};
};

CircuitGraphPlot.prototype = {};
$.extend(CircuitGraphPlot.prototype, new InstanceRegistry());
$.extend(CircuitGraphPlot.prototype, new SkeletonSource());

CircuitGraphPlot.prototype.getName = function() {
	return "Circuit Graph Plot " + this.widgetID;
};

CircuitGraphPlot.prototype.destroy = function() {
  this.unregisterInstance();
  this.unregisterSource();

  Object.keys(this).forEach(function(key) { delete this[key]; }, this);
};

CircuitGraphPlot.prototype.updateModels = function(models) {
	this.append(models);
};

/** Returns a clone of all skeleton models, keyed by skeleton ID. */
CircuitGraphPlot.prototype.getSelectedSkeletonModels = function() {
  if (!this.svg) return {};
	var skeletons = this.skeletons;
	return Object.keys(this.selected).reduce(function(o, skid) {
		o[skid] = skeletons[skid].clone();
		return o;
	}, {});
};

CircuitGraphPlot.prototype.getSkeletonModels = CircuitGraphPlot.prototype.getSelectedSkeletonModels;

CircuitGraphPlot.prototype.hasSkeleton = function(skeleton_id) {
  return skeleton_id in this.skeleton_ids;
};

CircuitGraphPlot.prototype.clear = function() {
	// TODO
};

CircuitGraphPlot.prototype.append = function(models) {
	// Update names and colors if present, remove when deselected
	Object.keys(this.skeletons).forEach(function(skid) {
		var model = models[skid];
		if (model) {
			if (model.selected) {
				this.skeletons[skid] = model;
			} else {
				delete this.skeletons[skid];
			}
		}
	}, this);

  Object.keys(models).forEach(function(skid) {
    if (skid in this.skeletons) return;
    var model = models[skid];
    if (model.selected) {
      this.skeletons[skid] = model.clone();
    }
  }, this);

	this.skeleton_ids = Object.keys(this.skeletons);

	// fetch connectivity data, create adjacency matrix and plot it
	requestQueue.register(django_url + project.id + '/skeletongroup/skeletonlist_confidence_compartment_subgraph', 'POST',
			{skeleton_list: this.skeleton_ids},
			(function(status, text) {
				if (200 !== status) return;
				var json = $.parseJSON(text);
				if (json.error) { alert(json.error); return; }
				// Create adjacency matrix
				var AdjM = this.skeleton_ids.map(function(skid) { return this.skeleton_ids.map(function(skid) { return 0; }); }, this);
				// Populate adjacency matrix
				var indices = this.skeleton_ids.reduce(function(o, skid, i) { o[skid] = i; return o; }, {});
				json.edges.forEach(function(edge) {
					AdjM[indices[edge[0]]][indices[edge[1]]] = edge[2];
				});
        // Update data and GUI
        this.plot(this.skeleton_ids, this.skeletons, AdjM);
			}).bind(this));
};

/** Takes an array of skeleton IDs, a map of skeleton ID vs SkeletonModel,
 * and an array of arrays representing the adjacency matrix where the order
 * in rows and columns corresponds to the order in the array of skeleton IDs.
 * Clears the existing plot and replaces it with the new data. */
CircuitGraphPlot.prototype.plot = function(skeleton_ids, models, AdjM) {
  // Set the new data
  this.skeleton_ids = skeleton_ids;
  this.skeletons = models;
  this.selected = {};

  // Compute signal flow and eigenvectors
  try {
    var cga = new CircuitGraphAnalysis(AdjM);
  } catch (e) {
    console.log(e, e.stack);
    alert("Failed to compute the adjacency matrix: \n" + e + "\n" + e.stack);
    return;
  }

  // Store for replotting later
  this.vectors = [[-1, cga.z]];
  for (var i=0; i<10 && i <cga.e.length; ++i) {
    this.vectors.push(cga.e[i]);
  }

  // Reset pulldown menus
  var updateSelect = function(select) {
    select.options.length = 0;
    select.options.add(new Option('Signal Flow', 0));
    for (var i=0; i<10 && i <cga.e.length; ++i) {
      select.options.add(new Option('Eigenvalue ' + Number(cga.e[i][0]).toFixed(2), i+1));
    }
    return select;
  };
  updateSelect($('#circuit_graph_plot_X_' + this.widgetID)[0]).selectedIndex = 1;
  updateSelect($('#circuit_graph_plot_Y_' + this.widgetID)[0]).selectedIndex = 0;

  this.redraw();
};

CircuitGraphPlot.prototype.redraw = function() {
  if (!this.skeleton_ids || 0 === this.skeleton_ids.length) return;

  var containerID = '#circuit_graph_plot_div' + this.widgetID,
      container = $(containerID);

  // Clear existing plot if any
  container.empty();

  // Recreate plot
  var margin = {top: 20, right: 20, bottom: 30, left: 40},
      width = container.width() - margin.left - margin.right,
      height = container.height() - margin.top - margin.bottom;

  var svg = d3.select(containerID).append("svg")
    .attr("id", "circuit_graph_plot" + this.widgetID)
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + ", " + margin.top + ")");

  var xSelect = $('#circuit_graph_plot_X_' + this.widgetID)[0],
      ySelect = $('#circuit_graph_plot_Y_' + this.widgetID)[0];

  var xVector = this.vectors[xSelect.selectedIndex][1],
      yVector = this.vectors[ySelect.selectedIndex][1];

  // Package data
  var data = this.skeleton_ids.map(function(skid, i) {
    var model = this.skeletons[skid];
    return {skid: skid,
            name: model.baseName,
            hex: '#' + model.color.getHexString(),
            x: xVector[i],
            y: yVector[i]};
  }, this);

  // Define the ranges of the axes
  var xR = d3.scale.linear().domain(d3.extent(xVector)).nice().range([0, width]);
  var yR = d3.scale.linear().domain(d3.extent(yVector)).nice().range([height, 0]);

  // Define the data domains/axes
  var xAxis = d3.svg.axis().scale(xR)
                           .orient("bottom")
                           .ticks(10);
  var yAxis = d3.svg.axis().scale(yR)
                           .orient("left")
                           .ticks(10);

  // Create a 'g' group for each skeleton, containing a circle and the neuron name
  var elems = svg.selectAll(".state").data(data).enter()
    .append('g')
    .attr('transform', function(d) { return "translate(" + xR(d.x) + "," + yR(d.y) + ")"; });

  var setSelected = (function(skid, b) {
    if (b) this.selected[skid] = true;
    else delete this.selected[skid];
  }).bind(this);

  var selected = this.selected;

  elems.append('circle')
     .attr('class', 'dot')
     .attr('r', function(d) { return selected[d.skid] ? 6 : 3; })
     .style('fill', function(d) { return d.hex; })
     .style('stroke', function(d) { return selected[d.skid] ? 'black' : 'grey'; })
     .on('click', function(d) {
       // Toggle selected:
       var c = d3.select(this);
       if (3 === Number(c.attr('r'))) {
         c.attr('r', 6).style('stroke', 'black');
         setSelected(d.skid, true);
       } else {
         c.attr('r', 3).style('stroke', 'grey');
         setSelected(d.skid, false);
       }
     })
   .append('svg:title')
     .text(function(d) { return d.name; });

  elems.append('text')
     .text(function(d) { return d.name; })
     .attr('id', 'name')
     .attr('display', this.names_visible ? '' : 'none')
     .attr('dx', function(d) { return 5; });

  // Insert the graphics for the axes (after the data, so that they draw on top)
  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
    .append("text")
      .attr("x", width)
      .attr("y", -6)
      .style("text-anchor", "end")
      .text(xSelect.options[xSelect.selectedIndex].text);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text(ySelect.options[ySelect.selectedIndex].text);

  this.svg = svg;
};

/** Redraw only the last request, where last is a period of about 1 second. */
CircuitGraphPlot.prototype.resize = function() {
  var now = new Date();
  // Overwrite request log if any
  this.last_request = now;

  setTimeout((function() {
    if (this.last_request && now === this.last_request) {
      delete this.last_request;
      this.redraw();
    }
  }).bind(this), 1000);
};

CircuitGraphPlot.prototype.setNamesVisible = function(v) {
  if (this.svg) {
    this.svg.selectAll('text#name').attr('display', v ? '' : 'none');
  }
};

CircuitGraphPlot.prototype.toggleNamesVisible = function(checkbox) {
  this.names_visible = checkbox.checked;
  this.setNamesVisible(this.names_visible);
};

CircuitGraphPlot.prototype.update = function() {
  this.append(this.skeletons);
};

CircuitGraphPlot.prototype.highlight = function() {
  // TODO
};
<commit_msg>Circuit Graph Plot: implement the "Clear" button.<commit_after>/* -*- mode: espresso; espresso-indent-level: 2; indent-tabs-mode: nil -*- */
/* vim: set softtabstop=2 shiftwidth=2 tabstop=2 expandtab: */

"use strict";

var CircuitGraphPlot = function() {
  this.widgetID = this.registerInstance();
  this.registerSource();

	// SkeletonModel instances
	this.skeletons = {};
  // Skeleton IDs, each has a model in this.skeletons
  // and the order corresponds with that of the adjacency matrix.
  this.skeleton_ids = [];

	// From CircuitGraphAnalysis, first array entry is Signal Flow, rest are
	// the sorted pairs of [eigenvalue, eigenvector].
	this.vectors = null;

  this.names_visible = true;

  // Skeleton ID vs true
  this.selected = {};
};

CircuitGraphPlot.prototype = {};
$.extend(CircuitGraphPlot.prototype, new InstanceRegistry());
$.extend(CircuitGraphPlot.prototype, new SkeletonSource());

CircuitGraphPlot.prototype.getName = function() {
	return "Circuit Graph Plot " + this.widgetID;
};

CircuitGraphPlot.prototype.destroy = function() {
  this.unregisterInstance();
  this.unregisterSource();

  Object.keys(this).forEach(function(key) { delete this[key]; }, this);
};

CircuitGraphPlot.prototype.updateModels = function(models) {
	this.append(models);
};

/** Returns a clone of all skeleton models, keyed by skeleton ID. */
CircuitGraphPlot.prototype.getSelectedSkeletonModels = function() {
  if (!this.svg) return {};
	var skeletons = this.skeletons;
	return Object.keys(this.selected).reduce(function(o, skid) {
		o[skid] = skeletons[skid].clone();
		return o;
	}, {});
};

CircuitGraphPlot.prototype.getSkeletonModels = CircuitGraphPlot.prototype.getSelectedSkeletonModels;

CircuitGraphPlot.prototype.hasSkeleton = function(skeleton_id) {
  return skeleton_id in this.skeleton_ids;
};

CircuitGraphPlot.prototype.clear = function() {
	this.skeletons = {};
  this.skeleton_ids = [];
  this.selected = {};
  this.redraw();
};

CircuitGraphPlot.prototype.append = function(models) {
	// Update names and colors if present, remove when deselected
	Object.keys(this.skeletons).forEach(function(skid) {
		var model = models[skid];
		if (model) {
			if (model.selected) {
				this.skeletons[skid] = model;
			} else {
				delete this.skeletons[skid];
			}
		}
	}, this);

  Object.keys(models).forEach(function(skid) {
    if (skid in this.skeletons) return;
    var model = models[skid];
    if (model.selected) {
      this.skeletons[skid] = model.clone();
    }
  }, this);

	this.skeleton_ids = Object.keys(this.skeletons);

	// fetch connectivity data, create adjacency matrix and plot it
	requestQueue.register(django_url + project.id + '/skeletongroup/skeletonlist_confidence_compartment_subgraph', 'POST',
			{skeleton_list: this.skeleton_ids},
			(function(status, text) {
				if (200 !== status) return;
				var json = $.parseJSON(text);
				if (json.error) { alert(json.error); return; }
				// Create adjacency matrix
				var AdjM = this.skeleton_ids.map(function(skid) { return this.skeleton_ids.map(function(skid) { return 0; }); }, this);
				// Populate adjacency matrix
				var indices = this.skeleton_ids.reduce(function(o, skid, i) { o[skid] = i; return o; }, {});
				json.edges.forEach(function(edge) {
					AdjM[indices[edge[0]]][indices[edge[1]]] = edge[2];
				});
        // Update data and GUI
        this.plot(this.skeleton_ids, this.skeletons, AdjM);
			}).bind(this));
};

/** Takes an array of skeleton IDs, a map of skeleton ID vs SkeletonModel,
 * and an array of arrays representing the adjacency matrix where the order
 * in rows and columns corresponds to the order in the array of skeleton IDs.
 * Clears the existing plot and replaces it with the new data. */
CircuitGraphPlot.prototype.plot = function(skeleton_ids, models, AdjM) {
  // Set the new data
  this.skeleton_ids = skeleton_ids;
  this.skeletons = models;
  this.selected = {};

  // Compute signal flow and eigenvectors
  try {
    var cga = new CircuitGraphAnalysis(AdjM);
  } catch (e) {
    console.log(e, e.stack);
    alert("Failed to compute the adjacency matrix: \n" + e + "\n" + e.stack);
    return;
  }

  // Store for replotting later
  this.vectors = [[-1, cga.z]];
  for (var i=0; i<10 && i <cga.e.length; ++i) {
    this.vectors.push(cga.e[i]);
  }

  // Reset pulldown menus
  var updateSelect = function(select) {
    select.options.length = 0;
    select.options.add(new Option('Signal Flow', 0));
    for (var i=0; i<10 && i <cga.e.length; ++i) {
      select.options.add(new Option('Eigenvalue ' + Number(cga.e[i][0]).toFixed(2), i+1));
    }
    return select;
  };
  updateSelect($('#circuit_graph_plot_X_' + this.widgetID)[0]).selectedIndex = 1;
  updateSelect($('#circuit_graph_plot_Y_' + this.widgetID)[0]).selectedIndex = 0;

  this.redraw();
};

CircuitGraphPlot.prototype.redraw = function() {
  var containerID = '#circuit_graph_plot_div' + this.widgetID,
      container = $(containerID);

  // Clear existing plot if any
  container.empty();

  if (!this.skeleton_ids || 0 === this.skeleton_ids.length) return;

  // Recreate plot
  var margin = {top: 20, right: 20, bottom: 30, left: 40},
      width = container.width() - margin.left - margin.right,
      height = container.height() - margin.top - margin.bottom;

  var svg = d3.select(containerID).append("svg")
    .attr("id", "circuit_graph_plot" + this.widgetID)
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + ", " + margin.top + ")");

  var xSelect = $('#circuit_graph_plot_X_' + this.widgetID)[0],
      ySelect = $('#circuit_graph_plot_Y_' + this.widgetID)[0];

  var xVector = this.vectors[xSelect.selectedIndex][1],
      yVector = this.vectors[ySelect.selectedIndex][1];

  // Package data
  var data = this.skeleton_ids.map(function(skid, i) {
    var model = this.skeletons[skid];
    return {skid: skid,
            name: model.baseName,
            hex: '#' + model.color.getHexString(),
            x: xVector[i],
            y: yVector[i]};
  }, this);

  // Define the ranges of the axes
  var xR = d3.scale.linear().domain(d3.extent(xVector)).nice().range([0, width]);
  var yR = d3.scale.linear().domain(d3.extent(yVector)).nice().range([height, 0]);

  // Define the data domains/axes
  var xAxis = d3.svg.axis().scale(xR)
                           .orient("bottom")
                           .ticks(10);
  var yAxis = d3.svg.axis().scale(yR)
                           .orient("left")
                           .ticks(10);

  // Create a 'g' group for each skeleton, containing a circle and the neuron name
  var elems = svg.selectAll(".state").data(data).enter()
    .append('g')
    .attr('transform', function(d) { return "translate(" + xR(d.x) + "," + yR(d.y) + ")"; });

  var setSelected = (function(skid, b) {
    if (b) this.selected[skid] = true;
    else delete this.selected[skid];
  }).bind(this);

  var selected = this.selected;

  elems.append('circle')
     .attr('class', 'dot')
     .attr('r', function(d) { return selected[d.skid] ? 6 : 3; })
     .style('fill', function(d) { return d.hex; })
     .style('stroke', function(d) { return selected[d.skid] ? 'black' : 'grey'; })
     .on('click', function(d) {
       // Toggle selected:
       var c = d3.select(this);
       if (3 === Number(c.attr('r'))) {
         c.attr('r', 6).style('stroke', 'black');
         setSelected(d.skid, true);
       } else {
         c.attr('r', 3).style('stroke', 'grey');
         setSelected(d.skid, false);
       }
     })
   .append('svg:title')
     .text(function(d) { return d.name; });

  elems.append('text')
     .text(function(d) { return d.name; })
     .attr('id', 'name')
     .attr('display', this.names_visible ? '' : 'none')
     .attr('dx', function(d) { return 5; });

  // Insert the graphics for the axes (after the data, so that they draw on top)
  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
    .append("text")
      .attr("x", width)
      .attr("y", -6)
      .style("text-anchor", "end")
      .text(xSelect.options[xSelect.selectedIndex].text);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text(ySelect.options[ySelect.selectedIndex].text);

  this.svg = svg;
};

/** Redraw only the last request, where last is a period of about 1 second. */
CircuitGraphPlot.prototype.resize = function() {
  var now = new Date();
  // Overwrite request log if any
  this.last_request = now;

  setTimeout((function() {
    if (this.last_request && now === this.last_request) {
      delete this.last_request;
      this.redraw();
    }
  }).bind(this), 1000);
};

CircuitGraphPlot.prototype.setNamesVisible = function(v) {
  if (this.svg) {
    this.svg.selectAll('text#name').attr('display', v ? '' : 'none');
  }
};

CircuitGraphPlot.prototype.toggleNamesVisible = function(checkbox) {
  this.names_visible = checkbox.checked;
  this.setNamesVisible(this.names_visible);
};

CircuitGraphPlot.prototype.update = function() {
  this.append(this.skeletons);
};

CircuitGraphPlot.prototype.highlight = function() {
  // TODO
};
<|endoftext|>


<commit_before>import { GL } from '../Renderer/webgl.js';
import { GltfObject } from './gltf_object.js';

class gltfAccessor extends GltfObject
{
    constructor()
    {
        super();
        this.bufferView = undefined;
        this.byteOffset = 0;
        this.componentType = undefined;
        this.normalized = false;
        this.count = undefined;
        this.type = undefined;
        this.max = undefined;
        this.min = undefined;
        this.sparse = undefined;
        this.name = undefined;

        // non gltf
        this.glBuffer = undefined;
        this.typedView = undefined;
        this.filteredView = undefined;
        this.normalizedFilteredView = undefined;
        this.normalizedTypedView = undefined;
    }

    // getTypedView provides a view to the accessors data in form of
    // a TypedArray. This data can directly be passed to vertexAttribPointer
    getTypedView(gltf)
    {
        if (this.typedView !== undefined)
        {
            return this.typedView;
        }

        if (this.bufferView !== undefined)
        {
            const bufferView = gltf.bufferViews[this.bufferView];
            const buffer = gltf.buffers[bufferView.buffer];
            const byteOffset = this.byteOffset + bufferView.byteOffset;

            const componentSize = this.getComponentSize(this.componentType);
            let componentCount = this.getComponentCount(this.type);

            let arrayLength = 0;
            if(bufferView.byteStride !== 0)
            {
                if (componentSize !== 0)
                {
                    arrayLength = bufferView.byteStride / componentSize * (this.count - 1) + componentCount;
                }
                else
                {
                    console.warn("Invalid component type in accessor '" + (this.name ? this.name : "") + "'");
                }
            }
            else
            {
                arrayLength = this.count * componentCount;
            }

            if (arrayLength * componentSize > buffer.buffer.byteLength - byteOffset)
            {
                arrayLength = (buffer.buffer.byteLength - byteOffset) / componentSize;
                console.warn("Count in accessor '" + (this.name ? this.name : "") + "' is too large.");
            }

            switch (this.componentType)
            {
            case GL.BYTE:
                this.typedView = new Int8Array(buffer.buffer, byteOffset, arrayLength);
                break;
            case GL.UNSIGNED_BYTE:
                this.typedView = new Uint8Array(buffer.buffer, byteOffset, arrayLength);
                break;
            case GL.SHORT:
                this.typedView = new Int16Array(buffer.buffer, byteOffset, arrayLength);
                break;
            case GL.UNSIGNED_SHORT:
                this.typedView = new Uint16Array(buffer.buffer, byteOffset, arrayLength);
                break;
            case GL.UNSIGNED_INT:
                this.typedView = new Uint32Array(buffer.buffer, byteOffset, arrayLength);
                break;
            case GL.FLOAT:
                this.typedView = new Float32Array(buffer.buffer, byteOffset, arrayLength);
                break;
            }
        }

        if (this.typedView === undefined)
        {
            console.warn("Failed to convert buffer view to typed view!: " + this.bufferView);
        }
        else if (this.sparse !== undefined)
        {
            this.applySparse(gltf, this.typedView);
        }

        return this.typedView;
    }

    // getNormalizedTypedView provides an alternative view to the accessors data,
    // where quantized data is already normalized. This is useful if the data is not passed
    // to vertexAttribPointer but used immediately (like e.g. animations)
    getNormalizedTypedView(gltf)
    {
        if(this.normalizedTypedView !== undefined)
        {
            return this.normalizedTypedView;
        }

        const typedView = this.getTypedView(gltf);
        this.normalizedTypedView = this.normalized ? gltfAccessor.dequantize(typedView, this.componentType) : typedView;
        return this.normalizedTypedView;
    }

    // getDeinterlacedView provides a view to the accessors data in form of
    // a TypedArray. In contrast to getTypedView, getDeinterlacedView deinterlaces
    // data, i.e. stripping padding and unrelated components from the array. It then
    // only contains the data of the accessor
    getDeinterlacedView(gltf)
    {
        if (this.filteredView !== undefined)
        {
            return this.filteredView;
        }

        if (this.bufferView !== undefined)
        {
            const bufferView = gltf.bufferViews[this.bufferView];
            const buffer = gltf.buffers[bufferView.buffer];
            const byteOffset = this.byteOffset + bufferView.byteOffset;

            const componentSize = this.getComponentSize(this.componentType);
            const componentCount = this.getComponentCount(this.type);
            const arrayLength = this.count * componentCount;

            let stride = bufferView.byteStride !== 0 ? bufferView.byteStride : componentCount * componentSize;
            let dv = new DataView(buffer.buffer, byteOffset, this.count * stride);

            let func = 'getFloat32';
            switch (this.componentType)
            {
            case GL.BYTE:
                this.filteredView = new Int8Array(arrayLength);
                func = 'getInt8';
                break;
            case GL.UNSIGNED_BYTE:
                this.filteredView = new Uint8Array(arrayLength);
                func = 'getUint8';
                break;
            case GL.SHORT:
                this.filteredView = new Int16Array(arrayLength);
                func = 'getInt16';
                break;
            case GL.UNSIGNED_SHORT:
                this.filteredView = new Uint16Array(arrayLength);
                func = 'getUint16';
                break;
            case GL.UNSIGNED_INT:
                this.filteredView = new Uint32Array(arrayLength);
                func = 'getUint32';
                break;
            case GL.FLOAT:
                this.filteredView = new Float32Array(arrayLength);
                func = 'getFloat32';
                break;
            }

            for(let i = 0; i < arrayLength; ++i)
            {
                let offset = Math.floor(i/componentCount) * stride + (i % componentCount) * componentSize;
                this.filteredView[i] = dv[func](offset, true);
            }
        }

        if (this.filteredView === undefined)
        {
            console.warn("Failed to convert buffer view to filtered view!: " + this.bufferView)
        }
        else if (this.sparse !== undefined)
        {
            this.applySparse(gltf, this.filteredView);
        }

        return this.filteredView;
    }

    // getNormalizedDeinterlacedView provides an alternative view to the accessors data,
    // where quantized data is already normalized. This is useful if the data is not passed
    // to vertexAttribPointer but used immediately (like e.g. animations)
    getNormalizedDeinterlacedView(gltf)
    {
        if(this.normalizedFilteredView !== undefined)
        {
            return this.normalizedFilteredView;
        }

        const filteredView = this.getDeinterlacedView(gltf);
        this.normalizedFilteredView = this.normalized ? gltfAccessor.dequantize(filteredView, this.componentType) : filteredView;
        return this.normalizedFilteredView;
    }

    applySparse(gltf, view)
    {
        // Gather indices.

        const indicesBufferView = gltf.bufferViews[this.sparse.indices.bufferView];
        const indicesBuffer = gltf.buffers[indicesBufferView.buffer];
        const indicesByteOffset = this.sparse.indices.byteOffset + indicesBufferView.byteOffset;

        const indicesComponentSize = this.getComponentSize(this.sparse.indices.componentType);
        let indicesComponentCount = 1;

        if(indicesBufferView.byteStride !== 0)
        {
            indicesComponentCount = indicesBufferView.byteStride / indicesComponentSize;
        }

        const indicesArrayLength = this.sparse.count * indicesComponentCount;

        let indicesTypedView;
        switch (this.sparse.indices.componentType)
        {
        case GL.UNSIGNED_BYTE:
            indicesTypedView = new Uint8Array(indicesBuffer.buffer, indicesByteOffset, indicesArrayLength);
            break;
        case GL.UNSIGNED_SHORT:
            indicesTypedView = new Uint16Array(indicesBuffer.buffer, indicesByteOffset, indicesArrayLength);
            break;
        case GL.UNSIGNED_INT:
            indicesTypedView = new Uint32Array(indicesBuffer.buffer, indicesByteOffset, indicesArrayLength);
            break;
        }

        // Gather values.

        const valuesBufferView = gltf.bufferViews[this.sparse.values.bufferView];
        const valuesBuffer = gltf.buffers[valuesBufferView.buffer];
        const valuesByteOffset = this.sparse.values.byteOffset + valuesBufferView.byteOffset;

        const valuesComponentSize = this.getComponentSize(this.componentType);
        let valuesComponentCount = this.getComponentCount(this.type);

        if(valuesBufferView.byteStride !== 0)
        {
            valuesComponentCount = valuesBufferView.byteStride / valuesComponentSize;
        }

        const valuesArrayLength = this.sparse.count * valuesComponentCount;

        let valuesTypedView;
        switch (this.componentType)
        {
        case GL.BYTE:
            valuesTypedView = new Int8Array(valuesBuffer.buffer, valuesByteOffset, valuesArrayLength);
            break;
        case GL.UNSIGNED_BYTE:
            valuesTypedView = new Uint8Array(valuesBuffer.buffer, valuesByteOffset, valuesArrayLength);
            break;
        case GL.SHORT:
            valuesTypedView = new Int16Array(valuesBuffer.buffer, valuesByteOffset, valuesArrayLength);
            break;
        case GL.UNSIGNED_SHORT:
            valuesTypedView = new Uint16Array(valuesBuffer.buffer, valuesByteOffset, valuesArrayLength);
            break;
        case GL.UNSIGNED_INT:
            valuesTypedView = new Uint32Array(valuesBuffer.buffer, valuesByteOffset, valuesArrayLength);
            break;
        case GL.FLOAT:
            valuesTypedView = new Float32Array(valuesBuffer.buffer, valuesByteOffset, valuesArrayLength);
            break;
        }

        // Overwrite values.

        for(let i = 0; i < this.sparse.count; ++i)
        {
            for(let k = 0; k < valuesComponentCount; ++k)
            {
                view[indicesTypedView[i] * valuesComponentCount + k] = valuesTypedView[i * valuesComponentCount + k];
            }
        }
    }

    // dequantize can be used to perform the normalization from WebGL2 vertexAttribPointer explicitly
    static dequantize(typedArray, componentType)
    {
        switch (componentType)
        {
        case GL.BYTE:
            return typedArray.map(c => Math.max(c / 127.0, -1.0));
        case GL.UNSIGNED_BYTE:
            return typedArray.map(c => c / 255.0);
        case GL.SHORT:
            return typedArray.map(c => Math.max(c / 32767.0, -1.0));
        case GL.UNSIGNED_SHORT:
            return typedArray.map(c => c / 65535.0);
        default:
            return typedArray;
        }
    }

    getComponentCount(type)
    {
        return CompononentCount.get(type);
    }

    getComponentSize(componentType)
    {
        switch (componentType)
        {
        case GL.BYTE:
        case GL.UNSIGNED_BYTE:
            return 1;
        case GL.SHORT:
        case GL.UNSIGNED_SHORT:
            return 2;
        case GL.UNSIGNED_INT:
        case GL.FLOAT:
            return 4;
        default:
            return 0;
        }
    }

    destroy()
    {
        if (this.glBuffer !== undefined)
        {
            // TODO: this breaks the dependency direction
            WebGl.context.deleteBuffer(this.glBuffer);
        }

        this.glBuffer = undefined;
    }
}

const CompononentCount = new Map(
    [
        ["SCALAR", 1],
        ["VEC2", 2],
        ["VEC3", 3],
        ["VEC4", 4],
        ["MAT2", 4],
        ["MAT3", 9],
        ["MAT4", 16]
    ]
);

export { gltfAccessor };
<commit_msg>fixed dequantization<commit_after>import { GL } from '../Renderer/webgl.js';
import { GltfObject } from './gltf_object.js';

class gltfAccessor extends GltfObject
{
    constructor()
    {
        super();
        this.bufferView = undefined;
        this.byteOffset = 0;
        this.componentType = undefined;
        this.normalized = false;
        this.count = undefined;
        this.type = undefined;
        this.max = undefined;
        this.min = undefined;
        this.sparse = undefined;
        this.name = undefined;

        // non gltf
        this.glBuffer = undefined;
        this.typedView = undefined;
        this.filteredView = undefined;
        this.normalizedFilteredView = undefined;
        this.normalizedTypedView = undefined;
    }

    // getTypedView provides a view to the accessors data in form of
    // a TypedArray. This data can directly be passed to vertexAttribPointer
    getTypedView(gltf)
    {
        if (this.typedView !== undefined)
        {
            return this.typedView;
        }

        if (this.bufferView !== undefined)
        {
            const bufferView = gltf.bufferViews[this.bufferView];
            const buffer = gltf.buffers[bufferView.buffer];
            const byteOffset = this.byteOffset + bufferView.byteOffset;

            const componentSize = this.getComponentSize(this.componentType);
            let componentCount = this.getComponentCount(this.type);

            let arrayLength = 0;
            if(bufferView.byteStride !== 0)
            {
                if (componentSize !== 0)
                {
                    arrayLength = bufferView.byteStride / componentSize * (this.count - 1) + componentCount;
                }
                else
                {
                    console.warn("Invalid component type in accessor '" + (this.name ? this.name : "") + "'");
                }
            }
            else
            {
                arrayLength = this.count * componentCount;
            }

            if (arrayLength * componentSize > buffer.buffer.byteLength - byteOffset)
            {
                arrayLength = (buffer.buffer.byteLength - byteOffset) / componentSize;
                console.warn("Count in accessor '" + (this.name ? this.name : "") + "' is too large.");
            }

            switch (this.componentType)
            {
            case GL.BYTE:
                this.typedView = new Int8Array(buffer.buffer, byteOffset, arrayLength);
                break;
            case GL.UNSIGNED_BYTE:
                this.typedView = new Uint8Array(buffer.buffer, byteOffset, arrayLength);
                break;
            case GL.SHORT:
                this.typedView = new Int16Array(buffer.buffer, byteOffset, arrayLength);
                break;
            case GL.UNSIGNED_SHORT:
                this.typedView = new Uint16Array(buffer.buffer, byteOffset, arrayLength);
                break;
            case GL.UNSIGNED_INT:
                this.typedView = new Uint32Array(buffer.buffer, byteOffset, arrayLength);
                break;
            case GL.FLOAT:
                this.typedView = new Float32Array(buffer.buffer, byteOffset, arrayLength);
                break;
            }
        }

        if (this.typedView === undefined)
        {
            console.warn("Failed to convert buffer view to typed view!: " + this.bufferView);
        }
        else if (this.sparse !== undefined)
        {
            this.applySparse(gltf, this.typedView);
        }

        return this.typedView;
    }

    // getNormalizedTypedView provides an alternative view to the accessors data,
    // where quantized data is already normalized. This is useful if the data is not passed
    // to vertexAttribPointer but used immediately (like e.g. animations)
    getNormalizedTypedView(gltf)
    {
        if(this.normalizedTypedView !== undefined)
        {
            return this.normalizedTypedView;
        }

        const typedView = this.getTypedView(gltf);
        this.normalizedTypedView = this.normalized ? gltfAccessor.dequantize(typedView, this.componentType) : typedView;
        return this.normalizedTypedView;
    }

    // getDeinterlacedView provides a view to the accessors data in form of
    // a TypedArray. In contrast to getTypedView, getDeinterlacedView deinterlaces
    // data, i.e. stripping padding and unrelated components from the array. It then
    // only contains the data of the accessor
    getDeinterlacedView(gltf)
    {
        if (this.filteredView !== undefined)
        {
            return this.filteredView;
        }

        if (this.bufferView !== undefined)
        {
            const bufferView = gltf.bufferViews[this.bufferView];
            const buffer = gltf.buffers[bufferView.buffer];
            const byteOffset = this.byteOffset + bufferView.byteOffset;

            const componentSize = this.getComponentSize(this.componentType);
            const componentCount = this.getComponentCount(this.type);
            const arrayLength = this.count * componentCount;

            let stride = bufferView.byteStride !== 0 ? bufferView.byteStride : componentCount * componentSize;
            let dv = new DataView(buffer.buffer, byteOffset, this.count * stride);

            let func = 'getFloat32';
            switch (this.componentType)
            {
            case GL.BYTE:
                this.filteredView = new Int8Array(arrayLength);
                func = 'getInt8';
                break;
            case GL.UNSIGNED_BYTE:
                this.filteredView = new Uint8Array(arrayLength);
                func = 'getUint8';
                break;
            case GL.SHORT:
                this.filteredView = new Int16Array(arrayLength);
                func = 'getInt16';
                break;
            case GL.UNSIGNED_SHORT:
                this.filteredView = new Uint16Array(arrayLength);
                func = 'getUint16';
                break;
            case GL.UNSIGNED_INT:
                this.filteredView = new Uint32Array(arrayLength);
                func = 'getUint32';
                break;
            case GL.FLOAT:
                this.filteredView = new Float32Array(arrayLength);
                func = 'getFloat32';
                break;
            }

            for(let i = 0; i < arrayLength; ++i)
            {
                let offset = Math.floor(i/componentCount) * stride + (i % componentCount) * componentSize;
                this.filteredView[i] = dv[func](offset, true);
            }
        }

        if (this.filteredView === undefined)
        {
            console.warn("Failed to convert buffer view to filtered view!: " + this.bufferView)
        }
        else if (this.sparse !== undefined)
        {
            this.applySparse(gltf, this.filteredView);
        }

        return this.filteredView;
    }

    // getNormalizedDeinterlacedView provides an alternative view to the accessors data,
    // where quantized data is already normalized. This is useful if the data is not passed
    // to vertexAttribPointer but used immediately (like e.g. animations)
    getNormalizedDeinterlacedView(gltf)
    {
        if(this.normalizedFilteredView !== undefined)
        {
            return this.normalizedFilteredView;
        }

        const filteredView = this.getDeinterlacedView(gltf);
        this.normalizedFilteredView = this.normalized ? gltfAccessor.dequantize(filteredView, this.componentType) : filteredView;
        return this.normalizedFilteredView;
    }

    applySparse(gltf, view)
    {
        // Gather indices.

        const indicesBufferView = gltf.bufferViews[this.sparse.indices.bufferView];
        const indicesBuffer = gltf.buffers[indicesBufferView.buffer];
        const indicesByteOffset = this.sparse.indices.byteOffset + indicesBufferView.byteOffset;

        const indicesComponentSize = this.getComponentSize(this.sparse.indices.componentType);
        let indicesComponentCount = 1;

        if(indicesBufferView.byteStride !== 0)
        {
            indicesComponentCount = indicesBufferView.byteStride / indicesComponentSize;
        }

        const indicesArrayLength = this.sparse.count * indicesComponentCount;

        let indicesTypedView;
        switch (this.sparse.indices.componentType)
        {
        case GL.UNSIGNED_BYTE:
            indicesTypedView = new Uint8Array(indicesBuffer.buffer, indicesByteOffset, indicesArrayLength);
            break;
        case GL.UNSIGNED_SHORT:
            indicesTypedView = new Uint16Array(indicesBuffer.buffer, indicesByteOffset, indicesArrayLength);
            break;
        case GL.UNSIGNED_INT:
            indicesTypedView = new Uint32Array(indicesBuffer.buffer, indicesByteOffset, indicesArrayLength);
            break;
        }

        // Gather values.

        const valuesBufferView = gltf.bufferViews[this.sparse.values.bufferView];
        const valuesBuffer = gltf.buffers[valuesBufferView.buffer];
        const valuesByteOffset = this.sparse.values.byteOffset + valuesBufferView.byteOffset;

        const valuesComponentSize = this.getComponentSize(this.componentType);
        let valuesComponentCount = this.getComponentCount(this.type);

        if(valuesBufferView.byteStride !== 0)
        {
            valuesComponentCount = valuesBufferView.byteStride / valuesComponentSize;
        }

        const valuesArrayLength = this.sparse.count * valuesComponentCount;

        let valuesTypedView;
        switch (this.componentType)
        {
        case GL.BYTE:
            valuesTypedView = new Int8Array(valuesBuffer.buffer, valuesByteOffset, valuesArrayLength);
            break;
        case GL.UNSIGNED_BYTE:
            valuesTypedView = new Uint8Array(valuesBuffer.buffer, valuesByteOffset, valuesArrayLength);
            break;
        case GL.SHORT:
            valuesTypedView = new Int16Array(valuesBuffer.buffer, valuesByteOffset, valuesArrayLength);
            break;
        case GL.UNSIGNED_SHORT:
            valuesTypedView = new Uint16Array(valuesBuffer.buffer, valuesByteOffset, valuesArrayLength);
            break;
        case GL.UNSIGNED_INT:
            valuesTypedView = new Uint32Array(valuesBuffer.buffer, valuesByteOffset, valuesArrayLength);
            break;
        case GL.FLOAT:
            valuesTypedView = new Float32Array(valuesBuffer.buffer, valuesByteOffset, valuesArrayLength);
            break;
        }

        // Overwrite values.

        for(let i = 0; i < this.sparse.count; ++i)
        {
            for(let k = 0; k < valuesComponentCount; ++k)
            {
                view[indicesTypedView[i] * valuesComponentCount + k] = valuesTypedView[i * valuesComponentCount + k];
            }
        }
    }

    // dequantize can be used to perform the normalization from WebGL2 vertexAttribPointer explicitly
    static dequantize(typedArray, componentType)
    {
        switch (componentType)
        {
        case GL.BYTE:
            return new Float32Array(typedArray).map(c => Math.max(c / 127.0, -1.0));
        case GL.UNSIGNED_BYTE:
            return new Float32Array(typedArray).map(c => c / 255.0);
        case GL.SHORT:
            return new Float32Array(typedArray).map(c => Math.max(c / 32767.0, -1.0));
        case GL.UNSIGNED_SHORT:
            return new Float32Array(typedArray).map(c => c / 65535.0);
        default:
            return typedArray;
        }
    }

    getComponentCount(type)
    {
        return CompononentCount.get(type);
    }

    getComponentSize(componentType)
    {
        switch (componentType)
        {
        case GL.BYTE:
        case GL.UNSIGNED_BYTE:
            return 1;
        case GL.SHORT:
        case GL.UNSIGNED_SHORT:
            return 2;
        case GL.UNSIGNED_INT:
        case GL.FLOAT:
            return 4;
        default:
            return 0;
        }
    }

    destroy()
    {
        if (this.glBuffer !== undefined)
        {
            // TODO: this breaks the dependency direction
            WebGl.context.deleteBuffer(this.glBuffer);
        }

        this.glBuffer = undefined;
    }
}

const CompononentCount = new Map(
    [
        ["SCALAR", 1],
        ["VEC2", 2],
        ["VEC3", 3],
        ["VEC4", 4],
        ["MAT2", 4],
        ["MAT3", 9],
        ["MAT4", 16]
    ]
);

export { gltfAccessor };
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import Editor, { createEditorStateWithText } from 'draft-js-plugins-editor';
import createHashtagPlugin from 'draft-js-hashtag-plugin';
import createStickerPlugin from 'draft-js-sticker-plugin';
import createLinkifyPlugin from 'draft-js-linkify-plugin';
import createMentionPlugin from 'draft-js-mention-plugin';
import createUndoPlugin from 'draft-js-undo-plugin';
import styles from './styles.css';
import stickers from './stickers';
import mentions from './mentions';
import StatePreview from '../../../shared/StatePreview';

const hashtagPlugin = createHashtagPlugin();
const linkifyPlugin = createLinkifyPlugin();
const mentionPlugin = createMentionPlugin({
  mentions,
});
const undoPlugin = createUndoPlugin();
const stickerPlugin = createStickerPlugin({
  stickers,
});
const { StickerSelect } = stickerPlugin;
const { UndoButton, RedoButton } = undoPlugin;

const plugins = [
  hashtagPlugin,
  stickerPlugin,
  linkifyPlugin,
  mentionPlugin,
];

export default class UnicornEditor extends Component {

  state = {
    editorState: createEditorStateWithText('Hello World!'),
    showState: false,
  };

  onChange = (editorState) => {
    this.setState({
      editorState,
    });
  };

  focus = () => {
    this.refs.editor.focus();
  };

  toggleShowState = () => {
    this.setState({
      showState: !this.state.showState,
    });
  };

  /* eslint-disable react/jsx-no-bind */
  render() {
    const stateButton = this.state.showState ? styles.pressedStateButton : styles.stateButton;

    return (

          <Editor
            editorState={this.state.editorState}
            onChange={this.onChange}
            plugins={plugins}
            spellCheck
            ref="editor"
          />

            <StickerSelect editor={ this } />

          <UndoButton
            editorState={ this.state.editorState }
            onChange={ this.onChange }
          />
          <RedoButton
            editorState={ this.state.editorState }
            onChange={ this.onChange }
          />
          <button
            className={ stateButton }
            onClick={ this.toggleShowState }
          >
            Toggle State Preview
          </button>

        <StatePreview
          editorState={ this.state.editorState }
          collapsed={ !this.state.showState }
        />

    );
  }
}
<commit_msg>update text<commit_after>import React, { Component } from 'react';
import Editor, { createEditorStateWithText } from 'draft-js-plugins-editor';
import createHashtagPlugin from 'draft-js-hashtag-plugin';
import createStickerPlugin from 'draft-js-sticker-plugin';
import createLinkifyPlugin from 'draft-js-linkify-plugin';
import createMentionPlugin from 'draft-js-mention-plugin';
import createUndoPlugin from 'draft-js-undo-plugin';
import styles from './styles.css';
import stickers from './stickers';
import mentions from './mentions';
import StatePreview from '../../../shared/StatePreview';

const hashtagPlugin = createHashtagPlugin();
const linkifyPlugin = createLinkifyPlugin();
const mentionPlugin = createMentionPlugin({
  mentions,
});
const undoPlugin = createUndoPlugin();
const stickerPlugin = createStickerPlugin({
  stickers,
});
const { StickerSelect } = stickerPlugin;
const { UndoButton, RedoButton } = undoPlugin;

const plugins = [
  hashtagPlugin,
  stickerPlugin,
  linkifyPlugin,
  mentionPlugin,
];

const text = `Once upon a time there was a new Editor. It was all about unicorns and supported features like #hashtags. It's creators like Jyoti, Nik or Julian could mentioned. Of course it also supports unicorn stickers like this one:

Of course it also supports Emojis 🤓🎉`;

export default class UnicornEditor extends Component {

  state = {
    editorState: createEditorStateWithText(text),
    showState: false,
  };

  onChange = (editorState) => {
    this.setState({
      editorState,
    });
  };

  focus = () => {
    this.refs.editor.focus();
  };

  toggleShowState = () => {
    this.setState({
      showState: !this.state.showState,
    });
  };

  /* eslint-disable react/jsx-no-bind */
  render() {
    const stateButton = this.state.showState ? styles.pressedStateButton : styles.stateButton;

    return (

          <Editor
            editorState={this.state.editorState}
            onChange={this.onChange}
            plugins={plugins}
            spellCheck
            ref="editor"
          />

            <StickerSelect editor={ this } />

          <UndoButton
            editorState={ this.state.editorState }
            onChange={ this.onChange }
          />
          <RedoButton
            editorState={ this.state.editorState }
            onChange={ this.onChange }
          />
          <button
            className={ stateButton }
            onClick={ this.toggleShowState }
          >
            Toggle State Preview
          </button>

        <StatePreview
          editorState={ this.state.editorState }
          collapsed={ !this.state.showState }
        />

    );
  }
}
<|endoftext|>


<commit_before>var maxIter = 200;

function f(z, c){
    return z.square().add(c);
}

var defaults = {
   x_min: -2,
   x_max: 0.75,
   y_min: -1.5,
   y_max: 1.5
};

function checkMandelbrotPoint(c, ratio) {
    var iterCount = maxIter;

    var cx = c.x, cy = c.y;

    if (checkCardiodOrSecondBulb(cx, cy)) {
        return {inSet: true};
    }

    var x = 0, y = 0, prevX = NaN, prevY = NaN;
    for (var i = 1; i <= iterCount; i++) {
        prevX = x;
        prevY = y;
        x = x*x - y*y + cx;
        y = 2 * prevX * prevY + cy;

        if (x == prevX && y == prevY) {
            return {inSet: true};
        }

        if (x*x+y*y > 4) {
            return {inSet: false, iteration: i};
        }
    }

    return {inSet: true};
}

// Optimization check
// Details: http://en.wikipedia.org/wiki/Mandelbrot_set#Cardioid_.2F_bulb_checking
function checkCardiodOrSecondBulb(x, y) {
    var p = (x - 1/4);
    var q = p*p + y*y;
    return q * (q + p) < 1/4 * y*y;
}

function colorMandelbrotPoint(pointData) {
    if (pointData.inSet) {
        return "#000000";
    } else {
        var colorRate = Math.round(255 * (1 - pointData.iteration / maxIter));
        var color = 'rgb(' + colorRate + ',' + colorRate + ',' + colorRate + ')';
        return color;
    }
}

var canvasManager;

window.onload = function (){
    canvasManager = new CanvasManager('main', 'zoom', defaults, checkMandelbrotPoint, colorMandelbrotPoint);
    canvasManager.drawSet();

    var resetButton = document.getElementsByClassName('resetButton')[0];
    resetButton.onclick = function () {
        canvasManager.resetZoom();
    }
}<commit_msg>Basic linear gradient implementation<commit_after>var maxIter = 200;

function f(z, c){
    return z.square().add(c);
}

var defaults = {
   x_min: -2,
   x_max: 0.75,
   y_min: -1.5,
   y_max: 1.5
};

function checkMandelbrotPoint(c, ratio) {
    var iterCount = maxIter;

    var cx = c.x, cy = c.y;

    if (checkCardiodOrSecondBulb(cx, cy)) {
        return {inSet: true};
    }

    var x = 0, y = 0, prevX = NaN, prevY = NaN;
    for (var i = 1; i <= iterCount; i++) {
        prevX = x;
        prevY = y;
        x = x*x - y*y + cx;
        y = 2 * prevX * prevY + cy;

        if (x == prevX && y == prevY) {
            return {inSet: true};
        }

        if (x*x+y*y > 4) {
            return {inSet: false, iteration: i};
        }
    }

    return {inSet: true};
}

// Optimization check
// Details: http://en.wikipedia.org/wiki/Mandelbrot_set#Cardioid_.2F_bulb_checking
function checkCardiodOrSecondBulb(x, y) {
    var p = (x - 1/4);
    var q = p*p + y*y;
    return q * (q + p) < 1/4 * y*y;
}

var inSetHue = {r: 0, g: 0, b: 0};
var orangeRedHue = {r: 220, g: 20, b: 60}
function getColor(minHue, maxHue, rate) {
    var r = Math.round((maxHue.r - minHue.r) * rate);
    var g = Math.round((maxHue.g - minHue.g) * rate);
    var b = Math.round((maxHue.b - minHue.b) * rate);

    return 'rgb(' + r + ',' + g + ',' + b + ')';
}

function linearGradient(pointData) {
    if (pointData.inSet) {
        return getColor(inSetHue, orangeRedHue, 0);
    } else {
        var colorRate = 1 - pointData.iteration / maxIter;
        return getColor(inSetHue, orangeRedHue, colorRate);
    }
}

var canvasManager;

window.onload = function (){
    canvasManager = new CanvasManager('main', 'zoom', defaults, checkMandelbrotPoint, linearGradient);
    canvasManager.drawSet();

    var resetButton = document.getElementsByClassName('resetButton')[0];
    resetButton.onclick = function () {
        canvasManager.resetZoom();
    }
}<|endoftext|>