<commit_before>import React from 'react';
import { Tab, Tabs, TabList, TabPanel } from 'react-tabs';
import { compose, pure, lifecycle, mapProps } from 'recompose';
import R from 'ramda';
import Mutator from '../../utils/mutator';
import * as TypesService from '../../services/types-service';
import * as RulesService from './rules-utils';
import JPadVisualEditor from './JPadVisualEditor/JPadVisualEditor';
import JPadTextEditor from './JPadTextEditor/JPadTextEditor';
import './JPadFullEditor.css';

const MutatorFor = propName => Comp =>
  class extends React.Component {
    constructor() {
      super();
      this.state = {};
    }
    componentWillMount() {
      this.setState({ mutator: Mutator.stateless(() => this.props[propName], this.props.onMutation) });
    }
    render() {
      const { [propName]: _, ...otherProps } = this.props;
      return <Comp mutate={this.state.mutator} {...otherProps} />;
    }
  };

const KeyRulesEditor = ({ source, valueType, mutate, onMutation, alerter, isReadonly }) =>

    <Tabs className={'tab-container'}>

      <TabList>
        <Tab className={'tab-header'}>
          
          Rules
        </Tab>
        <Tab className={'tab-header'}>
          
          Source
        </Tab>
      </TabList>
      <TabPanel className={'tab-content'}>
        <fieldset disabled={isReadonly} style={{ border: 'none' }}>
          <JPadVisualEditor {...{ mutate, alerter }} jpadSource={source} valueType={valueType} />
        </fieldset>

      </TabPanel>
      <TabPanel className={'tab-content'}>
        <JPadTextEditor
          source={source}
          onChange={x => onMutation(JSON.parse(x))}
          isReadonly={isReadonly}
        />

          {JSON.stringify(JSON.parse(source), null, 4)}

      </TabPanel>

    </Tabs>

;

function getTypedValue(value, valueType) {
  try {
    return TypesService.convertValue(value, valueType);
  } catch (err) {
    return valueType === TypesService.types.boolean.name ? '' : `${value}`;
  }
}

function changeValueType(valueType, rulesMutate, depth) {
  const rules = rulesMutate.getValue();
  if (depth === 0) {
    for (let i = 0; i < rules.length; i++) {
      const ruleMutate = rulesMutate.in(i);

      const valueDistrubtion = ruleMutate.in('ValueDistribution').getValue();
      if (!valueDistrubtion) {
        const currentRuleValue = ruleMutate.in('Value').getValue();
        ruleMutate.in('Value').updateValue(getTypedValue(currentRuleValue, valueType));
        break;
      }

      const valueToConvert = valueDistrubtion.type === 'weighted'
        ? Object.keys(valueDistrubtion.args)[0]
        : '';
      const convertedValue = getTypedValue(valueToConvert, valueType);

      ruleMutate
        .in('ValueDistribution')
        .delete()
        .in('OwnerType')
        .delete()
        .in('Type')
        .updateValue('SingleVariant')
        .up()
        .insert('Value', convertedValue);
    }
    return;
  }

  Object.keys(rules).forEach(key => changeValueType(valueType, rulesMutate.in(key), depth - 1));
}

export default compose(
  mapProps(({ source, onDependencyChanges, dependencies, onChange, ...other }) => ({
    onMutation(sourceTree) {
      const newDependencies = RulesService.getDependencies(
        sourceTree.rules,
        sourceTree.partitions.length,
      );
      if (!R.equals(dependencies, newDependencies)) {
        onDependencyChanges(newDependencies);
      }
      onChange(JSON.stringify(sourceTree, null, 4));
    },
    source,
    sourceTree: RulesService.convertToExplicitKey(JSON.parse(source)),
    ...other,
  })),
  MutatorFor('sourceTree'),
  pure,
  lifecycle({
    componentWillReceiveProps({ valueType, mutate }) {
      const currentValueType = mutate.in('valueType').getValue();
      if (valueType === currentValueType) return;

      const currentDefaultValue = mutate.in('defaultValue').getValue();

      mutate.apply((m) => {
        m.in('valueType').updateValue(valueType);
        if (currentDefaultValue !== undefined) {
          const modifiedDefaultValue = getTypedValue(currentDefaultValue, valueType);
          m.in('defaultValue').updateValue(modifiedDefaultValue);
        }
        changeValueType(valueType, m.in('rules'), m.in('partitions').getValue().length);
        return m;
      });
    },
  }),
)(KeyRulesEditor);
<commit_msg>make tabs component controlled<commit_after>import React from 'react';
import { Tab, Tabs, TabList, TabPanel } from 'react-tabs';
import { compose, pure, lifecycle, mapProps, withState } from 'recompose';
import R from 'ramda';
import Mutator from '../../utils/mutator';
import * as TypesService from '../../services/types-service';
import * as RulesService from './rules-utils';
import JPadVisualEditor from './JPadVisualEditor/JPadVisualEditor';
import JPadTextEditor from './JPadTextEditor/JPadTextEditor';
import './JPadFullEditor.css';

const MutatorFor = propName => Comp =>
  class extends React.Component {
    constructor() {
      super();
      this.state = {};
    }
    componentWillMount() {
      this.setState({ mutator: Mutator.stateless(() => this.props[propName], this.props.onMutation) });
    }
    render() {
      const { [propName]: _, ...otherProps } = this.props;
      return <Comp mutate={this.state.mutator} {...otherProps} />;
    }
  };

const KeyRulesEditor = ({
  source,
  valueType,
  mutate,
  onMutation,
  alerter,
  isReadonly,
  selectedTab,
  setSelectedTab,
}) =>

    <Tabs
      className={'tab-container'}
      selectedIndex={selectedTab}
      onSelect={(index, lastIndex) => {
        console.log('selectedTab', selectedTab);
        if (lastIndex === 1) {
          return true;
        }
        setSelectedTab(index);
      }}
    >

      <TabList>
        <Tab className={'tab-header'}>
          
          Rules
        </Tab>
        <Tab className={'tab-header'}>
          
          Source
        </Tab>
      </TabList>
      <TabPanel className={'tab-content'}>
        <fieldset disabled={isReadonly} style={{ border: 'none' }}>
          <JPadVisualEditor {...{ mutate, alerter }} jpadSource={source} valueType={valueType} />
        </fieldset>

      </TabPanel>
      <TabPanel className={'tab-content'}>
        <JPadTextEditor
          source={source}
          onChange={x => onMutation(JSON.parse(x))}
          isReadonly={isReadonly}
        />

          {JSON.stringify(JSON.parse(source), null, 4)}

      </TabPanel>

    </Tabs>

;

function getTypedValue(value, valueType) {
  try {
    return TypesService.convertValue(value, valueType);
  } catch (err) {
    return valueType === TypesService.types.boolean.name ? '' : `${value}`;
  }
}

function changeValueType(valueType, rulesMutate, depth) {
  const rules = rulesMutate.getValue();
  if (depth === 0) {
    for (let i = 0; i < rules.length; i++) {
      const ruleMutate = rulesMutate.in(i);

      const valueDistrubtion = ruleMutate.in('ValueDistribution').getValue();
      if (!valueDistrubtion) {
        const currentRuleValue = ruleMutate.in('Value').getValue();
        ruleMutate.in('Value').updateValue(getTypedValue(currentRuleValue, valueType));
        break;
      }

      const valueToConvert = valueDistrubtion.type === 'weighted'
        ? Object.keys(valueDistrubtion.args)[0]
        : '';
      const convertedValue = getTypedValue(valueToConvert, valueType);

      ruleMutate
        .in('ValueDistribution')
        .delete()
        .in('OwnerType')
        .delete()
        .in('Type')
        .updateValue('SingleVariant')
        .up()
        .insert('Value', convertedValue);
    }
    return;
  }

  Object.keys(rules).forEach(key => changeValueType(valueType, rulesMutate.in(key), depth - 1));
}

export default compose(
  mapProps(({ source, onDependencyChanges, dependencies, onChange, ...other }) => ({
    onMutation(sourceTree) {
      const newDependencies = RulesService.getDependencies(
        sourceTree.rules,
        sourceTree.partitions.length,
      );
      if (!R.equals(dependencies, newDependencies)) {
        onDependencyChanges(newDependencies);
      }
      onChange(JSON.stringify(sourceTree, null, 4));
    },
    source,
    sourceTree: RulesService.convertToExplicitKey(JSON.parse(source)),
    ...other,
  })),
  MutatorFor('sourceTree'),
  withState('selectedTab', 'setSelectedTab', 0),
  pure,
  lifecycle({
    componentWillReceiveProps({ valueType, mutate }) {
      const currentValueType = mutate.in('valueType').getValue();
      if (valueType === currentValueType) return;

      const currentDefaultValue = mutate.in('defaultValue').getValue();

      mutate.apply((m) => {
        m.in('valueType').updateValue(valueType);
        if (currentDefaultValue !== undefined) {
          const modifiedDefaultValue = getTypedValue(currentDefaultValue, valueType);
          m.in('defaultValue').updateValue(modifiedDefaultValue);
        }
        changeValueType(valueType, m.in('rules'), m.in('partitions').getValue().length);
        return m;
      });
    },
  }),
)(KeyRulesEditor);
<|endoftext|>


<commit_before>import macro from 'vtk.js/Sources/macro';
import vtkMapper from 'vtk.js/Sources/Rendering/Core/Mapper';
import vtkScalarsToColors from 'vtk.js/Sources/Common/Core/ScalarsToColors';

// ----------------------------------------------------------------------------
// vtkAbstractRepresentationProxy methods
// ----------------------------------------------------------------------------

function vtkAbstractRepresentationProxy(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkAbstractRepresentationProxy');

  function updateConnectivity() {
    if (model.input) {
      let count = model.sourceDependencies.length;
      while (count--) {
        model.sourceDependencies[count].setInputData(model.input.getDataset());
      }
    }
  }

  publicAPI.setInput = (source) => {
    if (model.sourceSubscription) {
      model.sourceSubscription.unsubscribe();
      model.sourceSubscription = null;
    }
    publicAPI.gcPropertyLinks();
    model.input = source;
    publicAPI.updateColorByDomain();

    if (model.input) {
      updateConnectivity();
      model.sourceSubscription = model.input.onDatasetChange(
        updateConnectivity
      );
    }
  };

  publicAPI.getInputDataSet = () =>
    model.input ? model.input.getDataset() : null;

  publicAPI.getDataArray = (arrayName, arrayLocation) => {
    const [selectedArray, selectedLocation] = publicAPI.getColorBy();
    const ds = publicAPI.getInputDataSet();
    const fields = ds
      ? ds.getReferenceByName(arrayLocation || selectedLocation)
      : null;
    const array = fields
      ? fields.getArrayByName(arrayName || selectedArray)
      : null;
    return array;
  };

  publicAPI.getLookupTableProxy = (arrayName) => {
    const arrayNameToUse = arrayName || publicAPI.getColorBy()[0];
    if (arrayNameToUse) {
      return model.proxyManager.getLookupTable(arrayNameToUse);
    }
    return null;
  };

  publicAPI.setLookupTableProxy = (lutProxy) => {
    // In place edits, no need to re-assign it...
    console.log(
      'setLookupTable',
      lutProxy.getPresetName(),
      lutProxy.getDataRange()
    );
  };

  publicAPI.getPiecewiseFunctionProxy = (arrayName) => {
    const arrayNameToUse = arrayName || publicAPI.getColorBy()[0];
    if (arrayNameToUse) {
      return model.proxyManager.getPiecewiseFunction(arrayNameToUse);
    }
    return null;
  };

  publicAPI.setPiecewiseFunctionProxy = (pwfProxy) => {
    // In place edits, no need to re-assign it...
    console.log('setPiecewiseFunction', pwfProxy.getDataRange());
  };

  publicAPI.rescaleTransferFunctionToDataRange = (n, l, c = -1) => {
    const array = publicAPI.getDataArray(n, l);
    const dataRange = array.getRange(c);
    model.proxyManager.rescaleTransferFunctionToDataRange(n, dataRange);
  };

  publicAPI.isVisible = () => {
    if (model.actors.length) {
      return model.actors[0].getVisibility();
    }
    if (model.volumes.length) {
      return model.volumes[0].getVisibility();
    }
    return false;
  };

  publicAPI.setVisibility = (visible) => {
    let count = model.actors.length;
    while (count--) {
      model.actors[count].setVisibility(visible);
    }
    count = model.volumes.length;
    while (count--) {
      model.volumes[count].setVisibility(visible);
    }
  };

  publicAPI.setColorBy = (arrayName, arrayLocation, componentIndex = -1) => {
    let colorMode = vtkMapper.ColorMode.DEFAULT;
    let scalarMode = vtkMapper.ScalarMode.DEFAULT;
    const colorByArrayName = arrayName;
    const interpolateScalarsBeforeMapping = arrayLocation === 'pointData';
    const activeArray = publicAPI.getDataArray(arrayName, arrayLocation);
    const scalarVisibility = !!activeArray;
    const lookupTable = arrayName
      ? publicAPI.getLookupTableProxy(arrayName).getLookupTable()
      : null;

    if (lookupTable) {
      if (componentIndex === -1) {
        lookupTable.setVectorModeToMagnitude();
      } else {
        lookupTable.setVectorModeToComponent();
        lookupTable.setVectorComponent(componentIndex);
      }
    }

    if (scalarVisibility) {
      colorMode = vtkMapper.ColorMode.MAP_SCALARS;
      scalarMode =
        arrayLocation === 'pointData'
          ? vtkMapper.ScalarMode.USE_POINT_FIELD_DATA
          : vtkMapper.ScalarMode.USE_CELL_FIELD_DATA;

      model.mapper.setLookupTable(lookupTable);
      publicAPI.rescaleTransferFunctionToDataRange(
        arrayName,
        arrayLocation,
        componentIndex
      );
    }

    model.mapper.set({
      colorByArrayName,
      colorMode,
      interpolateScalarsBeforeMapping,
      scalarMode,
      scalarVisibility,
    });
  };

  publicAPI.getColorBy = () => {
    if (!model.mapper.getColorByArrayName) {
      const ds = publicAPI.getInputDataSet();
      if (ds.getPointData().getScalars()) {
        return [
          ds
            .getPointData()
            .getScalars()
            .getName(),
          'pointData',
          -1,
        ];
      }
      if (ds.getCellData().getScalars()) {
        return [
          ds
            .getCellData()
            .getScalars()
            .getName(),
          'cellData',
          -1,
        ];
      }
      if (ds.getPointData().getNumberOfArrays()) {
        return [
          ds
            .getPointData()
            .getArrayByIndex(0)
            .getName(),
          'pointData',
          -1,
        ];
      }
      if (ds.getCellData().getNumberOfArrays()) {
        return [
          ds
            .getCellData()
            .getArrayByIndex(0)
            .getName(),
          'cellData',
          -1,
        ];
      }
      return [];
    }
    const result = [];
    const {
      colorByArrayName,
      colorMode,
      scalarMode,
      scalarVisibility,
    } = model.mapper.get(
      'colorByArrayName',
      'colorMode',
      'scalarMode',
      'scalarVisibility'
    );

    if (scalarVisibility && colorByArrayName) {
      result.push(colorByArrayName);
      result.push(
        scalarMode === vtkMapper.ScalarMode.USE_POINT_FIELD_DATA
          ? 'pointData'
          : 'cellData'
      );
    }

    if (colorMode === vtkMapper.ColorMode.MAP_SCALARS && colorByArrayName) {
      const lut = publicAPI
        .getLookupTableProxy(colorByArrayName)
        .getLookupTable();
      const componentIndex =
        lut.getVectorMode() === vtkScalarsToColors.VectorMode.MAGNITUDE
          ? -1
          : lut.getVectorComponent();
      result.push(componentIndex);
    }
    return result;
  };

  publicAPI.listDataArrays = () => {
    const arrayList = [];
    if (!model.input) {
      return arrayList;
    }

    const dataset = publicAPI.getInputDataSet();

    // Point data
    const pointData = dataset.getPointData();
    let size = pointData.getNumberOfArrays();
    for (let idx = 0; idx < size; idx++) {
      const array = pointData.getArrayByIndex(idx);
      arrayList.push({
        name: array.getName(),
        location: 'pointData',
        numberOfComponents: array.getNumberOfComponents(),
        dataRange: array.getRange(),
      });
    }

    // Cell data
    const cellData = dataset.getCellData();
    size = cellData.getNumberOfArrays();
    for (let idx = 0; idx < size; idx++) {
      const array = cellData.getArrayByIndex(idx);
      arrayList.push({
        name: array.getName(),
        location: 'cellData',
        numberOfComponents: array.getNumberOfComponents(),
        dataRange: array.getRange(),
      });
    }

    return arrayList;
  };

  publicAPI.updateColorByDomain = () => {
    publicAPI.updateProxyProperty('colorBy', {
      domain: {
        arrays: publicAPI.listDataArrays(),
        solidColor: !model.disableSolidColor,
      },
    });
  };

  publicAPI.delete = macro.chain(() => {
    if (model.sourceSubscription) {
      model.sourceSubscription.unsubscribe();
      model.sourceSubscription = null;
    }
  }, publicAPI.delete);
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  actors: [],
  volumes: [],
  sourceDependencies: [],
};

// ----------------------------------------------------------------------------

function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  macro.obj(publicAPI, model);
  macro.get(publicAPI, model, ['input', 'mapper', 'actors', 'volumes']);

  // Object specific methods
  vtkAbstractRepresentationProxy(publicAPI, model);
  macro.proxy(publicAPI, model);
}

export default { extend };
<commit_msg>fix(AbstractRepresentationProxy): Allow dynamic link registration<commit_after>import macro from 'vtk.js/Sources/macro';
import vtkMapper from 'vtk.js/Sources/Rendering/Core/Mapper';
import vtkScalarsToColors from 'vtk.js/Sources/Common/Core/ScalarsToColors';

// ----------------------------------------------------------------------------
// vtkAbstractRepresentationProxy methods
// ----------------------------------------------------------------------------

function vtkAbstractRepresentationProxy(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkAbstractRepresentationProxy');

  function updateConnectivity() {
    if (model.input) {
      let count = model.sourceDependencies.length;
      while (count--) {
        model.sourceDependencies[count].setInputData(model.input.getDataset());
      }
    }
  }

  publicAPI.setInput = (source) => {
    if (model.sourceSubscription) {
      model.sourceSubscription.unsubscribe();
      model.sourceSubscription = null;
    }
    publicAPI.gcPropertyLinks();
    model.input = source;
    publicAPI.updateColorByDomain();

    if (model.input) {
      updateConnectivity();
      model.sourceSubscription = model.input.onDatasetChange(
        updateConnectivity
      );
    }

    // Allow dynamic registration of links
    if (model.links) {
      for (let i = 0; i < model.links.length; i++) {
        const { link, property } = model.links[i];
        const sLink = source.getPropertyLink(link);
        publicAPI.registerPropertyLinkForGC(sLink);
        sLink.bind(publicAPI, property);
      }
    }
  };

  publicAPI.getInputDataSet = () =>
    model.input ? model.input.getDataset() : null;

  publicAPI.getDataArray = (arrayName, arrayLocation) => {
    const [selectedArray, selectedLocation] = publicAPI.getColorBy();
    const ds = publicAPI.getInputDataSet();
    const fields = ds
      ? ds.getReferenceByName(arrayLocation || selectedLocation)
      : null;
    const array = fields
      ? fields.getArrayByName(arrayName || selectedArray)
      : null;
    return array;
  };

  publicAPI.getLookupTableProxy = (arrayName) => {
    const arrayNameToUse = arrayName || publicAPI.getColorBy()[0];
    if (arrayNameToUse) {
      return model.proxyManager.getLookupTable(arrayNameToUse);
    }
    return null;
  };

  publicAPI.setLookupTableProxy = (lutProxy) => {
    // In place edits, no need to re-assign it...
    console.log(
      'setLookupTable',
      lutProxy.getPresetName(),
      lutProxy.getDataRange()
    );
  };

  publicAPI.getPiecewiseFunctionProxy = (arrayName) => {
    const arrayNameToUse = arrayName || publicAPI.getColorBy()[0];
    if (arrayNameToUse) {
      return model.proxyManager.getPiecewiseFunction(arrayNameToUse);
    }
    return null;
  };

  publicAPI.setPiecewiseFunctionProxy = (pwfProxy) => {
    // In place edits, no need to re-assign it...
    console.log('setPiecewiseFunction', pwfProxy.getDataRange());
  };

  publicAPI.rescaleTransferFunctionToDataRange = (n, l, c = -1) => {
    const array = publicAPI.getDataArray(n, l);
    const dataRange = array.getRange(c);
    model.proxyManager.rescaleTransferFunctionToDataRange(n, dataRange);
  };

  publicAPI.isVisible = () => {
    if (model.actors.length) {
      return model.actors[0].getVisibility();
    }
    if (model.volumes.length) {
      return model.volumes[0].getVisibility();
    }
    return false;
  };

  publicAPI.setVisibility = (visible) => {
    let count = model.actors.length;
    while (count--) {
      model.actors[count].setVisibility(visible);
    }
    count = model.volumes.length;
    while (count--) {
      model.volumes[count].setVisibility(visible);
    }
  };

  publicAPI.setColorBy = (arrayName, arrayLocation, componentIndex = -1) => {
    let colorMode = vtkMapper.ColorMode.DEFAULT;
    let scalarMode = vtkMapper.ScalarMode.DEFAULT;
    const colorByArrayName = arrayName;
    const interpolateScalarsBeforeMapping = arrayLocation === 'pointData';
    const activeArray = publicAPI.getDataArray(arrayName, arrayLocation);
    const scalarVisibility = !!activeArray;
    const lookupTable = arrayName
      ? publicAPI.getLookupTableProxy(arrayName).getLookupTable()
      : null;

    if (lookupTable) {
      if (componentIndex === -1) {
        lookupTable.setVectorModeToMagnitude();
      } else {
        lookupTable.setVectorModeToComponent();
        lookupTable.setVectorComponent(componentIndex);
      }
    }

    if (scalarVisibility) {
      colorMode = vtkMapper.ColorMode.MAP_SCALARS;
      scalarMode =
        arrayLocation === 'pointData'
          ? vtkMapper.ScalarMode.USE_POINT_FIELD_DATA
          : vtkMapper.ScalarMode.USE_CELL_FIELD_DATA;

      model.mapper.setLookupTable(lookupTable);
      publicAPI.rescaleTransferFunctionToDataRange(
        arrayName,
        arrayLocation,
        componentIndex
      );
    }

    model.mapper.set({
      colorByArrayName,
      colorMode,
      interpolateScalarsBeforeMapping,
      scalarMode,
      scalarVisibility,
    });
  };

  publicAPI.getColorBy = () => {
    if (!model.mapper.getColorByArrayName) {
      const ds = publicAPI.getInputDataSet();
      if (ds.getPointData().getScalars()) {
        return [
          ds
            .getPointData()
            .getScalars()
            .getName(),
          'pointData',
          -1,
        ];
      }
      if (ds.getCellData().getScalars()) {
        return [
          ds
            .getCellData()
            .getScalars()
            .getName(),
          'cellData',
          -1,
        ];
      }
      if (ds.getPointData().getNumberOfArrays()) {
        return [
          ds
            .getPointData()
            .getArrayByIndex(0)
            .getName(),
          'pointData',
          -1,
        ];
      }
      if (ds.getCellData().getNumberOfArrays()) {
        return [
          ds
            .getCellData()
            .getArrayByIndex(0)
            .getName(),
          'cellData',
          -1,
        ];
      }
      return [];
    }
    const result = [];
    const {
      colorByArrayName,
      colorMode,
      scalarMode,
      scalarVisibility,
    } = model.mapper.get(
      'colorByArrayName',
      'colorMode',
      'scalarMode',
      'scalarVisibility'
    );

    if (scalarVisibility && colorByArrayName) {
      result.push(colorByArrayName);
      result.push(
        scalarMode === vtkMapper.ScalarMode.USE_POINT_FIELD_DATA
          ? 'pointData'
          : 'cellData'
      );
    }

    if (colorMode === vtkMapper.ColorMode.MAP_SCALARS && colorByArrayName) {
      const lut = publicAPI
        .getLookupTableProxy(colorByArrayName)
        .getLookupTable();
      const componentIndex =
        lut.getVectorMode() === vtkScalarsToColors.VectorMode.MAGNITUDE
          ? -1
          : lut.getVectorComponent();
      result.push(componentIndex);
    }
    return result;
  };

  publicAPI.listDataArrays = () => {
    const arrayList = [];
    if (!model.input) {
      return arrayList;
    }

    const dataset = publicAPI.getInputDataSet();

    // Point data
    const pointData = dataset.getPointData();
    let size = pointData.getNumberOfArrays();
    for (let idx = 0; idx < size; idx++) {
      const array = pointData.getArrayByIndex(idx);
      arrayList.push({
        name: array.getName(),
        location: 'pointData',
        numberOfComponents: array.getNumberOfComponents(),
        dataRange: array.getRange(),
      });
    }

    // Cell data
    const cellData = dataset.getCellData();
    size = cellData.getNumberOfArrays();
    for (let idx = 0; idx < size; idx++) {
      const array = cellData.getArrayByIndex(idx);
      arrayList.push({
        name: array.getName(),
        location: 'cellData',
        numberOfComponents: array.getNumberOfComponents(),
        dataRange: array.getRange(),
      });
    }

    return arrayList;
  };

  publicAPI.updateColorByDomain = () => {
    publicAPI.updateProxyProperty('colorBy', {
      domain: {
        arrays: publicAPI.listDataArrays(),
        solidColor: !model.disableSolidColor,
      },
    });
  };

  publicAPI.delete = macro.chain(() => {
    if (model.sourceSubscription) {
      model.sourceSubscription.unsubscribe();
      model.sourceSubscription = null;
    }
  }, publicAPI.delete);
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  actors: [],
  volumes: [],
  sourceDependencies: [],
};

// ----------------------------------------------------------------------------

function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  macro.obj(publicAPI, model);
  macro.get(publicAPI, model, ['input', 'mapper', 'actors', 'volumes']);

  // Object specific methods
  vtkAbstractRepresentationProxy(publicAPI, model);
  macro.proxy(publicAPI, model);
}

export default { extend };
<|endoftext|>


<commit_before>jQuery.noConflict();
jQuery(document).ready(function() {
    var current = null;
    jQuery('#djDebugPanelList li a').click(function() {
        if (current) {
            current.hide();
            current = null;
            return false;
        }
        current = jQuery('#djDebug #' + this.className);
        current.show();
        return false;
    });
    jQuery('#djDebug a.close').click(function() {
        if (current) { current.hide(); }
        current = null;
        return false;
    })
});
<commit_msg>We now have a jQuery.djDebug object to extend.  This might be overkill but it fixes a few issues with open/closing panels and adds a keybinding on the ESC key to close any panels that are open.<commit_after>jQuery.noConflict();
(function(jQuery) {
	jQuery.djDebug = function(data, klass) {
		jQuery.djDebug.init();
	}
	jQuery.extend(jQuery.djDebug, {
		init: function() {
			var current = null;
			jQuery('#djDebugPanelList li a').click(function() {
				current = jQuery('#djDebug #' + this.className);
				if (current.is(':visible')) {
					jQuery(document).trigger('close.djDebug');
				} else {
					jQuery('.panelContent').hide();
					current.show();
					jQuery.djDebug.open();
				}
				return false;
			});
			jQuery('#djDebug a.close').click(function() {
				jQuery(document).trigger('close.djDebug');
				return false;
			});
		},
		open: function() {
			jQuery(document).bind('keydown.djDebug', function(e) {
				if (e.keyCode == 27) {
					jQuery.djDebug.close();
				}
			});
		},
		close: function() {
			jQuery(document).trigger('close.djDebug');
			return false;
		}
	});
	jQuery(document).bind('close.djDebug', function() {
		jQuery(document).unbind('keydown.djDebug');
		jQuery('.panelContent').hide();
	});
})(jQuery);
jQuery(document).ready(function() {
	jQuery.djDebug();
});
<|endoftext|>


<commit_before>import {
  isPlainObject
} from 'uni-shared'

import {
  invoke
} from 'uni-core/service/bridge'

import {
  onMethod,
  invokeMethod
} from '../../platform'

const requestTasks = Object.create(null)

function formatResponse (res, args) {
  if (
    typeof res.data === 'string' &&
    res.data.charCodeAt(0) === 65279
  ) {
    res.data = res.data.substr(1)
  }

  res.statusCode = parseInt(res.statusCode, 10)

  if (isPlainObject(res.header)) {
    res.header = Object.keys(res.header).reduce(function (ret, key) {
      const value = res.header[key]
      if (Array.isArray(value)) {
        ret[key] = value.join(',')
      } else if (typeof value === 'string') {
        ret[key] = value
      }
      return ret
    }, {})
  }

  if (args.dataType && args.dataType.toLowerCase() === 'json') {
    try {
      res.data = JSON.parse(res.data)
    } catch (e) {}
  }

  return res
}

onMethod('onRequestTaskStateChange', function ({
  requestTaskId,
  state,
  data,
  statusCode,
  header,
  errMsg
}) {
  const {
    args,
    callbackId
  } = requestTasks[requestTaskId]

  if (!callbackId) {
    return
  }
  delete requestTasks[requestTaskId]
  switch (state) {
    case 'success':
      invoke(callbackId, formatResponse({
        data,
        statusCode,
        header,
        errMsg: 'request:ok'
      }, args))
      break
    case 'fail':
      invoke(callbackId, {
        errMsg: 'request:fail ' + errMsg
      })
      break
  }
})

class RequestTask {
  constructor (id) {
    this.id = id
  }

  abort () {
    invokeMethod('operateRequestTask', {
      requestTaskId: this.id,
      operationType: 'abort'
    })
  }

  offHeadersReceived () {

  }

  onHeadersReceived () {

  }
}

export function request (args, callbackId) {
  const {
    requestTaskId
  } = invokeMethod('createRequestTask', args)

  requestTasks[requestTaskId] = {
    args,
    callbackId
  }

  return new RequestTask(requestTaskId)
}
<commit_msg>fix uni.request<commit_after>import {
  isPlainObject
} from 'uni-shared'

import {
  invoke
} from 'uni-core/service/bridge'

import {
  onMethod,
  invokeMethod
} from '../../platform'

const requestTasks = Object.create(null)

function formatResponse (res, args) {
  if (
    typeof res.data === 'string' &&
    res.data.charCodeAt(0) === 65279
  ) {
    res.data = res.data.substr(1)
  }

  res.statusCode = parseInt(res.statusCode, 10)

  if (isPlainObject(res.header)) {
    res.header = Object.keys(res.header).reduce(function (ret, key) {
      const value = res.header[key]
      if (Array.isArray(value)) {
        ret[key] = value.join(',')
      } else if (typeof value === 'string') {
        ret[key] = value
      }
      return ret
    }, {})
  }

  if (args.dataType && args.dataType.toLowerCase() === 'json') {
    try {
      res.data = JSON.parse(res.data)
    } catch (e) {}
  }

  return res
}

onMethod('onRequestTaskStateChange', function ({
  requestTaskId,
  state,
  data,
  statusCode,
  header,
  errMsg
}) {
  const {
    args,
    callbackId
  } = requestTasks[requestTaskId] || {}

  if (!callbackId) {
    return
  }
  delete requestTasks[requestTaskId]
  switch (state) {
    case 'success':
      invoke(callbackId, formatResponse({
        data,
        statusCode,
        header,
        errMsg: 'request:ok'
      }, args))
      break
    case 'fail':
      invoke(callbackId, {
        errMsg: 'request:fail ' + errMsg
      })
      break
  }
})

class RequestTask {
  constructor (id) {
    this.id = id
  }

  abort () {
    invokeMethod('operateRequestTask', {
      requestTaskId: this.id,
      operationType: 'abort'
    })
  }

  offHeadersReceived () {

  }

  onHeadersReceived () {

  }
}

export function request (args, callbackId) {
  const {
    requestTaskId
  } = invokeMethod('createRequestTask', args)

  requestTasks[requestTaskId] = {
    args,
    callbackId
  }

  return new RequestTask(requestTaskId)
}
<|endoftext|>


<commit_before>'use strict';

angular.module('emuwebApp')
  .directive('previewtrack', function () {
    return {
      restrict: 'A',
      link: function (scope, element) {

        var startPCM = -1;

        element.bind('click', function (x) {
          if (!$.isEmptyObject(scope.shs.wavJSO)) {
            var width = scope.vs.curViewPort.eS - scope.vs.curViewPort.sS;
            startPCM = getX(x) * (scope.shs.wavJSO.Data.length / x.originalEvent.srcElement.width);
            scope.vs.setViewPort((startPCM - (width / 2)), (startPCM + (width / 2)));
            scope.$apply();
          }
        });

        element.bind('mousedown', function (x) {
          if (!$.isEmptyObject(scope.shs.wavJSO)) {
            startPCM = getX(x) * (scope.shs.wavJSO.Data.length / x.originalEvent.srcElement.width);
          }
        });

        element.bind('mousemove', function (x) {
          switch (event.which) {
          case 1:
            if (startPCM !== -1) {
              var width = scope.vs.curViewPort.eS - scope.vs.curViewPort.sS;
              startPCM = getX(x) * (scope.shs.wavJSO.Data.length / x.originalEvent.srcElement.width);
              scope.vs.setViewPort((startPCM - (width / 2)), (startPCM + (width / 2)));
              scope.$apply();
            }
            break;
          }
        });

        element.bind('mouseup', function () {
          startPCM = -1;
        });

        element.bind('mouseout', function () {
          startPCM = -1;
        });

        function getX(e) {
          return e.offsetX * (e.originalEvent.srcElement.width / e.originalEvent.srcElement.clientWidth);
        }

      }
    };
  });<commit_msg>isolated scope update<commit_after>'use strict';

angular.module('emuwebApp')
  .directive('previewtrack', function (viewState, Soundhandlerservice) {
    return {
      restrict: 'A',
      scope: {},
      link: function (scope, element) {

        var startPCM = -1;

        element.bind('click', function (x) {
          if (!$.isEmptyObject(Soundhandlerservice.wavJSO)) {
            var width = viewState.curViewPort.eS - viewState.curViewPort.sS;
            startPCM = getX(x) * (Soundhandlerservice.wavJSO.Data.length / x.originalEvent.srcElement.width);
            scope.$apply(function () {
              viewState.setViewPort((startPCM - (width / 2)), (startPCM + (width / 2)));
            });
          }
        });

        element.bind('mousedown', function (x) {
          if (!$.isEmptyObject(Soundhandlerservice.wavJSO)) {
            startPCM = getX(x) * (Soundhandlerservice.wavJSO.Data.length / x.originalEvent.srcElement.width);
          }
        });

        element.bind('mousemove', function (x) {
          switch (event.which) {
          case 1:
            if (startPCM !== -1) {
              var width = viewState.curViewPort.eS - viewState.curViewPort.sS;
              startPCM = getX(x) * (Soundhandlerservice.wavJSO.Data.length / x.originalEvent.srcElement.width);
              scope.$apply(function () {
                viewState.setViewPort((startPCM - (width / 2)), (startPCM + (width / 2)));
              });
            }
            break;
          }
        });

        element.bind('mouseup', function () {
          startPCM = -1;
        });

        element.bind('mouseout', function () {
          startPCM = -1;
        });

        function getX(e) {
          return e.offsetX * (e.originalEvent.srcElement.width / e.originalEvent.srcElement.clientWidth);
        }

      }
    };
  });<|endoftext|>


<commit_before>(function (document) {
  function Monkberry() {
    this.pool = new Pool();
    this.templates = {};
    this.filters = {};
    this.wrappers = {};
  }

  Monkberry.prototype.foreach = function (parent, node, map, template, data, array, options) {
    var i, j, len, keys, transform, arrayLength, childrenSize = map.length;

    if (Array.isArray(array)) {
      transform = transformArray;
      arrayLength = array.length;
    } else {
      transform = transformObject;
      keys = Object.keys(array);
      arrayLength = keys.length;
    }

    len = childrenSize - arrayLength;
    for (i in map.items) {
      if (len-- > 0) {
        map.items[i].remove();
      } else {
        break;
      }
    }

    j = 0;
    for (i in map.items) {
      map.items[i].update(transform(data, array, keys, j, options));
      j++;
    }

    for (j = childrenSize, len = arrayLength; j < len; j++) {
      // Render new view.
      var view = this.render(template);

      // Set view hierarchy.
      view.parent = parent;
      parent.nested.push(view);

      // Add nodes DOM.
      if (node.nodeType == 8) {
        view.insertBefore(node);
      } else {
        view.appendTo(node);
      }

      // Set view data (note what it must be after adding nodes to DOM).
      view.update(transform(data, array, keys, j, options));

      // Remember to remove from children map on view remove.
      i = map.push(view);
      view.onRemove = (function (i) {
        return function () {
          map.remove(i);
        };
      })(i);
    }
  };

  Monkberry.prototype.insert = function (parent, node, child/*.ref*/, template, data, test) {
    if (child.ref) {
      if (test) {
        child.ref.update(data);
      } else {
        child.ref.remove();
      }
    } else if (test) {
      // Render new view.
      var view = this.render(template);

      // Set view hierarchy.
      view.parent = parent;
      parent.nested.push(view);

      // Add nodes DOM.
      if (node.nodeType == 8) {
        view.insertBefore(node);
      } else {
        view.appendTo(node);
      }

      // Set view data (note what it must be after adding nodes to DOM).
      view.update(data);

      // Remember to remove child ref on remove of view.
      child.ref = view;
      view.onRemove = function () {
        child.ref = null;
      };
    }

    return test;
  };

  Monkberry.prototype.render = function (name, values, no_cache) {
    no_cache = no_cache || false;

    if (this.templates[name]) {
      var view;

      if (no_cache) {
        view = this.templates[name]();
        view.name = name;
        view.pool = this.pool;
      } else {
        view = this.pool.pull(name);
        if (!view) {
          view = this.templates[name]();
          view.name = name;
          view.pool = this.pool;
        }
      }

      if (values !== undefined) {
        view.update(values);
      }

      if (view.onRender) {
        view.onRender();
      }

      view.wrapped = view.wrapped || {};
      if (this.wrappers[name] && !view.wrapped[name]) {
        view = this.wrappers[name](view);
        view.wrapped[name] = true;
      }

      return view;
    } else {
      throw new Error('Template with name "' + name + '" does not found.');
    }
  };

  Monkberry.prototype.prerender = function (name, times) {
    while (times--) {
      this.pool.push(name, this.render(name, undefined, true));
    }
  };

  Monkberry.prototype.mount = function (templates) {
    var _this = this;

    // Some of templates mounts as factory which returns list of templates.
    if (typeof templates === 'function') {
      templates = templates(this, document);
    }

    Object.keys(templates).forEach(function (name) {
      _this.templates[name] = templates[name];
    });
  };

  Monkberry.prototype.view = function () {
    return new View;
  };

  Monkberry.prototype.map = function () {
    return new Map;
  };

  /**
   * Main class for view.
   */
  function View() {
    this.name = ''; // Name of template.
    this.parent = null; // Parent view.
    this.nested = []; // Nested views.
    this.nodes = []; // Root DOM nodes.
  }

  View.prototype.appendTo = function (toNode) {
    for (var i = 0, len = this.nodes.length; i < len; i++) {
      toNode.appendChild(this.nodes[i]);
    }
  };

  View.prototype.update = function (data) {
    var _this = this, keys = typeof data === 'object' ? Object.keys(data) : [];
    if (_this.__cache__) {
      // Clear cache to prevent double updating.
      keys.forEach(function (key) {
        if (key in _this.__cache__) {
          delete _this.__cache__[key];
        }
      });
    }
    if (_this.__update__) {
      keys.forEach(function (key) {
        if (_this.__update__.hasOwnProperty(key)) {
          _this.__update__[key](data, data[key]);
        }
      });
    }
  };

  View.prototype.insertBefore = function (toNode) {
    for (var i = 0, len = this.nodes.length; i < len; i++) {
      if (toNode.parentNode) {
        toNode.parentNode.insertBefore(this.nodes[i], toNode);
      } else {
        throw new Error("Can not insert child view into parent node." +
          "You need append your view first and then update.");
      }
    }
  };

  View.prototype.dom = function (toNode) {
    if (this.nodes.length == 1) {
      return this.nodes[0];
    } else {
      var fragment = document.createDocumentFragment();
      for (var i = 0, len = this.nodes.length; i < len; i++) {
        fragment.appendChild(this.nodes[i]);
      }
      return fragment;
    }
  };

  View.prototype.remove = function () {
    // Remove appended nodes.
    var i = this.nodes.length;
    while (i--) {
      this.nodes[i].parentNode.removeChild(this.nodes[i]);
    }
    // Remove self from parent's children map or child ref.
    if (this.onRemove) {
      this.onRemove();
    }
    // Remove all nested views.
    i = this.nested.length;
    while (i--) {
      this.nested[i].remove();
    }
    // Remove this view from parent's nested views.
    if (this.parent) {
      i = this.parent.nested.indexOf(this);
      this.parent.nested.splice(i, 1);
    }
    // Store view in pool for reuse in future.
    this.pool.push(this.name, this);
  };

  /**
   * Pool stores pre rendered views for faster template
   * rendering and removed views for reuseing DOM nodes.
   */
  function Pool() {
    this.store = {};
  }

  Pool.prototype.push = function (name, view) {
    if (!this.store[name]) {
      this.store[name] = [];
    }
    this.store[name].push(view);
  };

  Pool.prototype.pull = function (name) {
    if (this.store[name]) {
      return this.store[name].pop();
    } else {
      return void 0;
    }
  };

  /**
   * Simple Map implementation with length property.
   */
  function Map() {
    this.items = Object.create(null);
    this.length = 0;
    this.next = 0;
  }

  Map.prototype.push = function (element) {
    this.items[this.next] = element;
    this.length += 1;
    this.next += 1;
    return this.next - 1;
  };

  Map.prototype.remove = function (i) {
    if (i in this.items) {
      delete this.items[i];
      this.length -= 1;
    } else {
      throw new Error('You are trying to delete not existing element "' + i + '" form map.');
    }
  };

  Map.prototype.forEach = function (callback) {
    for (var i in this.items) {
      callback(this.items[i]);
    }
  };

  /**
   *  Helper function for working with foreach loops data.
   *  Will transform data for "key, value of array" constructions.
   */

  function transformArray(data, array, keys, i, options) {
    if (options) {
      var t = data;
      t[options.value] = array[i];

      if (options.key) {
        t[options.key] = i;
      }

      return t;
    } else {
      return i;
    }
  }

  function transformObject(data, array, keys, i, options) {
    if (options) {
      var t = data;
      t[options.value] = array[keys[i]];

      if (options.key) {
        t[options.key] = keys[i];
      }

      return t;
    } else {
      return array[keys[i]];
    }
  }

  if (typeof module !== "undefined") {
    module.exports = new Monkberry();
  } else {
    window.monkberry = new Monkberry();
  }
})(window.document);
<commit_msg>Separate render function on user/internal. Add force remove.<commit_after>(function (document) {
  function Monkberry() {
    this.pool = new Pool();
    this.templates = {};
    this.filters = {};
    this.wrappers = {};
  }

  Monkberry.prototype.foreach = function (parent, node, map, template, data, array, options) {
    var i, j, len, keys, transform, arrayLength, childrenSize = map.length;

    if (Array.isArray(array)) {
      transform = transformArray;
      arrayLength = array.length;
    } else {
      transform = transformObject;
      keys = Object.keys(array);
      arrayLength = keys.length;
    }

    len = childrenSize - arrayLength;
    for (i in map.items) {
      if (len-- > 0) {
        map.items[i].remove();
      } else {
        break;
      }
    }

    j = 0;
    for (i in map.items) {
      map.items[i].update(transform(data, array, keys, j, options));
      j++;
    }

    for (j = childrenSize, len = arrayLength; j < len; j++) {
      // Render new view.
      var view = this._render(template);

      // Set view hierarchy.
      view.parent = parent;
      parent.nested.push(view);

      // Add nodes DOM.
      if (node.nodeType == 8) {
        view.insertBefore(node);
      } else {
        view.appendTo(node);
      }

      // Set view data (note what it must be after adding nodes to DOM).
      view.update(transform(data, array, keys, j, options));

      // Remember to remove from children map on view remove.
      i = map.push(view);
      view.onRemove = (function (i) {
        return function () {
          map.remove(i);
        };
      })(i);
    }
  };

  Monkberry.prototype.insert = function (parent, node, child/*.ref*/, template, data, test) {
    if (child.ref) {
      if (test) {
        child.ref.update(data);
      } else {
        child.ref.remove();
      }
    } else if (test) {
      // Render new view.
      var view = this._render(template);

      // Set view hierarchy.
      view.parent = parent;
      parent.nested.push(view);

      // Add nodes DOM.
      if (node.nodeType == 8) {
        view.insertBefore(node);
      } else {
        view.appendTo(node);
      }

      // Set view data (note what it must be after adding nodes to DOM).
      view.update(data);

      // Remember to remove child ref on remove of view.
      child.ref = view;
      view.onRemove = function () {
        child.ref = null;
      };
    }

    return test;
  };

  Monkberry.prototype.render = function (name, values, noCache) {
    return this._render(name, values, noCache);
  };

  /**
   * This method is used only for private rendering of views.
   */
  Monkberry.prototype._render = function (name, values, noCache) {
    noCache = noCache || false;

    if (this.templates[name]) {
      var view;

      if (noCache) {
        view = this.templates[name]();
        view.name = name;
        view.pool = this.pool;
      } else {
        view = this.pool.pull(name);
        if (!view) {
          view = this.templates[name]();
          view.name = name;
          view.pool = this.pool;
        }
      }

      if (values !== undefined) {
        view.update(values);
      }

      if (view.onRender) {
        view.onRender();
      }

      if (this.wrappers[name] && !view.wrapped[name]) {
        view = this.wrappers[name](view);
        view.wrapped[name] = true;
      }

      return view;
    } else {
      throw new Error('Template with name "' + name + '" does not found.');
    }
  };

  Monkberry.prototype.prerender = function (name, times) {
    while (times--) {
      this.pool.push(name, this.render(name, undefined, true));
    }
  };

  Monkberry.prototype.mount = function (templates) {
    var _this = this;

    // Some of templates mounts as factory which returns list of templates.
    if (typeof templates === 'function') {
      templates = templates(this, document);
    }

    Object.keys(templates).forEach(function (name) {
      _this.templates[name] = templates[name];
    });
  };

  Monkberry.prototype.view = function () {
    return new View;
  };

  Monkberry.prototype.map = function () {
    return new Map;
  };

  /**
   * Main class for view.
   */
  function View() {
    this.name = ''; // Name of template.
    this.parent = null; // Parent view.
    this.nested = []; // Nested views.
    this.nodes = []; // Root DOM nodes.
    this.wrapped = {}; // List of already applied wrappers.
    this.onRender = null; // Function to call on render.
  }

  View.prototype.update = function (data) {
    var _this = this, keys = typeof data === 'object' ? Object.keys(data) : [];
    if (_this.__cache__) {
      // Clear cache to prevent double updating.
      keys.forEach(function (key) {
        if (key in _this.__cache__) {
          delete _this.__cache__[key];
        }
      });
    }
    if (_this.__update__) {
      keys.forEach(function (key) {
        if (_this.__update__.hasOwnProperty(key)) {
          _this.__update__[key](data, data[key]);
        }
      });
    }
  };

  View.prototype.appendTo = function (toNode) {
    for (var i = 0, len = this.nodes.length; i < len; i++) {
      toNode.appendChild(this.nodes[i]);
    }
  };

  View.prototype.insertBefore = function (toNode) {
    for (var i = 0, len = this.nodes.length; i < len; i++) {
      if (toNode.parentNode) {
        toNode.parentNode.insertBefore(this.nodes[i], toNode);
      } else {
        throw new Error("Can not insert child view into parent node." +
          "You need append your view first and then update.");
      }
    }
  };

  View.prototype.dom = function (toNode) {
    if (this.nodes.length == 1) {
      return this.nodes[0];
    } else {
      var fragment = document.createDocumentFragment();
      for (var i = 0, len = this.nodes.length; i < len; i++) {
        fragment.appendChild(this.nodes[i]);
      }
      return fragment;
    }
  };

  View.prototype.remove = function (force) {
    force = force || false;
    // Remove appended nodes.
    var i = this.nodes.length;
    while (i--) {
      this.nodes[i].parentNode.removeChild(this.nodes[i]);
    }
    // Remove self from parent's children map or child ref.
    if (this.onRemove) {
      this.onRemove();
    }
    // Remove all nested views.
    i = this.nested.length;
    while (i--) {
      this.nested[i].remove(force);
    }
    // Remove this view from parent's nested views.
    if (this.parent) {
      i = this.parent.nested.indexOf(this);
      this.parent.nested.splice(i, 1);
    }
    // Store view in pool for reuse in future.
    if (!force) {
      this.pool.push(this.name, this);
    }
  };

  /**
   * Pool stores pre rendered views for faster template
   * rendering and removed views for reuseing DOM nodes.
   */
  function Pool() {
    this.store = {};
  }

  Pool.prototype.push = function (name, view) {
    if (!this.store[name]) {
      this.store[name] = [];
    }
    this.store[name].push(view);
  };

  Pool.prototype.pull = function (name) {
    if (this.store[name]) {
      return this.store[name].pop();
    } else {
      return void 0;
    }
  };

  /**
   * Simple Map implementation with length property.
   */
  function Map() {
    this.items = Object.create(null);
    this.length = 0;
    this.next = 0;
  }

  Map.prototype.push = function (element) {
    this.items[this.next] = element;
    this.length += 1;
    this.next += 1;
    return this.next - 1;
  };

  Map.prototype.remove = function (i) {
    if (i in this.items) {
      delete this.items[i];
      this.length -= 1;
    } else {
      throw new Error('You are trying to delete not existing element "' + i + '" form map.');
    }
  };

  Map.prototype.forEach = function (callback) {
    for (var i in this.items) {
      callback(this.items[i]);
    }
  };

  /**
   *  Helper function for working with foreach loops data.
   *  Will transform data for "key, value of array" constructions.
   */

  function transformArray(data, array, keys, i, options) {
    if (options) {
      var t = data;
      t[options.value] = array[i];

      if (options.key) {
        t[options.key] = i;
      }

      return t;
    } else {
      return i;
    }
  }

  function transformObject(data, array, keys, i, options) {
    if (options) {
      var t = data;
      t[options.value] = array[keys[i]];

      if (options.key) {
        t[options.key] = keys[i];
      }

      return t;
    } else {
      return array[keys[i]];
    }
  }

  if (typeof module !== "undefined") {
    module.exports = new Monkberry();
  } else {
    window.monkberry = new Monkberry();
  }
})(window.document);
<|endoftext|>


<commit_before>import Vue from 'vue'
import store from 'src/vuex/store'
import ProgressButton from 'src/components/ProgressButton'
import { timeout } from 'src/utils'

describe('ProgressButton.vue', () => {
  let vm, progress
  before(() => {
    vm = new Vue({
      store,
      el: 'body',
      replace: false,
      template: '
<progress-button id="0" v-ref:progress></progress-button>
',
      components: { ProgressButton }
    })
    progress = vm.$refs.progress
  })

  it('display Download by default', () => {
    progress.$el.should.contain.text('Download')
  })

  it('switches states when starting a download', (done) => {
    progress.$el.disabled.should.be.false
    progress.state.should.equal('')
    progress.start()
    progress.state.should.equal('state-loading')
    progress.$tick().then(() => {
      progress.$el.disabled.should.be.true
      progress.finish()
      return timeout(350)
    }).then(() => {
      progress.$el.disabled.should.be.true
      progress.state.should.equal('state-success')
    }).then(done, done)
  })
})
<commit_msg>Fix test<commit_after>import Vue from 'vue'
import store from 'src/vuex/store'
import ProgressButton from 'src/components/ProgressButton'
import { timeout } from 'src/utils'

describe('ProgressButton.vue', () => {
  let vm, progress
  before(() => {
    vm = new Vue({
      store,
      el: 'body',
      data: {
        text: 'Download'
      },
      replace: false,
      template: '
<progress-button id="0" v-ref:progress>{{text}}</progress-button>
',
      components: { ProgressButton }
    })
    progress = vm.$refs.progress
  })

  it('display text', (done) => {
    progress.$el.should.contain.text('Download')
    vm.text = 'Loading'
    vm.$tick().then(() => {
      progress.$el.should.contain.text('Loading')
    }).then(done, done)
  })

  it('switches states when starting a download', (done) => {
    progress.$el.disabled.should.be.false
    progress.state.should.equal('')
    progress.start()
    progress.state.should.equal('state-loading')
    progress.$tick().then(() => {
      progress.$el.disabled.should.be.true
      progress.finish()
      return timeout(350)
    }).then(() => {
      progress.$el.disabled.should.be.true
      progress.state.should.equal('state-success')
    }).then(done, done)
  })
})
<|endoftext|>


<commit_before>import {  bufferToFile  } from './app/utils/file'
const fs = require('fs')
const isOnline = require('is-online');

let activity; // export this !

function trackActivityPattern( deltaMinutes, activityDays ) { //  Track user's Activity Pattern and saves it to a file named activity.txt

  // Defaults :
  deltaMinutes = (typeof deltaMinutes !== 'undefined') ?  deltaMinutes : 10; // update activity every 10 min
  activityDays = (typeof activityDays !== 'undefined') ?  activityDays : 7; // activity for 1 week

  //calculated variables
  const partsPerHour = Math.ceil(60/deltaMinutes);
  const partsPerDay  = Math.ceil(24*60/deltaMinutes);
  const activityParts = Math.ceil(activityDays * partsPerDay)
  var the_interval = deltaMinutes * 60 * 1000;

  //initalize your activity with all offline, Zero !
  activity= Array.apply(null, Array(activityParts) ).map(Number.prototype.valueOf,0);
  var activitycounter=0;

  console.log('activityParts = '+ activityParts);
  console.log('partsPerDay = '+ partsPerDay);
  console.log('partsPerHour = '+ partsPerHour);
  console.log('-------------------- Tracking Activity Pattern --------------------');

  //  minutes between  0-59, hours between 0 and 23
  //  0 Sunday, 1 Monday, 2 Tuesday, and etc

  setInterval(()=> { // loop untill activity period finished
    activitycounter++;
    console.log(activitycounter+'/'+activityParts);
    isOnline().then(online =>{ // check for online conectivity

      if(online)
      {
        console.log('\tonline');
        var date = new Date();
        const index = (date.getDay()*partsPerDay)  +  (date.getHours()*partsPerHour) + Math.floor(date.getMinutes()/deltaMinutes);
        activity[index] =  1; // online
        bufferToFile('ActivityPattern.txt',activity,()=>{console.log('\tupdated')});
        if(activitycounter==activityParts-1) //  reset the activity back again
        {
          console.log('-------------------- Reseting Activity Pattern --------------------');
          activity  = Array.apply(null, Array(  Math.ceil(activityDays * partsPerDay)  ) ).map(Number.prototype.valueOf,0);
          activitycounter=0;
        }
      }
      else console.log('\toffline');
    });
  }, the_interval);

}

function loadActivityPattern(path,callback) { // asynchronouslly loads the Activity Pattern

  fs.readFile(path, function(err, f){
    activity = f.toString().split(',');
  });
}

//  Track user's Activity Pattern
 trackActivityPattern();

//  Load the user's Activity Pattern
 loadActivityPattern('ActivityPattern.txt',()=>{
   console.log('Successfuly load the Activity Pattern !');
 });

// you can also Track under specified deltaMinutes, activityDay
 trackActivityPattern(1,1);

//  you can also load in sync. way
 activity = fs.readFileSync('activity.txt').toString().split(','); /
<commit_msg>fixed a typo<commit_after>import {  bufferToFile  } from './app/utils/file'
const fs = require('fs')
const isOnline = require('is-online');

let activity; // export this !

function trackActivityPattern( deltaMinutes, activityDays ) { //  Track user's Activity Pattern and saves it to a file named activity.txt

  // Defaults :
  deltaMinutes = (typeof deltaMinutes !== 'undefined') ?  deltaMinutes : 10; // update activity every 10 min
  activityDays = (typeof activityDays !== 'undefined') ?  activityDays : 7; // activity for 1 week

  //calculated variables
  const partsPerHour = Math.ceil(60/deltaMinutes);
  const partsPerDay  = Math.ceil(24*60/deltaMinutes);
  const activityParts = Math.ceil(activityDays * partsPerDay)
  var the_interval = deltaMinutes * 60 * 1000;

  //initalize your activity with all offline, Zero !
  activity= Array.apply(null, Array(activityParts) ).map(Number.prototype.valueOf,0);
  var activitycounter=0;

  console.log('activityParts = '+ activityParts);
  console.log('partsPerDay = '+ partsPerDay);
  console.log('partsPerHour = '+ partsPerHour);
  console.log('-------------------- Tracking Activity Pattern --------------------');

  //  minutes between  0-59, hours between 0 and 23
  //  0 Sunday, 1 Monday, 2 Tuesday, and etc

  setInterval(()=> { // loop untill activity period finished
    activitycounter++;
    console.log(activitycounter+'/'+activityParts);
    isOnline().then(online =>{ // check for online conectivity

      if(online)
      {
        console.log('\tonline');
        var date = new Date();
        const index = (date.getDay()*partsPerDay)  +  (date.getHours()*partsPerHour) + Math.floor(date.getMinutes()/deltaMinutes);
        activity[index] =  1; // online
        bufferToFile('ActivityPattern.txt',activity,()=>{console.log('\tupdated')});
        if(activitycounter==activityParts-1) //  reset the activity back again
        {
          console.log('-------------------- Reseting Activity Pattern --------------------');
          activity  = Array.apply(null, Array(  Math.ceil(activityDays * partsPerDay)  ) ).map(Number.prototype.valueOf,0);
          activitycounter=0;
        }
      }
      else console.log('\toffline');
    });
  }, the_interval);

}

function loadActivityPattern(path,callback) { // asynchronouslly loads the Activity Pattern

  fs.readFile(path, function(err, f){
    activity = f.toString().split(',');
  });
}

//  Track user's Activity Pattern
 trackActivityPattern();

//  Load the user's Activity Pattern
 loadActivityPattern('ActivityPattern.txt',()=>{
   console.log('Successfuly load the Activity Pattern !');
 });

// you can also Track under specified deltaMinutes, activityDay
 trackActivityPattern(1,1);

//  you can also load in sync. way
 activity = fs.readFileSync('activity.txt').toString().split(',');
<|endoftext|>


<commit_before>go.push({

  city_name: function() {
    return cities[This.city_id] || 'Worldwide';
  },

  cities_dropdown: function() {
    var agents_by_city = Agents.find('=city_id');

    // sort by number of agents first, then the city name
    var cities_by_num_agents = $keys(agents_by_city).sort_by(function (x){
      return cities[x];
    }).sort_by(function(x){
      return agents_by_city[x].length;
    }, {desc:true});

    var html = '';

    $.each(cities_by_num_agents, function(){
      var city_id = this;
      var city_name = cities[city_id];
      var num_agents = agents_by_city[city_id].length;

      html += "

"+city_name+"
"
            + "
has "+num_agents+" agents ready

";
    });
    return html;
  }

});
<commit_msg>fix broken descending option to sort_by<commit_after>go.push({

  city_name: function() {
    return cities[This.city_id] || 'Worldwide';
  },

  cities_dropdown: function() {
    var agents_by_city = Agents.find('=city_id');

    // sort by number of agents first, then the city name
    var cities_by_num_agents = $keys(agents_by_city).sort_by(function (x){
      return cities[x];
    }).sort_by(function(x){
      return agents_by_city[x].length;
    }, {order:'desc'});

    var html = '';

    $.each(cities_by_num_agents, function(){
      var city_id = this;
      var city_name = cities[city_id];
      var num_agents = agents_by_city[city_id].length;

      html += "

"+city_name+"
"
            + "
has "+num_agents+" agents ready

";
    });
    return html;
  }

});
<|endoftext|>


<commit_before>/*
 * Updates to the budget section to add classes to budget rows and inspector
 * Allows for one shared loop rather than multiple loops per feature
 */

(function poll() {
  // Waits until an external function gives us the all clear that we can run (at /shared/main.js)
  if (typeof ynabToolKit !== 'undefined' && ynabToolKit.pageReady === true) {
    var loadCategories = true;
    var selMonth;

    ynabToolKit.budgetCategoryInfo = (function () {
      // Supporting functions, or variables, etc
      var entityManager = ynab.YNABSharedLib.defaultInstance.entityManager;
      var subCats = [];
      var internalIdBase;

      function getCalculation(subCategoryName) {
        var subCat = subCats.find(getSubCategoryByName);
        var calculation;
        if (subCat) {
          var crazyInternalId = internalIdBase + subCat.entityId;
          calculation = entityManager.getMonthlySubCategoryBudgetCalculationById(crazyInternalId);
          calculation.goalType = subCat.getGoalType();
          calculation.goalCreationMonth = (subCat.goalCreationMonth) ? subCat.goalCreationMonth.toString().substr(0, 7) : '';
          /**
           * If the month the goal was created in is greater than the selected month, null the goal type to prevent further
           * processing.
           */
          if (calculation.goalCreationMonth && calculation.goalCreationMonth > selMonth) {
            calculation.goalType = null;
          }
        }

        return calculation;

        function getSubCategoryByName(ele) {
          return ele.toolkitName === subCategoryName;
        }
      }

      function setClasses(row, name, classes) {
        // inspector title
        var inspectorTitle = $.trim($('h1.inspector-category-name').text());

        // clear all old classes
        $(row)
          .removeClass('toolkit-row-budgetedpositive toolkit-row-budgetednegative toolkit-row-budgetedzero')
          .removeClass(' toolkit-row-availablepositive toolkit-row-availablenegative toolkit-row-availablezero')
          .removeClass(' toolkit-row-goalupcoming toolkit-row-goalTB toolkit-row-goalMF toolkit-row-goalTBD');
        if (inspectorTitle === name) {
          $('dl.inspector-overview-available')
            .removeClass('toolkit-row-budgetedpositive toolkit-row-budgetednegative toolkit-row-budgetedzero')
            .removeClass('toolkit-row-availablepositive toolkit-row-availablenegative toolkit-row-availablezero')
            .removeClass('toolkit-row-goal upcoming toolkit-row-goalTB toolkit-row-goalMF toolkit-row-goalTBD');
        }

        // add all new classes
        for (var i = 0, len = classes.length; i < len; i++) {
          $(row).addClass('toolkit-row-' + classes[i]);
          if (inspectorTitle === name) {
            $('dl.inspector-overview-available').addClass('toolkit-row-' + classes[i]);
          }
        }
      }

      return {
        invoke() {
          var uncategorized = $('.budget-table-uncategorized-transactions');
          $(uncategorized).each(function () {
            var subCategoryName = $(this).find('li.budget-table-cell-name>div>div')[0].title.match(/.[^\n]*/);
            var classes = [];

            // add available balance
            var available = $(this).find('.budget-table-cell-available .currency').text();
            if (ynab.unformat(available) < 0) {
              classes.push('availablenegative');
            } else if (ynab.unformat(available) > 0) {
              classes.push('availablepositive');
            } else {
              classes.push('availablezero');
            }

            // set classes
            setClasses(this, subCategoryName, classes);
          });

          var categories = $('.budget-table ul').not('.budget-table-uncategorized-transactions');
          var masterCategoryName = '';

          if (subCats === null || subCats.length === 0 || loadCategories) {
            subCats = ynabToolKit.shared.getMergedCategories();
            loadCategories = false;
          }

          selMonth = ynabToolKit.shared.parseSelectedMonth();

          // will be null on YNAB load when the user is not on the budget screen
          if (selMonth !== null) {
            selMonth = ynabToolKit.shared.yyyymm(selMonth);
            internalIdBase = 'mcbc/' + selMonth + '/';
          }

          // loop through categories
          $(categories).each(function () {
            if ($(this).hasClass('is-master-category')) {
              masterCategoryName = $(this).find('div.budget-table-cell-name-row-label-item>div>div[title]');
              masterCategoryName = (masterCategoryName !== 'undefined') ? $(masterCategoryName).attr('title') : '';
            }

            if ($(this).hasClass('is-sub-category')) {
              var subCategoryName = $(this).find('li.budget-table-cell-name>div>div')[0].title.match(/.[^\n]*/);
              var classes = [];

              // add budgeted
              var budgeted = $(this).find('.budget-table-cell-budgeted .currency').text();
              if (ynab.unformat(budgeted) < 0) {
                classes.push('budgetednegative');
              } else if (ynab.unformat(budgeted) > 0) {
                classes.push('budgetedpositive');
              } else {
                classes.push('budgetedzero');
              }

              // add available balance
              var available = $(this).find('.budget-table-cell-available .currency').text();
              if (ynab.unformat(available) < 0) {
                classes.push('availablenegative');
              } else if (ynab.unformat(available) > 0) {
                classes.push('availablepositive');
              } else {
                classes.push('availablezero');
              }

              // add goals and upcoming
              var calculation = getCalculation(masterCategoryName + '_' + subCategoryName);
              if (calculation.goalType === 'TB' ||
                calculation.goalType === 'MF' ||
                calculation.goalType === 'TBD') {
                classes.push('goal');
                classes.push('goal' + calculation.goalType);
              }

              if (calculation.upcomingTransactions < 0) {
                classes.push('upcoming');
              }

              // set classes
              setClasses(this, subCategoryName, classes);
            }
          });

          // call external features if appropriate
          if (ynabToolKit.options.goalIndicator) {
            ynabToolKit.shared.invokeExternalFeature('goalIndicator');
          }
        },

        observe(changedNodes) {
          // when this is moved to the webpack codebase, hopefully we can just listen to onRouteChanged
          // but until then we'll just have to keep adding stuff to this check that should trigger
          // budget-category related features to update
          if (changedNodes.has('navlink-budget active') ||
            changedNodes.has('budget-inspector') ||
            changedNodes.has('budget-table-cell-available-div user-data') ||
            changedNodes.has('budget-inspector-goals') ||
            changedNodes.has('budget-header-item budget-header-calendar toolkit-highlight-current-month')
          ) {
            ynabToolKit.budgetCategoryInfo.invoke();
          } else if (
            changedNodes.has('modal-overlay ynab-u modal-popup modal-budget-edit-category active') ||
            changedNodes.has('modal-overlay ynab-u modal-popup modal-add-master-category active') ||
            changedNodes.has('modal-overlay ynab-u modal-popup modal-add-sub-category active')) {
            /**
             * Seems there should be a more 'Embery' way to know when the categories have been
             * updated, added, or deleted but this'll have to do for now. Note that the flag is
             * set to true here so that next time invoke() is called the categories array will
             * be rebuilt. Rebuilding at this point won't work because the user hasn't completed
             * the update activity at this point.
             */
            loadCategories = true;
          }
        },

        addBudgetVersionIdObserver() {
          let applicationController = ynabToolKit.shared.containerLookup('controller:application');
          applicationController.addObserver('budgetVersionId', function () {
            Ember.run.scheduleOnce('afterRender', this, resetBudgetViewBudgetCategoryInfo);
          });

          function resetBudgetViewBudgetCategoryInfo() {
            loadCategories = true;
          }
        }
      };
    }()); // Keep feature functions contained within this object

    // Run once and activate setTimeOut()
    ynabToolKit.budgetCategoryInfo.invoke();
    ynabToolKit.budgetCategoryInfo.addBudgetVersionIdObserver();
  } else {
    setTimeout(poll, 250);
  }
}());

// calculation variable differences for different types of goals.

// Target
// goalExpectedCompletion: 9
// goalOverallFunded: 100000
// goalOverallLeft: 900000
// goalTarget: 0
// goalUnderFunded: 0

// Target by date
// goalExpectedCompletion: 0
// goalOverallFunded: 100000
// goalOverallLeft: 900000
// goalTarget: 250000
// goalUnderFunded: 150000

// Monthly goal
// goalExpectedCompletion: 0
// goalOverallFunded: 500000
// goalOverallLeft: 500000
// goalTarget: 1000000
// goalUnderFunded: 500000

// Upcoming transactions
// upcomingTransactions: -600000
<commit_msg>Goal Indicator fix<commit_after>/*
 * Updates to the budget section to add classes to budget rows and inspector
 * Allows for one shared loop rather than multiple loops per feature
 */

(function poll() {
  // Waits until an external function gives us the all clear that we can run (at /shared/main.js)
  if (typeof ynabToolKit !== 'undefined' && ynabToolKit.pageReady === true) {
    var loadCategories = true;
    var selMonth;

    ynabToolKit.budgetCategoryInfo = (function () {
      // Supporting functions, or variables, etc
      var entityManager = ynab.YNABSharedLib.defaultInstance.entityManager;
      var subCats = [];
      var internalIdBase;

      function getCalculation(subCategoryName) {
        var subCat = subCats.find(getSubCategoryByName);
        var calculation;
        if (subCat) {
          var crazyInternalId = internalIdBase + subCat.entityId;
          calculation = entityManager.getMonthlySubCategoryBudgetCalculationById(crazyInternalId);
          calculation.goalType = subCat.getGoalType();
          calculation.goalCreationMonth = (subCat.goalCreationMonth) ? subCat.goalCreationMonth.toString().substr(0, 7) : '';
          /**
           * If the month the goal was created in is greater than the selected month, null the goal type to prevent further
           * processing.
           */
          if (calculation.goalCreationMonth && calculation.goalCreationMonth > selMonth) {
            calculation.goalType = null;
          }
        }

        return calculation;

        function getSubCategoryByName(ele) {
          return ele.toolkitName === subCategoryName;
        }
      }

      function setClasses(row, name, classes) {
        // inspector title
        var inspectorTitle = $.trim($('h1.inspector-category-name').text());

        // clear all old classes
        $(row)
          .removeClass('toolkit-row-budgetedpositive toolkit-row-budgetednegative toolkit-row-budgetedzero')
          .removeClass(' toolkit-row-availablepositive toolkit-row-availablenegative toolkit-row-availablezero')
          .removeClass(' toolkit-row-goalupcoming toolkit-row-goalTB toolkit-row-goalMF toolkit-row-goalTBD');
        if (inspectorTitle === name) {
          $('dl.inspector-overview-available')
            .removeClass('toolkit-row-budgetedpositive toolkit-row-budgetednegative toolkit-row-budgetedzero')
            .removeClass('toolkit-row-availablepositive toolkit-row-availablenegative toolkit-row-availablezero')
            .removeClass('toolkit-row-goal upcoming toolkit-row-goalTB toolkit-row-goalMF toolkit-row-goalTBD');
        }

        // add all new classes
        for (var i = 0, len = classes.length; i < len; i++) {
          $(row).addClass('toolkit-row-' + classes[i]);
          if (inspectorTitle === name) {
            $('dl.inspector-overview-available').addClass('toolkit-row-' + classes[i]);
          }
        }
      }

      return {
        invoke() {
          var uncategorized = $('.budget-table-uncategorized-transactions');
          $(uncategorized).each(function () {
            var subCategoryName = $(this).find('li.budget-table-cell-name>div>div')[0].title.match(/.[^\n]*/);
            var classes = [];

            // add available balance
            var available = $(this).find('.budget-table-cell-available .currency').text();
            if (ynab.unformat(available) < 0) {
              classes.push('availablenegative');
            } else if (ynab.unformat(available) > 0) {
              classes.push('availablepositive');
            } else {
              classes.push('availablezero');
            }

            // set classes
            setClasses(this, subCategoryName, classes);
          });

          var categories = $('.budget-table ul').not('.budget-table-uncategorized-transactions');
          var masterCategoryName = 'Credit Card Payments';

          if (subCats === null || subCats.length === 0 || loadCategories) {
            subCats = ynabToolKit.shared.getMergedCategories();
            loadCategories = false;
          }

          selMonth = ynabToolKit.shared.parseSelectedMonth();

          // will be null on YNAB load when the user is not on the budget screen
          if (selMonth !== null) {
            selMonth = ynabToolKit.shared.yyyymm(selMonth);
            internalIdBase = 'mcbc/' + selMonth + '/';
          }

          // loop through categories
          $(categories).each(function () {
            if ($(this).hasClass('is-master-category')) {
              masterCategoryName = $(this).find('div.budget-table-cell-name-row-label-item>div>div[title]');
              masterCategoryName = (masterCategoryName !== 'undefined') ? $(masterCategoryName).attr('title') : '';
            }

            if ($(this).hasClass('is-sub-category')) {
              var subCategoryName = $(this).find('li.budget-table-cell-name>div>div')[0].title.match(/.[^\n]*/);
              var classes = [];

              // add budgeted
              var budgeted = $(this).find('.budget-table-cell-budgeted .currency').text();
              if (ynab.unformat(budgeted) < 0) {
                classes.push('budgetednegative');
              } else if (ynab.unformat(budgeted) > 0) {
                classes.push('budgetedpositive');
              } else {
                classes.push('budgetedzero');
              }

              // add available balance
              var available = $(this).find('.budget-table-cell-available .currency').text();
              if (ynab.unformat(available) < 0) {
                classes.push('availablenegative');
              } else if (ynab.unformat(available) > 0) {
                classes.push('availablepositive');
              } else {
                classes.push('availablezero');
              }

              // add goals and upcoming
              var calculation = getCalculation(masterCategoryName + '_' + subCategoryName);
              if (calculation.goalType === 'TB' ||
                calculation.goalType === 'MF' ||
                calculation.goalType === 'TBD') {
                classes.push('goal');
                classes.push('goal' + calculation.goalType);
              }

              if (calculation.upcomingTransactions < 0) {
                classes.push('upcoming');
              }

              // set classes
              setClasses(this, subCategoryName, classes);
            }
          });

          // call external features if appropriate
          if (ynabToolKit.options.goalIndicator) {
            ynabToolKit.shared.invokeExternalFeature('goalIndicator');
          }
        },

        observe(changedNodes) {
          // when this is moved to the webpack codebase, hopefully we can just listen to onRouteChanged
          // but until then we'll just have to keep adding stuff to this check that should trigger
          // budget-category related features to update
          if (changedNodes.has('navlink-budget active') ||
            changedNodes.has('budget-inspector') ||
            changedNodes.has('budget-table-cell-available-div user-data') ||
            changedNodes.has('budget-inspector-goals') ||
            changedNodes.has('budget-header-item budget-header-calendar toolkit-highlight-current-month')
          ) {
            ynabToolKit.budgetCategoryInfo.invoke();
          } else if (
            changedNodes.has('modal-overlay ynab-u modal-popup modal-budget-edit-category active') ||
            changedNodes.has('modal-overlay ynab-u modal-popup modal-add-master-category active') ||
            changedNodes.has('modal-overlay ynab-u modal-popup modal-add-sub-category active')) {
            /**
             * Seems there should be a more 'Embery' way to know when the categories have been
             * updated, added, or deleted but this'll have to do for now. Note that the flag is
             * set to true here so that next time invoke() is called the categories array will
             * be rebuilt. Rebuilding at this point won't work because the user hasn't completed
             * the update activity at this point.
             */
            loadCategories = true;
          }
        },

        addBudgetVersionIdObserver() {
          let applicationController = ynabToolKit.shared.containerLookup('controller:application');
          applicationController.addObserver('budgetVersionId', function () {
            Ember.run.scheduleOnce('afterRender', this, resetBudgetViewBudgetCategoryInfo);
          });

          function resetBudgetViewBudgetCategoryInfo() {
            loadCategories = true;
          }
        }
      };
    }()); // Keep feature functions contained within this object

    // Run once and activate setTimeOut()
    ynabToolKit.budgetCategoryInfo.invoke();
    ynabToolKit.budgetCategoryInfo.addBudgetVersionIdObserver();
  } else {
    setTimeout(poll, 250);
  }
}());

// calculation variable differences for different types of goals.

// Target
// goalExpectedCompletion: 9
// goalOverallFunded: 100000
// goalOverallLeft: 900000
// goalTarget: 0
// goalUnderFunded: 0

// Target by date
// goalExpectedCompletion: 0
// goalOverallFunded: 100000
// goalOverallLeft: 900000
// goalTarget: 250000
// goalUnderFunded: 150000

// Monthly goal
// goalExpectedCompletion: 0
// goalOverallFunded: 500000
// goalOverallLeft: 500000
// goalTarget: 1000000
// goalUnderFunded: 500000

// Upcoming transactions
// upcomingTransactions: -600000
<|endoftext|>


<commit_before>ace.define("ace/mode/polyglot_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function(require, exports) {
	var oop = require("../lib/oop");
	var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

	var PolyglotHighlightRules = function() {
		var keywordMapper = this.createKeywordMapper({
			'keyword': 'AND|OR|NOT',
			'support.type': '\*|\?|%',
		}, 'text', true);

		this.$rules = {
			start: [
				{
					token: 'comment',
					regex: /^\s*#/,
					next: 'qcomment',
				},
				{
					token: 'string',
					regex: '"(?=.)',
					next: 'qstring',
				},
				{
					token: 'constant.language',
					regex: /\[mesh\]/,
					caseInsensitive: true,
				},
				{
					token: 'variable',
					regex: /\[[a-z]{2,4}\]/,
				},
				{
					token: "paren.lparen",
					regex : "[\\[({]",
				},
				{
					token: "paren.rparen",
					regex : "[\\])}]",
				},
				{
					token: 'constant.language',
					regex: /exp .+?\//,
				},
				{
					token: 'string.interpolated',
					regex: /\<.+?\>/,
				},
				{
					token: 'keyword.other',
					regex: /\*/,
				},
				{
					token: 'keyword',
					regex: /\badj[0-9]+\b/,
				},
				{
					token: 'variable.parameter',
					token: '*',
				},
				{
					token: 'variable',
					regex: /\.[a-z,]{2,5}\./,
				},
				{
					token: keywordMapper,
					regex: "\\b\\w+\\b",
				},
			],
			qcomment: [
				{
					token: 'comment',
					regex: '$',
					next: 'start',
				},
				{
					defaultToken: 'comment',
				},
			],
			qstring: [
				{
					token: 'string',
					regex: '\\\\$',
					consumeLineEnd: true,
				},
				{
					token: 'string',
					regex: '"|$',
					next: 'start',
				},
				{
					defaultToken: 'string',
				},
			],
			qnstring: [
				{
					token: 'string',
					regex: '\\\\$',
					consumeLineEnd: true,
				},
				{
					token: 'string',
					regex: '[^a-zA-Z0-9]',
					next: 'start',
				},
				{
					defaultToken: 'string',
				},
			],
		};

		return this;
	};
	oop.inherits(PolyglotHighlightRules, TextHighlightRules);

	exports.PolyglotHighlightRules = PolyglotHighlightRules;
});

ace.define("ace/mode/polyglot", ["require", "exports", "module", "ace/lib/oop"], function(require, exports) {
	var oop = require("../lib/oop");
	var TextMode = require("../mode/text").Mode;
	var PolyglotHighlightRules = require("./polyglot_highlight_rules").PolyglotHighlightRules;

	var Mode = function() {
		this.HighlightRules = PolyglotHighlightRules;
		this.$behaviour = this.$defaultBehaviour;
	};
	oop.inherits(Mode, TextMode);

	(function() {
		this.$id = "ace/mode/polyglot";
		this.lineCommentStart = ["#"];
		this.blockComment = {start: "/*", end: "*/"};
	}).call(Mode.prototype);

	exports.Mode = Mode;
});
<commit_msg>Added ace rule for mesh:noexp<commit_after>ace.define("ace/mode/polyglot_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function(require, exports) {
	var oop = require("../lib/oop");
	var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

	var PolyglotHighlightRules = function() {
		var keywordMapper = this.createKeywordMapper({
			'keyword': 'AND|OR|NOT',
			'support.type': '\*|\?|%',
		}, 'text', true);

		this.$rules = {
			start: [
				{
					token: 'comment',
					regex: /^\s*#/,
					next: 'qcomment',
				},
				{
					token: 'string',
					regex: '"(?=.)',
					next: 'qstring',
				},
				{
					token: 'constant.language',
					regex: /\[mesh\]/,
					caseInsensitive: true,
				},
				{
					token: 'constant.language',
					regex: /\[mesh:noexp\]/,
					caseInsensitive: true,
				},
				{
					token: 'variable',
					regex: /\[[a-z]{2,4}\]/,
				},
				{
					token: "paren.lparen",
					regex : "[\\[({]",
				},
				{
					token: "paren.rparen",
					regex : "[\\])}]",
				},
				{
					token: 'constant.language',
					regex: /exp .+?\//,
				},
				{
					token: 'string.interpolated',
					regex: /\<.+?\>/,
				},
				{
					token: 'keyword.other',
					regex: /\*/,
				},
				{
					token: 'keyword',
					regex: /\badj[0-9]+\b/,
				},
				{
					token: 'variable.parameter',
					token: '*',
				},
				{
					token: 'variable',
					regex: /\.[a-z,]{2,5}\./,
				},
				{
					token: keywordMapper,
					regex: "\\b\\w+\\b",
				},
			],
			qcomment: [
				{
					token: 'comment',
					regex: '$',
					next: 'start',
				},
				{
					defaultToken: 'comment',
				},
			],
			qstring: [
				{
					token: 'string',
					regex: '\\\\$',
					consumeLineEnd: true,
				},
				{
					token: 'string',
					regex: '"|$',
					next: 'start',
				},
				{
					defaultToken: 'string',
				},
			],
			qnstring: [
				{
					token: 'string',
					regex: '\\\\$',
					consumeLineEnd: true,
				},
				{
					token: 'string',
					regex: '[^a-zA-Z0-9]',
					next: 'start',
				},
				{
					defaultToken: 'string',
				},
			],
		};

		return this;
	};
	oop.inherits(PolyglotHighlightRules, TextHighlightRules);

	exports.PolyglotHighlightRules = PolyglotHighlightRules;
});

ace.define("ace/mode/polyglot", ["require", "exports", "module", "ace/lib/oop"], function(require, exports) {
	var oop = require("../lib/oop");
	var TextMode = require("../mode/text").Mode;
	var PolyglotHighlightRules = require("./polyglot_highlight_rules").PolyglotHighlightRules;

	var Mode = function() {
		this.HighlightRules = PolyglotHighlightRules;
		this.$behaviour = this.$defaultBehaviour;
	};
	oop.inherits(Mode, TextMode);

	(function() {
		this.$id = "ace/mode/polyglot";
		this.lineCommentStart = ["#"];
		this.blockComment = {start: "/*", end: "*/"};
	}).call(Mode.prototype);

	exports.Mode = Mode;
});
<|endoftext|>


<commit_before>import { css } from 'styled-components';
import { isClassic } from '../../../utils/helpers/style-helper';
import InputPresentationStyle from '../input/input-presentation.style';
import InputIconToggleStyle from '../input-icon-toggle/input-icon-toggle.style';
import StyledIcon from '../../../components/icon/icon.style';

const dateClassicStyle = ({ theme }) => isClassic(theme) && css`
  & ${InputPresentationStyle} {
    width: 120px;
    &:focus {
      & ${InputIconToggleStyle} {
        background-color: #1e499f;
        border-color: #1e499f;
      }
      ${StyledIcon} {
        color: #FFFFFF;
      }
    }
    &:hover {
      & ${InputIconToggleStyle} {
        background-color: #255BC7;
        border-color: #255BC7;
      }
      ${StyledIcon} {
        color: #FFFFFF;
      }
    }
  }

  &&& ${InputIconToggleStyle} {
    border-left: 1px solid #bfccd2;
    box-sizing: border-box;
    width: 31px;
    &:hover {
      background-color: #1e499f;
      border-color: #1e499f;
      ${StyledIcon} {
        color: #FFFFFF;
      }
    }
  }

`;

export default dateClassicStyle;
<commit_msg>refactor: increases width of classic picker<commit_after>import { css } from 'styled-components';
import { isClassic } from '../../../utils/helpers/style-helper';
import InputPresentationStyle from '../input/input-presentation.style';
import InputIconToggleStyle from '../input-icon-toggle/input-icon-toggle.style';
import StyledIcon from '../../../components/icon/icon.style';

const dateClassicStyle = ({ theme }) => isClassic(theme) && css`
  & ${InputPresentationStyle} {
    width: 122px;
    &:focus {
      & ${InputIconToggleStyle} {
        background-color: #1e499f;
        border-color: #1e499f;
      }
      ${StyledIcon} {
        color: #FFFFFF;
      }
    }
    &:hover {
      & ${InputIconToggleStyle} {
        background-color: #255BC7;
        border-color: #255BC7;
      }
      ${StyledIcon} {
        color: #FFFFFF;
      }
    }
  }

  &&& ${InputIconToggleStyle} {
    border-left: 1px solid #bfccd2;
    box-sizing: border-box;
    width: 31px;
    &:hover {
      background-color: #1e499f;
      border-color: #1e499f;
      ${StyledIcon} {
        color: #FFFFFF;
      }
    }
  }

`;

export default dateClassicStyle;
<|endoftext|>


<commit_before>'use strict'

const P = require('bluebird'),
  _ = require('lodash')

let configuration = {}

exports.configure = function (internalChecks, integrationChecks) {
  configuration = {
    internalChecks: prepareChecksOfType('internal', internalChecks),
    integrationChecks: prepareChecksOfType('integration', integrationChecks)
  }
}

exports.setupExpressRoutes = function (app, prefix, additionalMiddleware) {
  app.get((prefix || '') + '/health/:mode?', disableCache, additionalMiddleware || noopMiddleware, exports.expressHealthCheck)
}

exports.expressHealthCheck = function (req, res, next) {
  const internalOnly = req.params.mode === 'internal' || req.query.mode === 'internal' || req.query.internal

  const healthChecks = configuration.internalChecks.concat(internalOnly ? [] : configuration.integrationChecks)

  checkHealth(healthChecks)
    .then(function (results) {
      if (!results.success) res.status(500)
      res.send(results)
    })
    .catch(next)
}

function checkHealth(checks) {
  return P.all(checks.map(checkSingleHealth))
    .then(function (results) {
      const success = results.every(result => result.success),
        successfulChecks = results.filter(result => result.success),
        ping = _.fromPairs(successfulChecks.map(result => [result.service, result.duration])),
        details = _.fromPairs(successfulChecks.filter(check => check.details).map(check => [check.service, check.details]))

      let failures = results.filter(result => !result.success).map(result => ({
        type: result.type,
        service: result.service,
        message: result.message,
        isTimeout: result.isTimeout
      }))
      return {
        success,
        failures: failures.length ? failures : undefined,
        ping,
        details: details
      }
    })

}

function prepareChecksOfType(type, checks) {
  if (!checks) return []
  if (_.isArray(checks)) {
    return _.compact(checks).map(check => prepareCheck(check, {type}))
  } else {
    return _.compact(_.toPairs(checks)
      .map(function (serviceAndCheck) {
        const service = serviceAndCheck[0],
          check = serviceAndCheck[1]
        return prepareCheck(check, {type, service})
      }))
  }
}

function prepareCheck(check, suggestions) {
  if (!check) return null
  return {
    service: check.name || suggestions.name || 'unspecified',
    type: check.type || suggestions.type,
    run: (check.apply ? check : check.run) || canNotRun
  }
}

function checkSingleHealth(check) {
  const dateAtStart = new Date().valueOf()
  const baseOutput = {service: check.service, type: check.type}
  return P.try(() => check.run()).timeout(check.timeout || 5000)
    .then(function (result) {
      const duration = new Date().valueOf() - dateAtStart
      return Object.assign(baseOutput, {success: true, duration})
    }, function (err) {
      if (err instanceof P.TimeoutError) {
        return Object.assign(baseOutput, {success: false, isTimeout: true})
      } else {
        return Object.assign(baseOutput, {success: false, message: err.message || err})
      }
    })
}

function noopMiddleware(req, res, next) {
  next()
}

function disableCache(req, res, next) {
  res.set('Cache-Control', 'no-cache, no-store, must-revalidate')
  res.set('Pragma', 'no-cache')
  res.set('Expires', '0')
  next()
}

function canNotRun() {
  throw new Error('Non-executable implementation')
}
<commit_msg>Use the suggested service name properly<commit_after>'use strict'

const P = require('bluebird'),
  _ = require('lodash')

let configuration = {}

exports.configure = function (internalChecks, integrationChecks) {
  configuration = {
    internalChecks: prepareChecksOfType('internal', internalChecks),
    integrationChecks: prepareChecksOfType('integration', integrationChecks)
  }
}

exports.setupExpressRoutes = function (app, prefix, additionalMiddleware) {
  app.get((prefix || '') + '/health/:mode?', disableCache, additionalMiddleware || noopMiddleware, exports.expressHealthCheck)
}

exports.expressHealthCheck = function (req, res, next) {
  const internalOnly = req.params.mode === 'internal' || req.query.mode === 'internal' || req.query.internal

  const healthChecks = configuration.internalChecks.concat(internalOnly ? [] : configuration.integrationChecks)

  checkHealth(healthChecks)
    .then(function (results) {
      if (!results.success) res.status(500)
      res.send(results)
    })
    .catch(next)
}

function checkHealth(checks) {
  return P.all(checks.map(checkSingleHealth))
    .then(function (results) {
      const success = results.every(result => result.success),
        successfulChecks = results.filter(result => result.success),
        ping = _.fromPairs(successfulChecks.map(result => [result.service, result.duration])),
        details = _.fromPairs(successfulChecks.filter(check => check.details).map(check => [check.service, check.details]))

      let failures = results.filter(result => !result.success).map(result => ({
        type: result.type,
        service: result.service,
        message: result.message,
        isTimeout: result.isTimeout
      }))
      return {
        success,
        failures: failures.length ? failures : undefined,
        ping,
        details: details
      }
    })

}

function prepareChecksOfType(type, checks) {
  if (!checks) return []
  if (_.isArray(checks)) {
    return _.compact(checks).map(check => prepareCheck(check, {type}))
  } else {
    return _.compact(_.toPairs(checks)
      .map(function (serviceAndCheck) {
        const service = serviceAndCheck[0],
          check = serviceAndCheck[1]
        return prepareCheck(check, {type, service})
      }))
  }
}

function prepareCheck(check, suggestions) {
  if (!check) return null
  return {
    service: suggestions.service || check.name || 'unspecified',
    type: check.type || suggestions.type,
    run: (check.apply ? check : check.run) || canNotRun
  }
}

function checkSingleHealth(check) {
  const dateAtStart = new Date().valueOf()
  const baseOutput = {service: check.service, type: check.type}
  return P.try(() => check.run()).timeout(check.timeout || 5000)
    .then(function (result) {
      const duration = new Date().valueOf() - dateAtStart
      return Object.assign(baseOutput, {success: true, duration})
    }, function (err) {
      if (err instanceof P.TimeoutError) {
        return Object.assign(baseOutput, {success: false, isTimeout: true})
      } else {
        return Object.assign(baseOutput, {success: false, message: err.message || err})
      }
    })
}

function noopMiddleware(req, res, next) {
  next()
}

function disableCache(req, res, next) {
  res.set('Cache-Control', 'no-cache, no-store, must-revalidate')
  res.set('Pragma', 'no-cache')
  res.set('Expires', '0')
  next()
}

function canNotRun() {
  throw new Error('Non-executable implementation')
}
<|endoftext|>