<commit_before>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2016, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

import React, { PropTypes } from 'react';
import _ from 'lodash';

import Header from '../common/Header';
import Table from '../common/Table';
import CollapsibleContainer from '../common/CollapsibleContainer';

import * as constants from '../../../utils/constants';
import * as data from '../../../utils/settings/data';

import styles from './NonTandem.css';

const NonTandem = (props) => {
  const {
    bgTargetColumns,
    bgTargetLabel,
    bgUnits,
    bolusSettingsLabel,
    carbRatioLabel,
    deviceType,
    insulinSensitivityLabel,
    manufacturerKey,
    pumpSettings,
    timePrefs,
  } = props;

  const renderBasalsData = () => {
    const schedules = data.getScheduleNames(pumpSettings.basalSchedules);

    const tables = _.map(schedules, (schedule) => {
      let scheduleName = pumpSettings.basalSchedules[schedule].name;
      if (manufacturerKey === 'carelink') {
        scheduleName = _.map(scheduleName.split(' '), (part) => (_.capitalize(part))).join(' ');
      }
      const label = data.getScheduleLabel(
        scheduleName,
        pumpSettings.activeSchedule,
      );

      if (pumpSettings.basalSchedules[schedule].name === pumpSettings.activeSchedule) {
        return (

            <CollapsibleContainer
              label={label}
              labelClass={styles.twoLineBasalScheduleHeader}
              openByDefault
              twoLineLabel
            >

            </CollapsibleContainer>

        );
      }
      return (

          <CollapsibleContainer
            label={label}
            labelClass={styles.singleLineBasalScheduleHeader}
            openByDefault={false}
          >

          </CollapsibleContainer>

      );
    });
    return (
{tables}
);
  };

  const renderSensitivityData = () => {
    const title = {
      label: {
        main: insulinSensitivityLabel,
        secondary: `${bgUnits}/U`,
      },
      className: styles.bolusSettingsHeader,
    };
    return (

    );
  };

  const renderRatioData = () => {
    const title = {
      label: {
        main: carbRatioLabel,
        secondary: 'g/U',
      },
      className: styles.bolusSettingsHeader,
    };
    return (

    );
  };

  const renderTargetData = () => {
    const title = {
      label: {
        main: bgTargetLabel,
        secondary: bgUnits,
      },
      className: styles.bolusSettingsHeader,
    };
    return (

    );
  };

  return (

Basal Rates

          {renderBasalsData()}

{bolusSettingsLabel}

            {renderSensitivityData()}
            {renderTargetData()}
            {renderRatioData()}

  );
};

NonTandem.propTypes = {
  bgTargetColumns: PropTypes.arrayOf(PropTypes.shape({
    key: PropTypes.string.isRequired,
    label: PropTypes.string.isRequired,
  }).isRequired).isRequired,
  bgTargetLabel: PropTypes.string.isRequired,
  bgUnits: PropTypes.oneOf([constants.MMOLL_UNITS, constants.MGDL_UNITS]).isRequired,
  bolusSettingsLabel: PropTypes.string.isRequired,
  carbRatioLabel: PropTypes.string.isRequired,
  deviceType: PropTypes.string.isRequired,
  insulinSensitivityLabel: PropTypes.string.isRequired,
  manufacturerKey: PropTypes.oneOf(['animas', 'carelink', 'insulet']),
  timePrefs: PropTypes.shape({
    timezoneAware: PropTypes.bool.isRequired,
    timezoneName: PropTypes.oneOfType([PropTypes.string, null]),
  }).isRequired,
  pumpSettings: PropTypes.shape({
    activeSchedule: PropTypes.string.isRequired,
    units: PropTypes.object.isRequired,
    deviceId: PropTypes.string.isRequired,
    basalSchedules: PropTypes.arrayOf(
      PropTypes.shape({
        name: PropTypes.string.isRequired,
        value: PropTypes.arrayOf(
          PropTypes.shape({
            start: PropTypes.number.isRequired,
            rate: PropTypes.number.isRequired,
          }),
        ),
      }),
    ).isRequired,
    bgTarget: PropTypes.arrayOf(
      PropTypes.shape({
        start: PropTypes.number.isRequired,
        target: PropTypes.number,
        range: PropTypes.number,
      })
    ).isRequired,
    carbRatio: PropTypes.arrayOf(
      PropTypes.shape({
        start: PropTypes.number.isRequired,
        amount: PropTypes.number.isRequired,
      })
    ).isRequired,
    insulinSensitivity: PropTypes.arrayOf(
      PropTypes.shape({
        start: PropTypes.number.isRequired,
        amount: PropTypes.number.isRequired,
      })
    ).isRequired,
  }).isRequired,
};

export default NonTandem;
<commit_msg>oops, do specific BG units constants for NonTandem too<commit_after>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2016, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

import React, { PropTypes } from 'react';
import _ from 'lodash';

import Header from '../common/Header';
import Table from '../common/Table';
import CollapsibleContainer from '../common/CollapsibleContainer';

import { MGDL_UNITS, MMOLL_UNITS } from '../../../utils/constants';
import * as data from '../../../utils/settings/data';

import styles from './NonTandem.css';

const NonTandem = (props) => {
  const {
    bgTargetColumns,
    bgTargetLabel,
    bgUnits,
    bolusSettingsLabel,
    carbRatioLabel,
    deviceType,
    insulinSensitivityLabel,
    manufacturerKey,
    pumpSettings,
    timePrefs,
  } = props;

  const renderBasalsData = () => {
    const schedules = data.getScheduleNames(pumpSettings.basalSchedules);

    const tables = _.map(schedules, (schedule) => {
      let scheduleName = pumpSettings.basalSchedules[schedule].name;
      if (manufacturerKey === 'carelink') {
        scheduleName = _.map(scheduleName.split(' '), (part) => (_.capitalize(part))).join(' ');
      }
      const label = data.getScheduleLabel(
        scheduleName,
        pumpSettings.activeSchedule,
      );

      if (pumpSettings.basalSchedules[schedule].name === pumpSettings.activeSchedule) {
        return (

            <CollapsibleContainer
              label={label}
              labelClass={styles.twoLineBasalScheduleHeader}
              openByDefault
              twoLineLabel
            >

            </CollapsibleContainer>

        );
      }
      return (

          <CollapsibleContainer
            label={label}
            labelClass={styles.singleLineBasalScheduleHeader}
            openByDefault={false}
          >

          </CollapsibleContainer>

      );
    });
    return (
{tables}
);
  };

  const renderSensitivityData = () => {
    const title = {
      label: {
        main: insulinSensitivityLabel,
        secondary: `${bgUnits}/U`,
      },
      className: styles.bolusSettingsHeader,
    };
    return (

    );
  };

  const renderRatioData = () => {
    const title = {
      label: {
        main: carbRatioLabel,
        secondary: 'g/U',
      },
      className: styles.bolusSettingsHeader,
    };
    return (

    );
  };

  const renderTargetData = () => {
    const title = {
      label: {
        main: bgTargetLabel,
        secondary: bgUnits,
      },
      className: styles.bolusSettingsHeader,
    };
    return (

    );
  };

  return (

Basal Rates

          {renderBasalsData()}

{bolusSettingsLabel}

            {renderSensitivityData()}
            {renderTargetData()}
            {renderRatioData()}

  );
};

NonTandem.propTypes = {
  bgTargetColumns: PropTypes.arrayOf(PropTypes.shape({
    key: PropTypes.string.isRequired,
    label: PropTypes.string.isRequired,
  }).isRequired).isRequired,
  bgTargetLabel: PropTypes.string.isRequired,
  bgUnits: PropTypes.oneOf([MMOLL_UNITS, MGDL_UNITS]).isRequired,
  bolusSettingsLabel: PropTypes.string.isRequired,
  carbRatioLabel: PropTypes.string.isRequired,
  deviceType: PropTypes.string.isRequired,
  insulinSensitivityLabel: PropTypes.string.isRequired,
  manufacturerKey: PropTypes.oneOf(['animas', 'carelink', 'insulet']),
  timePrefs: PropTypes.shape({
    timezoneAware: PropTypes.bool.isRequired,
    timezoneName: PropTypes.oneOfType([PropTypes.string, null]),
  }).isRequired,
  pumpSettings: PropTypes.shape({
    activeSchedule: PropTypes.string.isRequired,
    units: PropTypes.object.isRequired,
    deviceId: PropTypes.string.isRequired,
    basalSchedules: PropTypes.arrayOf(
      PropTypes.shape({
        name: PropTypes.string.isRequired,
        value: PropTypes.arrayOf(
          PropTypes.shape({
            start: PropTypes.number.isRequired,
            rate: PropTypes.number.isRequired,
          }),
        ),
      }),
    ).isRequired,
    bgTarget: PropTypes.arrayOf(
      PropTypes.shape({
        start: PropTypes.number.isRequired,
        target: PropTypes.number,
        range: PropTypes.number,
      })
    ).isRequired,
    carbRatio: PropTypes.arrayOf(
      PropTypes.shape({
        start: PropTypes.number.isRequired,
        amount: PropTypes.number.isRequired,
      })
    ).isRequired,
    insulinSensitivity: PropTypes.arrayOf(
      PropTypes.shape({
        start: PropTypes.number.isRequired,
        amount: PropTypes.number.isRequired,
      })
    ).isRequired,
  }).isRequired,
};

export default NonTandem;
<|endoftext|>


<commit_before>
const API_BLUEPRINT_HEADER = /^[\uFEFF]?(((VERSION:( |\t)2)|(FORMAT:( |\t)(X-)?1A))([\n\r]{1,2}|$))/i;
const API_BLUEPRINT_RESPONSE = /\+\s+Response\s+\d{3}/i;

const LEGACY_BLUEPRINT_TITLE = /\-{3} ([^\n\r]+ )?\-{3}([\n\r]{1,2}|$)/;

/**
 * Identifies given source.
 * @param {string} source - The source code of API description file.
 * @returns {string|null} Media type of given file.
 */
function identify(source) {
  // Stay awhile and listen!

  try {
    const json = JSON.parse(source);

    // It looks like the source is a valid JSON file. I suspect it to
    // be a Swagger file.
    if (json.swagger) {
      // Indeed, we are dealing with Swagger file!
      return 'application/swagger+json';
    }

    // Nothing I could identify. Maybe Horadric Cube could magically
    // turn it into a rather smart casual leather armor?
    return null;
  } catch(e) {
    // Oh! It almost blew up! I should be more careful. I'll better
    // treat the item as a plain text file.

    if (source.match(API_BLUEPRINT_HEADER)) {
      // I spotted 'FORMAT: 1A' header, which gives us a clear clue that
      // the file is API Blueprint.
      return 'text/vnd.apiblueprint';
    }

    if (source.match(LEGACY_BLUEPRINT_TITLE)) {
      // I spotted '--- Sample Title ---' title. This looks like
      // we are dealing with the legacy Apiary Blueprint.
      return 'text/vnd.legacyblueprint';
    }

    if (source.match(API_BLUEPRINT_RESPONSE)) {
      // I can not see the '--- Sample Title ---' and at the same time
      // there is something like '+ Response 200' in the document, which is
      // pretty distinctive for API Blueprint.
      return 'text/vnd.apiblueprint';
    }

    // I do not know. Very strange item!
    return null;
  }
}

export default {identify};
<commit_msg>Moded swagger detect on bottom, as it may be slow<commit_after>
const API_BLUEPRINT_HEADER = /^[\uFEFF]?(((VERSION:( |\t)2)|(FORMAT:( |\t)(X-)?1A))([\n\r]{1,2}|$))/i;
const API_BLUEPRINT_RESPONSE = /\+\s+Response\s+\d{3}/i;

const LEGACY_BLUEPRINT_TITLE = /\-{3} ([^\n\r]+ )?\-{3}([\n\r]{1,2}|$)/;

/**
 * Identifies given source.
 * @param {string} source - The source code of API description file.
 * @returns {string|null} Media type of given file.
 */
function identify(source) {
  // Stay awhile and listen!

  if (source.match(API_BLUEPRINT_HEADER)) {
    // I spotted 'FORMAT: 1A' header, which gives us a clear clue that
    // the file is API Blueprint.
    return 'text/vnd.apiblueprint';
  }

  if (source.match(LEGACY_BLUEPRINT_TITLE)) {
    // I spotted '--- Sample Title ---' title. This looks like
    // we are dealing with the legacy Apiary Blueprint.
    return 'text/vnd.legacyblueprint';
  }

  if (source.match(API_BLUEPRINT_RESPONSE)) {
    // I can not see the '--- Sample Title ---' and at the same time
    // there is something like '+ Response 200' in the document, which is
    // pretty distinctive for API Blueprint.
    return 'text/vnd.apiblueprint';
  }

  try {
    const json = JSON.parse(source);

    // It looks like the source is a valid JSON file. I suspect it to
    // be a Swagger file.
    if (json.swagger) {
      // Indeed, we are dealing with Swagger file!
      return 'application/swagger+json';
    }

    // Nothing I could identify. Maybe Horadric Cube could magically
    // turn it into a rather smart casual leather armor?
    return null;
  } catch(e) {
    return null;
  }
}

export default {identify};
<|endoftext|>


<commit_before>define(["wasm/ast", "wasm/typeinfo"], function(wast, typeinfo) {

  var SemanticPass = function(status) {
    this.status = status;
  };

  SemanticPass.prototype.error = function(message, pos) {
    this.status.error(message, pos);
    this.dead = true;
  };

  SemanticPass.prototype.setExprType = function(expr, t) {
    if(typeof t != "string") {
      console.log(Error(t));
      throw t;
    }
    expr.etype = t;
  };

  SemanticPass.prototype.processExpr = function(expr) {
    var old_dead = this.dead;
    this.dead = false;

    switch(expr.type) {
    case "ConstI32":
      this.setExprType(expr, "i32");
      expr.etype = "i32";
      break;
    case "ConstF32":
      this.setExprType(expr, "f32");
      break;
    case "ConstF64":
      this.setExprType(expr, "f64");
      break;
    case "GetName":
      var name = expr.name.text;
      var ref = this.localScope[name];
      if (ref !== undefined) {
	var expr = wast.GetLocal({index: ref.index});
	this.setExprType(expr, ref.ltype);
	break;
      } else {
	var ref = this.moduleScope[name];
	if (ref !== undefined) {
	  switch(ref.type) {
	  case "Function":
	    expr = wast.GetFunction({index: ref.index});
	    break;
          case "Extern":
	    expr = wast.GetExtern({index: ref.index});
	    break;
          case "MemoryDecl":
	    expr = wast.ConstI32({
	      value: ref.ptr
	    });
	    this.setExprType(expr, "i32");
	    break;
	  default:
	    console.log(ref);
	    throw ref;
	  }
	  break;
	} else {
	  this.error("cannot resolve name - " + name, expr.name.pos);
	}
      }
      break;
    case "SetName":
      var name = expr.name.text;
      var ref = this.localScope[name];
      if (ref !== undefined) {
	expr = wast.SetLocal({
	  index: ref.index,
	  value: this.processExpr(expr.value)
	});
	this.setExprType(expr, "void");
	break;
      } else {
	this.error("cannot assign to name - " + name, expr.name.pos);
      }
      break;
    case "Load":
      expr.address = this.processExpr(expr.address);
      // TODO type check
      this.setExprType(expr, expr.mtype);
      break;
    case "Store":
      expr.address = this.processExpr(expr.address);
      expr.value = this.processExpr(expr.value);
      // TODO type check
      this.setExprType(expr, expr.mtype);
      break;
    case "BinaryOp":
      expr.left = this.processExpr(expr.left);
      expr.right = this.processExpr(expr.right);
      if (!this.dead) {
	if (expr.left.etype != expr.right.etype) {
	  this.error("binary op type error - " + expr.left.etype + expr.op + expr.right.etype + " = ???");
	}
	switch (expr.op) {
	case "<":
	case "<=":
	case ">":
	case ">=":
	case "==":
	case "!=":
	  this.setExprType(expr, "i32");
	  break;
	default:
	  this.setExprType(expr, expr.left.etype);
	}
      }
      break;
    case "Call":
      expr.expr = this.processExpr(expr.expr);
      if (!this.dead) {
	switch (expr.expr.type) {
	case "GetFunction":
	  expr = wast.CallDirect({
	    func: expr.expr.index,
	    args: expr.args,
	  });
	  break;
	case "GetExtern":
	  expr = wast.CallExternal({
	    func: expr.expr.index,
	    args: expr.args,
	  });
	  break;
	default:
	  console.log(expr);
	  throw expr.expr;
	}
      }

      // Process arguments
      for (var i = 0; i < expr.args.length; i++) {
	expr.args[i] = this.processExpr(expr.args[i]);
      }

      if (!this.dead) {
	switch (expr.type) {
	case "CallDirect":
	  var target = this.module.funcs[expr.func];
	  if (expr.args.length != target.params.length) {
	    this.error("argument count mismatch");
	    console.log(target);
	    throw expr.args.length;
	  }
	  for (var i = 0; i < expr.args.length; i++) {
	    var arg = expr.args[i];
	    if (arg.etype != target.params[i].ptype) {
	      console.log(i, arg.etype, params[i].ptype);
	      throw expr;
	    }
	  }
	  this.setExprType(expr, target.returnType);
	  break;
	case "CallExternal":
	  var target = this.module.externs[expr.func];
	  if (expr.args.length != target.args.length) {
	    this.error("argument count mismatch");
	    console.log(target);
	    throw expr.args.length;
	  }
	  for (var i = 0; i < expr.args.length; i++) {
	    var arg = expr.args[i];
	    if (arg.etype != target.args[i]) {
	      console.log(i, arg.etype, target.args[i]);
	      throw expr;
	    }
	  }
	  this.setExprType(expr, target.returnType);
	  break;
	default:
	  console.log(expr);
	  throw expr;
	}
      }
      break;
    case "Return":
      expr.expr = this.processExpr(expr.expr);
      this.setExprType(expr, "void");
      if (!this.dead && expr.expr.etype != this.func.returnType) {
	this.error("return type mismatch - " + expr.expr.etype + " vs. " + this.func.returnType);
      }
      break;
    case "If":
      expr.cond = this.processExpr(expr.cond);
      if (!this.dead && expr.cond.etype != "i32") {
	this.error("condition type mismatch - " + expr.cond.etype + " vs. i32");
      }

      expr.t = this.processBlock(expr.t);
      if (expr.f != null) {
	expr.f = this.processBlock(expr.f);
      }
      this.setExprType(expr, "void");
      break;
    case "While":
      expr.cond = this.processExpr(expr.cond);
      expr.body = this.processBlock(expr.body);
      this.setExprType(expr, "void");
      break;
    default:
      console.log(expr);
      throw expr;
    }

    this.dead = this.dead || old_dead;
    return expr;
  };

  SemanticPass.prototype.processType = function(type) {
    var t = type.text;
    switch (t) {
    case "i32":
    case "f32":
    case "f64":
    case "void":
      break;
    default:
      this.error("unknown type - " + type.text, type.pos);
    }
    return t;
  };

  SemanticPass.prototype.createLocal = function(name, type) {
    if (typeof name !== "string") {
      throw Error(name);
    }
    if (typeof type !== "string") {
      throw Error(type);
    }

    if (name in this.localScope) {
      this.error("attemped to redeclare " + name);
      return -1;
    }

    var lcl = wast.Local({
      name: name,
      ltype: type,
      index: this.func.locals.length
    });
    this.func.locals.push(lcl);
    this.localScope[name] = lcl;
    return lcl.index;
  };

  SemanticPass.prototype.processStmt = function(node, block) {
    switch (node.type) {
    case "VarDecl":
      var t = this.processType(node.vtype);
      var index = this.createLocal(node.name.text, t);
      if (node.value) {
	node = wast.SetLocal({
	  index: index,
	  value: this.processExpr(node.value),
	});
	this.setExprType(node, "void");
	block.push(node);
      }
      break;
    default:
      block.push(this.processExpr(node));
    }
  };

  SemanticPass.prototype.processBlock = function(block) {
    if (block === null) {
      return block;
    }
    var old_dead = this.dead;
    var out = []
    for (var i in block) {
      this.processStmt(block[i], out);
    }
    this.dead = this.dead || old_dead;
    return out;
  };

  SemanticPass.prototype.processFunction = function(func) {
    this.func = func;
    this.localScope = {};

    this.dead = false;

    for (var i in func.params) {
      var p = func.params[i];
      p.index = this.createLocal(p.name.text, p.ptype);
    }
    func.body = this.processBlock(func.body);
  };

  SemanticPass.prototype.processExternSig = function(extern) {
    for (var i in extern.args) {
      extern.args[i] = this.processType(extern.args[i]);
    }
    extern.returnType = this.processType(extern.returnType);
  };

  SemanticPass.prototype.processFuncSig = function(func) {
    for (var i in func.params) {
      var p = func.params[i];
      p.ptype = this.processType(p.ptype);
    }
    func.returnType = this.processType(func.returnType);
  };

  SemanticPass.prototype.registerInModule = function(name, decl) {
    if (name.text in this.moduleScope) {
      this.error("attempted to redefine name - " + name.text, name.pos);
    } else {
      this.moduleScope[name.text] = decl;
    }
  };

  SemanticPass.prototype.indexModule = function(module) {
    this.moduleScope = {};
    for (var i = 0; i < module.externs.length; i++) {
      var e = module.externs[i];
      e.index = i;
      this.registerInModule(e.name, e);
      this.processExternSig(e);
    }
    for (var i = 0; i < module.funcs.length; i++) {
      var func = module.funcs[i];
      func.index = i;
      this.registerInModule(func.name, func);
      this.processFuncSig(func);
    }

    // Zero is null, so don't use that.
    var ptr = 8;
    for (var i in module.memory) {
      var mem = module.memory[i];
      mem.mtype = this.processType(mem.mtype);

      var size = typeinfo.sizeOf(mem.mtype);

      // Align
      if (ptr % size != 0) {
	ptr += size - ptr % size;
      }

      // Allocate
      mem.ptr = ptr;
      ptr += size;

      this.registerInModule(mem.name, mem);
    }
  };

  SemanticPass.prototype.processModule = function(module) {
    if (module.type != "ParsedModule") {
      console.log(module);
      throw module.type;
    }

    // Bucket the declarations.
    var externs = [];
    var funcs = [];
    var memory = [];
    for (var i in module.decls) {
      var decl = module.decls[i];
      switch (decl.type) {
      case "Function":
	funcs.push(decl);
	break;
      case "Extern":
	externs.push(decl);
	break;
      case "MemoryDecl":
	memory.push(decl);
	break;
      default:
	console.log(decl);
	throw decl.type;
      }
    }

    module = wast.Module({
      externs: externs,
      funcs: funcs,
      memory: memory,
    });

    this.module = module;
    this.indexModule(module);
    if (!this.dead) {
      for (var i in module.funcs) {
	this.processFunction(module.funcs[i]);
      }
    }
    return module;
  };

  var processModule = function(module, status) {
    var semantic = new SemanticPass(status);
    return semantic.processModule(module);
  };

  return {
    processModule: processModule,
  };

});
<commit_msg>Better handling of argument type errors.<commit_after>define(["wasm/ast", "wasm/typeinfo"], function(wast, typeinfo) {

  var SemanticPass = function(status) {
    this.status = status;
  };

  SemanticPass.prototype.error = function(message, pos) {
    this.status.error(message, pos);
    this.dead = true;
  };

  SemanticPass.prototype.setExprType = function(expr, t) {
    if(typeof t != "string") {
      console.log(Error(t));
      throw t;
    }
    expr.etype = t;
  };

  SemanticPass.prototype.processExpr = function(expr) {
    var old_dead = this.dead;
    this.dead = false;

    switch(expr.type) {
    case "ConstI32":
      this.setExprType(expr, "i32");
      expr.etype = "i32";
      break;
    case "ConstF32":
      this.setExprType(expr, "f32");
      break;
    case "ConstF64":
      this.setExprType(expr, "f64");
      break;
    case "GetName":
      var name = expr.name.text;
      var ref = this.localScope[name];
      if (ref !== undefined) {
	var expr = wast.GetLocal({index: ref.index});
	this.setExprType(expr, ref.ltype);
	break;
      } else {
	var ref = this.moduleScope[name];
	if (ref !== undefined) {
	  switch(ref.type) {
	  case "Function":
	    expr = wast.GetFunction({index: ref.index});
	    break;
          case "Extern":
	    expr = wast.GetExtern({index: ref.index});
	    break;
          case "MemoryDecl":
	    expr = wast.ConstI32({
	      value: ref.ptr
	    });
	    this.setExprType(expr, "i32");
	    break;
	  default:
	    console.log(ref);
	    throw ref;
	  }
	  break;
	} else {
	  this.error("cannot resolve name - " + name, expr.name.pos);
	}
      }
      break;
    case "SetName":
      var name = expr.name.text;
      var ref = this.localScope[name];
      if (ref !== undefined) {
	expr = wast.SetLocal({
	  index: ref.index,
	  value: this.processExpr(expr.value)
	});
	this.setExprType(expr, "void");
	break;
      } else {
	this.error("cannot assign to name - " + name, expr.name.pos);
      }
      break;
    case "Load":
      expr.address = this.processExpr(expr.address);
      // TODO type check
      this.setExprType(expr, expr.mtype);
      break;
    case "Store":
      expr.address = this.processExpr(expr.address);
      expr.value = this.processExpr(expr.value);
      // TODO type check
      this.setExprType(expr, expr.mtype);
      break;
    case "BinaryOp":
      expr.left = this.processExpr(expr.left);
      expr.right = this.processExpr(expr.right);
      if (!this.dead) {
	if (expr.left.etype != expr.right.etype) {
	  this.error("binary op type error - " + expr.left.etype + expr.op + expr.right.etype + " = ???");
	}
	switch (expr.op) {
	case "<":
	case "<=":
	case ">":
	case ">=":
	case "==":
	case "!=":
	  this.setExprType(expr, "i32");
	  break;
	default:
	  this.setExprType(expr, expr.left.etype);
	}
      }
      break;
    case "Call":
      expr.expr = this.processExpr(expr.expr);
      if (!this.dead) {
	switch (expr.expr.type) {
	case "GetFunction":
	  expr = wast.CallDirect({
	    func: expr.expr.index,
	    args: expr.args,
	  });
	  break;
	case "GetExtern":
	  expr = wast.CallExternal({
	    func: expr.expr.index,
	    args: expr.args,
	  });
	  break;
	default:
	  console.log(expr);
	  throw expr.expr;
	}
      }

      // Process arguments
      for (var i = 0; i < expr.args.length; i++) {
	expr.args[i] = this.processExpr(expr.args[i]);
      }

      if (!this.dead) {
	switch (expr.type) {
	case "CallDirect":
	  var target = this.module.funcs[expr.func];

	  if (expr.args.length != target.params.length) {
	    this.error("argument count mismatch - got " + expr.args.length + ", but expected " + target.params.length);
	  }

	  this.setExprType(expr, target.returnType);

	  if (!this.dead) {
	    for (var i = 0; i < expr.args.length; i++) {
	      var arg = expr.args[i];
	      if (arg.etype != target.params[i].ptype) {
		this.error("arg " + i + " - got " + arg.etype + ", but expected " + target.params[i].ptype);
	      }
	    }
	  }
	  break;
	case "CallExternal":
	  var target = this.module.externs[expr.func];

	  if (expr.args.length != target.args.length) {
	    this.error("argument count mismatch - got " + expr.args.length + ", but expected " + target.args.length);
	  }

	  this.setExprType(expr, target.returnType);

	  if (!this.dead) {
	    for (var i = 0; i < expr.args.length; i++) {
	      var arg = expr.args[i];
	      if (arg.etype != target.args[i]) {
		this.error("arg " + i + " - got " + arg.etype + ", but expected " + target.args[i]);
	      }
	    }
	  }
	  break;
	default:
	  console.log(expr);
	  throw expr;
	}
      }
      break;
    case "Return":
      expr.expr = this.processExpr(expr.expr);
      this.setExprType(expr, "void");
      if (!this.dead && expr.expr.etype != this.func.returnType) {
	this.error("return type mismatch - " + expr.expr.etype + " vs. " + this.func.returnType);
      }
      break;
    case "If":
      expr.cond = this.processExpr(expr.cond);
      if (!this.dead && expr.cond.etype != "i32") {
	this.error("condition type mismatch - " + expr.cond.etype + " vs. i32");
      }

      expr.t = this.processBlock(expr.t);
      if (expr.f != null) {
	expr.f = this.processBlock(expr.f);
      }
      this.setExprType(expr, "void");
      break;
    case "While":
      expr.cond = this.processExpr(expr.cond);
      if (!this.dead && expr.cond.etype != "i32") {
	this.error("condition type mismatch - " + expr.cond.etype + " vs. i32");
      }
      expr.body = this.processBlock(expr.body);
      this.setExprType(expr, "void");
      break;
    default:
      console.log(expr);
      throw expr;
    }

    this.dead = this.dead || old_dead;
    return expr;
  };

  SemanticPass.prototype.processType = function(type) {
    var t = type.text;
    switch (t) {
    case "i32":
    case "f32":
    case "f64":
    case "void":
      break;
    default:
      this.error("unknown type - " + type.text, type.pos);
    }
    return t;
  };

  SemanticPass.prototype.createLocal = function(name, type) {
    if (typeof name !== "string") {
      throw Error(name);
    }
    if (typeof type !== "string") {
      throw Error(type);
    }

    if (name in this.localScope) {
      this.error("attemped to redeclare " + name);
      return -1;
    }

    var lcl = wast.Local({
      name: name,
      ltype: type,
      index: this.func.locals.length
    });
    this.func.locals.push(lcl);
    this.localScope[name] = lcl;
    return lcl.index;
  };

  SemanticPass.prototype.processStmt = function(node, block) {
    switch (node.type) {
    case "VarDecl":
      var t = this.processType(node.vtype);
      var index = this.createLocal(node.name.text, t);
      if (node.value) {
	node = wast.SetLocal({
	  index: index,
	  value: this.processExpr(node.value),
	});
	this.setExprType(node, "void");
	block.push(node);
      }
      break;
    default:
      block.push(this.processExpr(node));
    }
  };

  SemanticPass.prototype.processBlock = function(block) {
    if (block === null) {
      return block;
    }
    var old_dead = this.dead;
    var out = []
    for (var i in block) {
      this.processStmt(block[i], out);
    }
    this.dead = this.dead || old_dead;
    return out;
  };

  SemanticPass.prototype.processFunction = function(func) {
    this.func = func;
    this.localScope = {};

    this.dead = false;

    for (var i in func.params) {
      var p = func.params[i];
      p.index = this.createLocal(p.name.text, p.ptype);
    }
    func.body = this.processBlock(func.body);
  };

  SemanticPass.prototype.processExternSig = function(extern) {
    for (var i in extern.args) {
      extern.args[i] = this.processType(extern.args[i]);
    }
    extern.returnType = this.processType(extern.returnType);
  };

  SemanticPass.prototype.processFuncSig = function(func) {
    for (var i in func.params) {
      var p = func.params[i];
      p.ptype = this.processType(p.ptype);
    }
    func.returnType = this.processType(func.returnType);
  };

  SemanticPass.prototype.registerInModule = function(name, decl) {
    if (name.text in this.moduleScope) {
      this.error("attempted to redefine name - " + name.text, name.pos);
    } else {
      this.moduleScope[name.text] = decl;
    }
  };

  SemanticPass.prototype.indexModule = function(module) {
    this.moduleScope = {};
    for (var i = 0; i < module.externs.length; i++) {
      var e = module.externs[i];
      e.index = i;
      this.registerInModule(e.name, e);
      this.processExternSig(e);
    }
    for (var i = 0; i < module.funcs.length; i++) {
      var func = module.funcs[i];
      func.index = i;
      this.registerInModule(func.name, func);
      this.processFuncSig(func);
    }

    // Zero is null, so don't use that.
    var ptr = 8;
    for (var i in module.memory) {
      var mem = module.memory[i];
      mem.mtype = this.processType(mem.mtype);

      var size = typeinfo.sizeOf(mem.mtype);

      // Align
      if (ptr % size != 0) {
	ptr += size - ptr % size;
      }

      // Allocate
      mem.ptr = ptr;
      ptr += size;

      this.registerInModule(mem.name, mem);
    }
  };

  SemanticPass.prototype.processModule = function(module) {
    if (module.type != "ParsedModule") {
      console.log(module);
      throw module.type;
    }

    // Bucket the declarations.
    var externs = [];
    var funcs = [];
    var memory = [];
    for (var i in module.decls) {
      var decl = module.decls[i];
      switch (decl.type) {
      case "Function":
	funcs.push(decl);
	break;
      case "Extern":
	externs.push(decl);
	break;
      case "MemoryDecl":
	memory.push(decl);
	break;
      default:
	console.log(decl);
	throw decl.type;
      }
    }

    module = wast.Module({
      externs: externs,
      funcs: funcs,
      memory: memory,
    });

    this.module = module;
    this.indexModule(module);
    if (!this.dead) {
      for (var i in module.funcs) {
	this.processFunction(module.funcs[i]);
      }
    }
    return module;
  };

  var processModule = function(module, status) {
    var semantic = new SemanticPass(status);
    return semantic.processModule(module);
  };

  return {
    processModule: processModule,
  };

});
<|endoftext|>


<commit_before>import app from 'app';
import _ from 'lodash';
import template from 'text!./data-matrix.directive.html';
import 'components/scbd-angularjs-services/main';
import 'services/main';
import 'views/directives/block-region-directive';
import 'pivottable';
import 'ngDialog'; ;

app.directive("matrixView", ["$q", "searchService", '$http', 'locale', 'thesaurusService', 'realm', '$timeout', 'ngDialog',
function ($q, searchService, $http, locale, thesaurusService, realm, $timeout, ngDialog) {

		return{
			template:template,
			restrict:'EA',
			replace:true,
			scope:{
                'api' : '=',
                'onRecordFormatting'    : '&'
            },
			link($scope, $element){

                require(['pivottable', 'plotly.js', 'plotly-renderers'], function(){});

                var pivotUIConf;
                var pivotResult;
                var defaultMessage        = $element.find('#loadingMessage').text()
                var exportFileName        = "Matrix-view"
                    $scope.matrixProgress = defaultMessage;
                var pageSize              = 1000;
                var queryCanceler         = undefined;
                var regions               = [];

                $scope.api          = {
                    updateResult : updateResult,
                    onExport     : onExport,
                    isBusy       : false
                };

                function updateResult(queryOptions){
                    if(queryCanceler){
                        queryCanceler.resolve();
                        $scope.matrixProgress   = defaultMessage;
                        $scope.matrixProgress  += '
' + $element.find('#resetFilterMessage').text()
                    }
                    else{
                        $scope.matrixProgress   = defaultMessage;
                    }
                    queryCanceler = $q.defer();

                    $scope.api.isBusy = $scope.loading = true;
                    queryOptions = queryOptions||{};
                    queryOptions.query   = queryOptions.query||'government_submissionYear_s:*';

                    var query = {
                        fields      : 'Government:government_EN_t,RecordType:schema_EN_t, Year:government_submissionYear_s, government_s,schemaType:schemaType_s,countryRegions_ss',
                        fieldQuery  : _.uniq(queryOptions.tagQueries),
                        query       : queryOptions.query||undefined,

                        rowsPerPage    : pageSize
                    }
                    return fetchRecords(query, {rows:[], pageNumber:0})
                        .then(function(result){
                                queryCanceler   = null;
                                pivotResult     = result;
                                pivotUI(pivotResult);

                                return result.rows;

                        })
                        .catch(function(err){
                            if(err.xhrStatus!="abort")
                                throw err;
                        })
                        .finally(function(){
                            if(!queryCanceler)
                                $scope.api.isBusy = $scope.loading = false;
                        });
                }

                function executeQuery(query){
                    return searchService.list(query, queryCanceler.promise)
                    .then(function(result){
                        var data = (result.data.response.docs);
                        data = _.map(data, function(row){

                            // $scope.onRecordFormatting({row:row});
                            if(row.Year)
                                row.Year = row.Year.replace(/([a-z]+)?_/i, '')

                            var region;
                            if(row.government_s){
                                region = _.find(regions, function(reg){
                                    return _.includes(reg.narrowerTerms, row.government_s)
                                });
                            }

                            return {
                                Government       :   row.Government||'x - Reference record',
                                Year             :   row.Year,
                                ["Record Type"]  :   row.RecordType,
                                Region           :   region ? region.title[locale] : 'No Region',
                                ["Schema Type"]  :   (row.schemaType||'').replace(/[a-z]/, function(match){ return match.toUpperCase()})
                            }
                        });

                        return { rows : data, numFound:result.data.response.numFound };
                    });
                }

                function fetchRecords(query, result){
                    var message = '';
                    if(result.numFound>0)
                        message = query.start + " of " + result.numFound;
                    $scope.matrixProgress += '
' + message;

                    query.start = result.pageNumber * pageSize;

                    return executeQuery(query)
                            .then(function(data){
                                result.rows         = _.union(result.rows, data.rows);
                                result.numFound     = data.numFound;
                                result.pageNumber  += 1;
                                if(result.rows.length < result.numFound){
                                    return fetchRecords(query, result);
                                }

                                return result;
                            });
                }

                function loadRegions(){
                    var DefaultRegions = [
                        "D50FE62D-8A5E-4407-83F8-AFCAAF708EA4", // CBD Regional Groups - Africa
                        "5E5B7AA4-2420-4147-825B-0820F7EC5A4B", // CBD Regional Groups - Asia and the Pacific
                        "942E40CA-4C23-4D3A-A0B4-736CD0EFCD54", // CBD Regional Groups - Central and Eastern Europe
                        "3D0CCC9A-A0A1-4399-8FA2-41D4D649DB0E", // CBD Regional Groups - Latin America and the Caribbean
                        "0EC2E5AE-25F3-4D3A-B71F-8019BB62ED4B"  // CBD Regional Groups - Western Europe and Others
                    ];
                    var regionsQuery = _.map(DefaultRegions, function(region){return thesaurusService.getTerms(region, {relations:true})})

                    return $q.all(regionsQuery)
                            .then(function(regionData){
                                regions = regionData;
                            });
                }

                function init(){
                    loadRegions()
                }

                function onExport(){

                    if($scope.loading)
                        return;
                    var exportData;
                    var downloadFormat;
                    var exportType;
                    if(pivotUIConf && pivotUIConf.rendererName.indexOf('Chart')>0){
                        exportData = $element.find('.plot-container.plotly').parent().html();
                        downloadFormat = 'jpeg';
                        exportType  = 'chart';
                    }
                    else{
                        exportData = $element.find('.pvtRendererArea .pvtTable').parent().html();
                        downloadFormat = 'xlsx';
                        exportType = 'excel'
                    }
                    ngDialog.open({
                        name     : 'exportDialog',
                        className : 'ngdialog-theme-default wide',
                        template : 'exportDialog',
                        controller : ['$scope', '$element', '$sce', function($scope, $element, $sce){
                            $scope.exportData     = $sce.trustAsHtml(exportData);
                            $scope.downloadFormat = downloadFormat;
                            $scope.exportType     = exportType;
                            $scope.fileName       = exportFileName
                            $scope.downloadData   = function(){
                                download($scope.downloadFormat, $scope.fileName);
                            };

                            $scope.closeDialog = function(){
                                ngDialog.close();
                            }
                        }]
                    })
                    function download(format, fileName){
                        if(pivotUIConf && pivotUIConf.rendererName.indexOf('Chart')>0){
                            pivotUI(pivotResult, format, fileName);
                            $timeout(function(){
                                var btn = $element.find('.modebar-container .modebar .modebar-group .modebar-btn:first()')[0]
                                btn.click()
                            }, 200);
                        }
                        else{
                            // Excel export
                            require(['tableexport'], function(){
                                var tableExport = $element.find('.pvtTable').tableExport({
                                                        formats: ["xlsx", "xls", "csv"],
                                                        filename: fileName||exportFileName,
                                                    });
                                $element.find('.'+ format).click();
                                tableExport.remove();
                            });
                        }
                    }
                }

                function pivotUI(result, chartExportFormat, fileName){

                    chartExportFormat = chartExportFormat || 'jpeg';

                    var derivers = $.pivotUtilities.derivers;
                    var renderers = $.extend($.pivotUtilities.renderers, $.pivotUtilities.plotly_renderers);
                    if(!pivotUIConf){
                        pivotUIConf = {
                            renderers: renderers,
                            rows: ["Government"],
                            cols: ["RecordType"],
                            aggregatorName: "Count",
                            rendererOptions: {
                                plotly:{
                                    // showlegend: true
                                },
                                plotlyConfig : {
                                    displayModeBar: true,
                                    toImageButtonOptions: {
                                        filename : exportFileName,
                                        format: chartExportFormat, // one of png, svg, jpeg, webp
                                    }
                                }
                            },
                            onRefresh: function(config){
                                pivotUIConf = config;
                            }
                        }
                    }
                    else{
                        pivotUIConf.rendererOptions.plotlyConfig.toImageButtonOptions.format    = chartExportFormat;
                        pivotUIConf.rendererOptions.plotlyConfig.toImageButtonOptions.filename  = fileName||exportFileName;
                    }

                    $element.find("#output").pivotUI(
                        result.rows,
                        pivotUIConf,
                        true // overwrite prev conf
                    );
                }

                init();

			}
		}

    }]);

<commit_msg>fetch facets in matrix view<commit_after>import app from 'app';
import _ from 'lodash';
import template from 'text!./data-matrix.directive.html';
import 'components/scbd-angularjs-services/main';
import 'services/main';
import 'views/directives/block-region-directive';
import 'pivottable';
import 'ngDialog'; ;

app.directive("matrixView", ["$q", "searchService", '$http', 'locale', 'thesaurusService', 'realm', '$timeout', 'ngDialog',
function ($q, searchService, $http, locale, thesaurusService, realm, $timeout, ngDialog) {

		return{
			template:template,
			restrict:'EA',
			replace:true,
            require:'^searchDirective',
			scope:{
                'api' : '=',
                'onRecordFormatting'    : '&'
            },
			link($scope, $element, $attr, searchDirectiveCtrl){

                require(['pivottable', 'plotly.js', 'plotly-renderers'], function(){});

                var pivotUIConf;
                var pivotResult;
                var defaultMessage        = $element.find('#loadingMessage').text()
                var exportFileName        = "Matrix-view"
                    $scope.matrixProgress = defaultMessage;
                var pageSize              = 1000;
                var queryCanceler         = undefined;
                var regions               = [];

                $scope.api          = {
                    updateResult : updateResult,
                    onExport     : onExport,
                    isBusy       : false
                };

                function updateResult(queryOptions){
                    if(queryCanceler){
                        queryCanceler.resolve();
                        $scope.matrixProgress   = defaultMessage;
                        $scope.matrixProgress  += '
' + $element.find('#resetFilterMessage').text()
                    }
                    else{
                        $scope.matrixProgress   = defaultMessage;
                    }
                    queryCanceler = $q.defer();

                    $scope.api.isBusy = $scope.loading = true;
                    queryOptions = queryOptions||{};
                    queryOptions.query   = queryOptions.query||'government_submissionYear_s:*';

                    var query = {
                        fields      : 'Government:government_EN_t,RecordType:schema_EN_t, Year:government_submissionYear_s, government_s,schemaType:schemaType_s,countryRegions_ss',
                        fieldQuery  : _.uniq(queryOptions.tagQueries),
                        query       : queryOptions.query||undefined,
                        facet          : true,
                        facetFields    : queryOptions.facetFields,
                        pivotFacetFields    : queryOptions.pivotFacetFields,
                        rowsPerPage    : pageSize
                    }
                    return fetchRecords(query, {rows:[], pageNumber:0})
                        .then(function(result){
                                queryCanceler   = null;
                                pivotResult     = result;
                                pivotUI(pivotResult);
                                return result;

                        })
                        .catch(function(err){
                            if(err.xhrStatus!="abort")
                                throw err;
                        })
                        .finally(function(){
                            if(!queryCanceler)
                                $scope.api.isBusy = $scope.loading = false;
                        });
                }

                function executeQuery(query){
                    return searchService.list(query, queryCanceler.promise)
                    .then(function(result){
                        var data = (result.data.response.docs);
                        data = _.map(data, function(row){

                            // $scope.onRecordFormatting({row:row});
                            if(row.Year)
                                row.Year = row.Year.replace(/([a-z]+)?_/i, '')

                            var region;
                            if(row.government_s){
                                region = _.find(regions, function(reg){
                                    return _.includes(reg.narrowerTerms, row.government_s)
                                });
                            }

                            return {
                                Government       :   row.Government||'x - Reference record',
                                Year             :   row.Year,
                                ["Record Type"]  :   row.RecordType,
                                Region           :   region ? region.title[locale] : 'No Region',
                                ["Schema Type"]  :   (row.schemaType||'').replace(/[a-z]/, function(match){ return match.toUpperCase()})
                            }
                        });

                        return {
                                rows : data,
                                numFound:result.data.response.numFound,
                                facets: result.data.facet_counts ? searchDirectiveCtrl.sanitizeFacets(result.data.facet_counts) : undefined
                        };
                    });
                }

                function fetchRecords(query, result){
                    var message = '';
                    if(result.numFound>0)
                        message = query.start + " of " + result.numFound;
                    $scope.matrixProgress += '
' + message;

                    query.start = result.pageNumber * pageSize;

                    return executeQuery(query)
                            .then(function(data){
                                result.rows         = _.union(result.rows, data.rows);
                                result.numFound     = data.numFound;
                                result.pageNumber  += 1;
                                result.facets       = result.facets || data.facets;
                                if(result.rows.length < result.numFound){
                                    query.facet = false;
                                    return fetchRecords(query, result);
                                }

                                return result;
                            });
                }

                function loadRegions(){
                    var DefaultRegions = [
                        "D50FE62D-8A5E-4407-83F8-AFCAAF708EA4", // CBD Regional Groups - Africa
                        "5E5B7AA4-2420-4147-825B-0820F7EC5A4B", // CBD Regional Groups - Asia and the Pacific
                        "942E40CA-4C23-4D3A-A0B4-736CD0EFCD54", // CBD Regional Groups - Central and Eastern Europe
                        "3D0CCC9A-A0A1-4399-8FA2-41D4D649DB0E", // CBD Regional Groups - Latin America and the Caribbean
                        "0EC2E5AE-25F3-4D3A-B71F-8019BB62ED4B"  // CBD Regional Groups - Western Europe and Others
                    ];
                    var regionsQuery = _.map(DefaultRegions, function(region){return thesaurusService.getTerms(region, {relations:true})})

                    return $q.all(regionsQuery)
                            .then(function(regionData){
                                regions = regionData;
                            });
                }

                function init(){
                    loadRegions()
                }

                function onExport(){

                    if($scope.loading)
                        return;
                    var exportData;
                    var downloadFormat;
                    var exportType;
                    if(pivotUIConf && pivotUIConf.rendererName.indexOf('Chart')>0){
                        exportData = $element.find('.plot-container.plotly').parent().html();
                        downloadFormat = 'jpeg';
                        exportType  = 'chart';
                    }
                    else{
                        exportData = $element.find('.pvtRendererArea .pvtTable').parent().html();
                        downloadFormat = 'xlsx';
                        exportType = 'excel'
                    }
                    ngDialog.open({
                        name     : 'exportDialog',
                        className : 'ngdialog-theme-default wide',
                        template : 'exportDialog',
                        controller : ['$scope', '$element', '$sce', function($scope, $element, $sce){
                            $scope.exportData     = $sce.trustAsHtml(exportData);
                            $scope.downloadFormat = downloadFormat;
                            $scope.exportType     = exportType;
                            $scope.fileName       = exportFileName
                            $scope.downloadData   = function(){
                                download($scope.downloadFormat, $scope.fileName);
                            };

                            $scope.closeDialog = function(){
                                ngDialog.close();
                            }
                        }]
                    })
                    function download(format, fileName){
                        if(pivotUIConf && pivotUIConf.rendererName.indexOf('Chart')>0){
                            pivotUI(pivotResult, format, fileName);
                            $timeout(function(){
                                var btn = $element.find('.modebar-container .modebar .modebar-group .modebar-btn:first()')[0]
                                btn.click()
                            }, 200);
                        }
                        else{
                            // Excel export
                            require(['tableexport'], function(){
                                var tableExport = $element.find('.pvtTable').tableExport({
                                                        formats: ["xlsx", "xls", "csv"],
                                                        filename: fileName||exportFileName,
                                                    });
                                $element.find('.'+ format).click();
                                tableExport.remove();
                            });
                        }
                    }
                }

                function pivotUI(result, chartExportFormat, fileName){

                    chartExportFormat = chartExportFormat || 'jpeg';

                    var derivers = $.pivotUtilities.derivers;
                    var renderers = $.extend($.pivotUtilities.renderers, $.pivotUtilities.plotly_renderers);
                    if(!pivotUIConf){
                        pivotUIConf = {
                            renderers: renderers,
                            rows: ["Government"],
                            cols: ["RecordType"],
                            aggregatorName: "Count",
                            rendererOptions: {
                                plotly:{
                                    // showlegend: true
                                },
                                plotlyConfig : {
                                    displayModeBar: true,
                                    toImageButtonOptions: {
                                        filename : exportFileName,
                                        format: chartExportFormat, // one of png, svg, jpeg, webp
                                    }
                                }
                            },
                            onRefresh: function(config){
                                pivotUIConf = config;
                            }
                        }
                    }
                    else{
                        pivotUIConf.rendererOptions.plotlyConfig.toImageButtonOptions.format    = chartExportFormat;
                        pivotUIConf.rendererOptions.plotlyConfig.toImageButtonOptions.filename  = fileName||exportFileName;
                    }

                    $element.find("#output").pivotUI(
                        result.rows,
                        pivotUIConf,
                        true // overwrite prev conf
                    );
                }

                init();

			}
		}

    }]);

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import createTreeStore from '../stores/tree';
import {createStore} from 'redux';
import {Provider, Connector, connect} from 'react-redux';
import * as actions from '../actions';
import {extendConfig} from "../utils/configUtils";
import {fixPathsInTree} from '../utils/treeUtils';
import {bindActionCreators} from "../utils/stuff";
import {validateTree} from "../utils/validation";
import {queryString} from "../utils/queryString";
import {defaultRoot} from "../utils/defaultUtils";
import { LocaleProvider } from 'antd';
import Immutable from 'immutable';

class ConnectedQuery extends Component {
    static propTypes = {
        config: PropTypes.object.isRequired,
        onChange: PropTypes.func,
        get_children: PropTypes.func,
        tree: PropTypes.instanceOf(Immutable.Map),
        //dispatch: PropTypes.func.isRequired,
    };

    constructor(props) {
        super(props);

        this._updateActions(props);

        this.validatedTree = this.validateTree(props, props.config, props.tree);
        if (props.tree !== this.validatedTree) {
            props.onChange && props.onChange(this.validatedTree);
        }
    }

    validateTree (props, oldConfig, oldTree) {
        let tree = validateTree(props.tree, oldTree, props.config, oldConfig, true, true);
        tree = fixPathsInTree(tree);
        return tree;
    }

    _updateActions (props) {
      const {config, dispatch} = props;
      this.actions = bindActionCreators({...actions.tree, ...actions.group, ...actions.rule}, config, dispatch);
    }

    componentWillReceiveProps(nextProps) {
        const {tree, onChange} = nextProps;
        const oldTree = this.props.tree;
        const oldConfig = this.props.config;
        const newTree = nextProps.tree;
        const newConfig = this.props.config;
        const oldValidatedTree = this.validatedTree;

        if (oldConfig != newConfig) {
            this._updateActions(nextProps);
        }

        this.validatedTree = this.validateTree(nextProps, oldConfig, oldTree);
        let validatedTreeChanged = oldValidatedTree !== this.validatedTree
            && JSON.stringify(oldValidatedTree) != JSON.stringify(this.validatedTree);
        if (validatedTreeChanged) {
            onChange && onChange(this.validatedTree);
            this.setState({treeChanged: true})
        } else {
            this.setState({treeChanged: false})
        }
    }

    render() {
        const {config, tree, get_children, dispatch, ...props} = this.props;
        const validatedTree = this.validatedTree;
        return

            {get_children({
                tree: this.validatedTree,
                actions: this.actions,
                config: config,
                dispatch: dispatch
            })}

    }
}

const QueryContainer = connect(
    (state) => {
        return {
          tree: state.tree,
        }
    },
)(ConnectedQuery);

export default class Query extends Component {
    static propTypes = {
        //config
        conjunctions: PropTypes.object.isRequired,
        fields: PropTypes.object.isRequired,
        types: PropTypes.object.isRequired,
        operators: PropTypes.object.isRequired,
        widgets: PropTypes.object.isRequired,
        settings: PropTypes.object.isRequired,

        onChange: PropTypes.func,
        get_children: PropTypes.func,
        value: PropTypes.instanceOf(Immutable.Map),
    };

    constructor(props, context) {
        super(props, context);
        const config = {
            conjunctions: props.conjunctions,
            fields: props.fields,
            types: props.types,
            operators: props.operators,
            widgets: props.widgets,
            settings: props.settings,
            tree: props.value,
        };

        const store = createTreeStore(config);

        this.state = {
            store: createStore(store)
        };
    }

    // handle case when value property changes
    componentWillReceiveProps(nextProps) {
      let getQueryStringForProps = (props) => props.value != null
          ? queryString(props.value, props)
          : '';
      let previousQueryString = getQueryStringForProps(this.props);
      let nextQueryString = getQueryStringForProps(nextProps);

      // compare stringified trees
      if (previousQueryString !== nextQueryString) {
          let nextTree = nextProps.value || defaultRoot({ ...nextProps, tree: null });
          this.state.store.dispatch(
              actions.tree.setTree(nextProps, nextTree)
          );
      }
    }

    render() {
        const {conjunctions, fields, types, operators, widgets, settings, get_children, onChange, value, tree, children, ...props} = this.props;
        let config = {conjunctions, fields, types, operators, widgets, settings};
        config = extendConfig(config);

        return (
            <LocaleProvider locale={config.settings.locale.antd}>
                <Provider store={this.state.store}>
                    <QueryContainer
                      store={this.state.store}
                      get_children={get_children}
                      config={config}
                      onChange={onChange}
                    />
                </Provider>
            </LocaleProvider>
        )
    }
}
<commit_msg>added dontDispatchOnNewProps<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import createTreeStore from '../stores/tree';
import {createStore} from 'redux';
import {Provider, Connector, connect} from 'react-redux';
import * as actions from '../actions';
import {extendConfig} from "../utils/configUtils";
import {fixPathsInTree} from '../utils/treeUtils';
import {bindActionCreators} from "../utils/stuff";
import {validateTree} from "../utils/validation";
import {queryString} from "../utils/queryString";
import {defaultRoot} from "../utils/defaultUtils";
import { LocaleProvider } from 'antd';
import Immutable from 'immutable';

class ConnectedQuery extends Component {
    static propTypes = {
        config: PropTypes.object.isRequired,
        onChange: PropTypes.func,
        get_children: PropTypes.func,
        tree: PropTypes.instanceOf(Immutable.Map),
        //dispatch: PropTypes.func.isRequired,
    };

    constructor(props) {
        super(props);

        this._updateActions(props);

        this.validatedTree = this.validateTree(props, props.config, props.tree);
        if (props.tree !== this.validatedTree) {
            props.onChange && props.onChange(this.validatedTree);
        }
    }

    validateTree (props, oldConfig, oldTree) {
        let tree = validateTree(props.tree, oldTree, props.config, oldConfig, true, true);
        tree = fixPathsInTree(tree);
        return tree;
    }

    _updateActions (props) {
      const {config, dispatch} = props;
      this.actions = bindActionCreators({...actions.tree, ...actions.group, ...actions.rule}, config, dispatch);
    }

    componentWillReceiveProps(nextProps) {
        const {tree, onChange} = nextProps;
        const oldTree = this.props.tree;
        const oldConfig = this.props.config;
        const newTree = nextProps.tree;
        const newConfig = this.props.config;
        const oldValidatedTree = this.validatedTree;

        if (oldConfig != newConfig) {
            this._updateActions(nextProps);
        }

        this.validatedTree = this.validateTree(nextProps, oldConfig, oldTree);
        let validatedTreeChanged = oldValidatedTree !== this.validatedTree
            && JSON.stringify(oldValidatedTree) != JSON.stringify(this.validatedTree);
        if (validatedTreeChanged) {
            onChange && onChange(this.validatedTree);
            this.setState({treeChanged: true})
        } else {
            this.setState({treeChanged: false})
        }
    }

    render() {
        const {config, tree, get_children, dispatch, ...props} = this.props;
        const validatedTree = this.validatedTree;
        return

            {get_children({
                tree: this.validatedTree,
                actions: this.actions,
                config: config,
                dispatch: dispatch
            })}

    }
}

const QueryContainer = connect(
    (state) => {
        return {
          tree: state.tree,
        }
    },
)(ConnectedQuery);

export default class Query extends Component {
    static propTypes = {
        //config
        conjunctions: PropTypes.object.isRequired,
        fields: PropTypes.object.isRequired,
        types: PropTypes.object.isRequired,
        operators: PropTypes.object.isRequired,
        widgets: PropTypes.object.isRequired,
        settings: PropTypes.object.isRequired,

        onChange: PropTypes.func,
        get_children: PropTypes.func,
        value: PropTypes.instanceOf(Immutable.Map),
    };

    constructor(props, context) {
        super(props, context);
        const config = {
            conjunctions: props.conjunctions,
            fields: props.fields,
            types: props.types,
            operators: props.operators,
            widgets: props.widgets,
            settings: props.settings,
            tree: props.value,
        };

        const store = createTreeStore(config);

        this.state = {
            store: createStore(store)
        };
    }

    // handle case when value property changes
    componentWillReceiveProps(nextProps) {
        if (this.props.dontDispatchOnNewProps)
            return;

        let getQueryStringForProps = (props) => props.value != null
            ? queryString(props.value, props)
            : '';
        let previousQueryString = getQueryStringForProps(this.props);
        let nextQueryString = getQueryStringForProps(nextProps);

        // compare stringified trees
        if (previousQueryString !== nextQueryString) {
            let nextTree = nextProps.value || defaultRoot({ ...nextProps, tree: null });
            this.state.store.dispatch(
                actions.tree.setTree(nextProps, nextTree)
            );
        }
    }

    render() {
        const {conjunctions, fields, types, operators, widgets, settings, get_children, onChange, value, tree, children, ...props} = this.props;
        let config = {conjunctions, fields, types, operators, widgets, settings};
        config = extendConfig(config);

        return (
            <LocaleProvider locale={config.settings.locale.antd}>
                <Provider store={this.state.store}>
                    <QueryContainer
                      store={this.state.store}
                      get_children={get_children}
                      config={config}
                      onChange={onChange}
                    />
                </Provider>
            </LocaleProvider>
        )
    }
}
<|endoftext|>


<commit_before>const common = {
	'polyfills.*.js': 4620,
	'polyfills.*.js.map': 31760,
	'favicon.ico': 15086,
};

exports.default = exports.full = Object.assign({}, common, {
	'assets/favicon.ico': 15086,
	'assets/icons/android-chrome-192x192.png': 14058,
	'assets/icons/android-chrome-512x512.png': 51484,
	'assets/icons/apple-touch-icon.png': 12746,
	'assets/icons/favicon-16x16.png': 626,
	'assets/icons/favicon-32x32.png': 1487,
	'assets/icons/mstile-150x150.png': 9050,
	'push-manifest.json': 327,
	'manifest.json': 426,
	'sw.js': 3850,
	'bundle.*.js': 19300,
	'bundle.*.js.map': 105590,
	'route-home.chunk.*.js': 1000,
	'route-home.chunk.*.js.map': 4981,
	'route-profile.chunk.*.js': 1650,
	'route-profile.chunk.*.js.map': 8609,
	'index.html': 850,
	'style.*.css': 1065,
	'style.*.css.map': 2345,
	'ssr-build/ssr-bundle.js': 41715,
	'ssr-build/ssr-bundle.js.map': 66661,
	'ssr-build/style.*.css': 1065,
	'ssr-build/style.*.css.map': 2345,
});

exports.sass = `

Header on background

Paragraph on background

	{{ ... }}

`;

exports.prerender = {};

exports.prerender.heads = {};
exports.prerender.heads.home = `

	<meta charset="utf-8">
	<title>Home<\\/title>
	<meta name="viewport" content="width=device-width,initial-scale=1">
	<meta name="mobile-web-app-capable" content="yes">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<link rel="manifest" href="\\/manifest\\.json">
	<link rel="preload" href="\\/bundle\\.\\w{5}\\.js" as="script">
	<link rel="preload" href="\\/route-home\\.chunk\\.\\w{5}\\.js" as="script">
	<link rel="preload" href="\\/route-home\\.chunk\\.\\w{5}\\.css" as="style">
	<link rel="shortcut icon" href="\\/favicon\\.ico">
	<link href=\\"/bundle.\\w{5}.css\\" rel=\\"preload\\" as=\\"style\\" onload=\\"this.rel='stylesheet'\\">
		<link rel=\\"stylesheet\\" href="\\/bundle.\\w{5}.css"><\\/noscript>

	<link href=\\"/bundle.\\w{5}.css\\" rel=\\"preload\\" as=\\"style\\" onload=\\"this.rel='stylesheet'\\">

		<link rel=\\"stylesheet\\" href=\\"/bundle.\\w{5}.css">

`;

exports.prerender.heads.route66 = `

	<meta charset="utf-8">
	<title>Route66<\\/title>
	<meta name="viewport" content="width=device-width,initial-scale=1">
	<meta name="mobile-web-app-capable" content="yes">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<link rel="manifest" href="\\/manifest\\.json">
	<link rel="preload" href="\\/bundle\\.\\w{5}\\.js" as="script">
	<link rel="preload" href="\\/route-route66\\.chunk\\.\\w{5}\\.js" as="script">
	<link rel="preload" href="\\/route-route66\\.chunk\\.\\w{5}\\.css" as="style">
	<link rel="shortcut icon" href="\\/favicon\\.ico">
	<link href=\\"/bundle.\\w{5}.css\\" rel="stylesheet">

`;

exports.preload = {};

exports.preload.head = `

	<meta charset=\\"utf-8\\">
	<title>preact-prerender<\\/title>
	<meta name=\\"viewport\\" content=\\"width=device-width,initial-scale=1\\">
	<meta name=\\"mobile-web-app-capable\\" content=\\"yes\\">
	<meta name=\\"apple-mobile-web-app-capable\\" content=\\"yes\\">
	<link rel=\\"manifest\\" href=\\"\\/manifest\\.json\\">
	<link rel=\\"preload\\" href=\\"\\/bundle\\.\\w{5}\\.js\\" as=\\"script\\">
	<link rel=\\"preload\\" href=\\"\\/route-home\\.chunk\\.\\w{5}\\.js\\" as=\\"script\\">
	<link rel=\\"preload\\" href=\\"\\/route-home\\~route-route66\\~route-route89\\.chunk\\.\\w{5}\\.js\\" as=\\"script\\">
	<link rel=\\"preload\\" href=\\"\\/route-home\\.chunk\\.\\w{5}\\.css\\" as=\\"style\\">
	<link rel=\\"shortcut icon\\" href=\\"\\/favicon\\.ico\\">

	<link href=\\"\\/bundle\\.\\w{5}\\.css\\" rel=\\"preload\\" as=\\"style\\" onload=\\"this\\.rel='stylesheet'\\">

		<link rel=\\"stylesheet\\" href=\\"\\/bundle\\.\\w{5}\\.css\\">

`;

exports.prerender.home = `

Home

	{{ ... }}

`;

exports.prerender.route = `

Route66

	{{ ... }}

`;

exports.webpack = `
<!DOCTYPE html>

		<meta charset="utf-8">
		<title>preact-webpack</title>
		<link rel="shortcut icon" href="/favicon.ico"></link>

Guess what

This is an app with custom template

		{{ ... }}

`;
<|endoftext|>


<commit_before>import debugModule from "debug";
const debug = debugModule("test:data:more-decoding");

import { assert } from "chai";

import Ganache from "ganache-core";

import { prepareContracts, lineOf } from "../helpers";
import Debugger from "lib/debugger";

import solidity from "lib/solidity/selectors";

import * as Codec from "@truffle/codec";

const __YUL = `
pragma solidity ^0.6.6;

contract AssemblyTest {
  function run() public {
    uint outside = 8;
    assembly {
      let u := 3
      let v := u
      let w := add(u, 3)
      let z := outside
      let result := staticcall(0, 0, 0, 0, 0, 0)
      if sgt(z, 0) {
        let k := shl(1, z)
        log1(0, 0, k) //BREAK #1
      }
      function twist(a, b) -> c, d {
        let x1, x2
        let y1, y2
        x1 := add(a, b)
        x2 := sub(a, b)
        y1 := and(a, b)
        y2 := or(a, b)
        c := mul(x1, x2)
        d := xor(y1, y2)
        log1(0, 0, sdiv(c, d)) //BREAK #2
      }
      let n, m := twist(w, v)
      log1(0, 0, shl(z, smod(n, m))) //BREAK #3
    }
  }
}
`;

let sources = {
  "AssemblyTest.sol": __YUL
};

describe("Assembly decoding", function() {
  var provider;

  var abstractions;
  var compilations;

  before("Create Provider", async function() {
    provider = Ganache.provider({ seed: "debugger", gasLimit: 7000000 });
  });

  before("Prepare contracts and artifacts", async function() {
    this.timeout(30000);

    let prepared = await prepareContracts(provider, sources);
    abstractions = prepared.abstractions;
    compilations = prepared.compilations;
  });

  it("Decodes assembly variables", async function() {
    this.timeout(12000);

    let instance = await abstractions.AssemblyTest.deployed();
    let receipt = await instance.run();
    let txHash = receipt.tx;

    let bugger = await Debugger.forTx(txHash, { provider, compilations });

    let sourceId = bugger.view(solidity.current.source).id;
    let compilationId = bugger.view(solidity.current.source).compilationId;
    let source = bugger.view(solidity.current.source).source;
    await bugger.addBreakpoint({
      sourceId,
      compilationId,
      line: lineOf("BREAK #1", source)
    });
    await bugger.addBreakpoint({
      sourceId,
      compilationId,
      line: lineOf("BREAK #2", source)
    });
    await bugger.addBreakpoint({
      sourceId,
      compilationId,
      line: lineOf("BREAK #3", source)
    });

    await bugger.continueUntilBreakpoint();

    const numberize = obj =>
      Object.assign(
        {},
        ...Object.entries(obj).map(([key, value]) => ({ [key]: Number(value) }))
      );

    let variables = numberize(
      Codec.Format.Utils.Inspect.nativizeVariables(await bugger.variables())
    );

    let expectedResult = {
      outside: 8,
      u: 3,
      v: 3,
      w: 6,
      z: 8,
      result: 1,
      k: 16
    };

    assert.deepInclude(variables, expectedResult);

    await bugger.continueUntilBreakpoint();

    variables = numberize(
      Codec.Format.Utils.Inspect.nativizeVariables(await bugger.variables())
    );

    expectedResult = {
      a: 6,
      b: 3,
      x1: 9,
      x2: 3,
      y1: 2,
      y2: 7,
      c: 27,
      d: 5
    };

    assert.deepInclude(variables, expectedResult);

    await bugger.continueUntilBreakpoint();

    variables = numberize(
      Codec.Format.Utils.Inspect.nativizeVariables(await bugger.variables())
    );

    expectedResult = {
      outside: 8,
      u: 3,
      v: 3,
      w: 6,
      z: 8,
      result: 1,
      n: 27,
      m: 5
    };

    assert.deepInclude(variables, expectedResult);
  });
});
<commit_msg>Change yul test to use gas() and identity precompile<commit_after>import debugModule from "debug";
const debug = debugModule("test:data:more-decoding");

import { assert } from "chai";

import Ganache from "ganache-core";

import { prepareContracts, lineOf } from "../helpers";
import Debugger from "lib/debugger";

import solidity from "lib/solidity/selectors";

import * as Codec from "@truffle/codec";

const __YUL = `
pragma solidity ^0.6.6;

contract AssemblyTest {
  function run() public {
    uint outside = 8;
    assembly {
      let u := 3
      let v := u
      let w := add(u, 3)
      let z := outside
      let result := staticcall(gas(), 0, 0, 0, 0, 0) //identity fn
      if sgt(z, 0) {
        let k := shl(1, z)
        log1(0, 0, k) //BREAK #1
      }
      function twist(a, b) -> c, d {
        let x1, x2
        let y1, y2
        x1 := add(a, b)
        x2 := sub(a, b)
        y1 := and(a, b)
        y2 := or(a, b)
        c := mul(x1, x2)
        d := xor(y1, y2)
        log1(0, 0, sdiv(c, d)) //BREAK #2
      }
      let n, m := twist(w, v)
      log1(0, 0, shl(z, smod(n, m))) //BREAK #3
    }
  }
}
`;

let sources = {
  "AssemblyTest.sol": __YUL
};

describe("Assembly decoding", function() {
  var provider;

  var abstractions;
  var compilations;

  before("Create Provider", async function() {
    provider = Ganache.provider({ seed: "debugger", gasLimit: 7000000 });
  });

  before("Prepare contracts and artifacts", async function() {
    this.timeout(30000);

    let prepared = await prepareContracts(provider, sources);
    abstractions = prepared.abstractions;
    compilations = prepared.compilations;
  });

  it("Decodes assembly variables", async function() {
    this.timeout(12000);

    let instance = await abstractions.AssemblyTest.deployed();
    let receipt = await instance.run();
    let txHash = receipt.tx;

    let bugger = await Debugger.forTx(txHash, { provider, compilations });

    let sourceId = bugger.view(solidity.current.source).id;
    let compilationId = bugger.view(solidity.current.source).compilationId;
    let source = bugger.view(solidity.current.source).source;
    await bugger.addBreakpoint({
      sourceId,
      compilationId,
      line: lineOf("BREAK #1", source)
    });
    await bugger.addBreakpoint({
      sourceId,
      compilationId,
      line: lineOf("BREAK #2", source)
    });
    await bugger.addBreakpoint({
      sourceId,
      compilationId,
      line: lineOf("BREAK #3", source)
    });

    await bugger.continueUntilBreakpoint();

    const numberize = obj =>
      Object.assign(
        {},
        ...Object.entries(obj).map(([key, value]) => ({ [key]: Number(value) }))
      );

    let variables = numberize(
      Codec.Format.Utils.Inspect.nativizeVariables(await bugger.variables())
    );

    let expectedResult = {
      outside: 8,
      u: 3,
      v: 3,
      w: 6,
      z: 8,
      result: 1,
      k: 16
    };

    assert.deepInclude(variables, expectedResult);

    await bugger.continueUntilBreakpoint();

    variables = numberize(
      Codec.Format.Utils.Inspect.nativizeVariables(await bugger.variables())
    );

    expectedResult = {
      a: 6,
      b: 3,
      x1: 9,
      x2: 3,
      y1: 2,
      y2: 7,
      c: 27,
      d: 5
    };

    assert.deepInclude(variables, expectedResult);

    await bugger.continueUntilBreakpoint();

    variables = numberize(
      Codec.Format.Utils.Inspect.nativizeVariables(await bugger.variables())
    );

    expectedResult = {
      outside: 8,
      u: 3,
      v: 3,
      w: 6,
      z: 8,
      result: 1,
      n: 27,
      m: 5
    };

    assert.deepInclude(variables, expectedResult);
  });
});
<|endoftext|>