<commit_before>import _ from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { withStyles } from 'material-ui/styles';
import Grid from 'material-ui/Grid';
import Button from 'material-ui/Button';
import { FormControl } from 'material-ui/Form';
/* import { FormControlLabel } from 'material-ui/Form';*/
import Input, { InputLabel } from 'material-ui/Input';
import { Link } from 'react-router';

import { MdLoop, MdChevronRight } from 'react-icons/lib/md';

import axios from 'axios';
import { apiRoot } from 'utils/constants';
import GeometryCanvasWithOptions from 'components/GeometryCanvasWithOptions';

import * as catKitActions from 'containers/CatKitDemo/actions';
import * as prototypeSearchActions from 'containers/PrototypeSearch/actions';
import * as actions from './actions';
import { styles } from './styles';

const backendRoot = `${apiRoot}/apps/bulkEnumerator`;
const url = `${backendRoot}/get_structure`;

const initialState = {
  loading: false,
  loadingParameters: false,
};

export class CellParameterInput extends React.Component {  // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    this.state = _.merge(initialState,
      _.pick(props, ['cellParameters']));
    this.getStructure = this.getStructure.bind(this);
    this.handleCellParameterChange = this.handleCellParameterChange.bind(this);
    this.handoffBulkStructure = this.handoffBulkStructure.bind(this);
    this.handoffPrototypeSearch = this.handoffPrototypeSearch.bind(this);
  }
  componentDidMount() {
    this.getStructure();
  }

  componentWillReceiveProps(nextProps) {
    const cellParameters = nextProps.cellParameters;
    this.props.setCellParameters(cellParameters);
    this.setState({
      cellParameters,
    });
  }

  getStructure() {
    const params = { params: {
      spacegroup: this.props.spacegroup,
      wyckoffPositions: [this.props.wyckoffPoints.map((point) => point.symbol)],
      wyckoffSpecies: [this.props.wyckoffPoints.map((point) => point.species)],
      cellParams: this.props.cellParameters,

    } };
    axios.get(url, params).then((response) => {
      this.props.setCellParameters(response.data.cell_params);
      this.props.receiveBulkStructure(response.data.std_cif);
      this.props.setName(response.data.name);
    });
  }

  handleCellParameterChange(key) {
    return (event) => {
      const cellParameters = this.props.cellParameters;
      cellParameters[key] = event.target.value;
      this.props.setCellParameters(cellParameters);
      this.setState({
        cellParameters,
      });
    };
  }

  handoffPrototypeSearch(name) {
    this.props.prototypeSearchSaveSearchTerms(`prototype:${name}`);
  }

  handoffBulkStructure() {
    const bulkParams = {
      wyckoff: {
        name: this.props.name,
        spacegroup: this.props.spacegroup,
      },
    };

    this.props.receiveBulkCif(this.props.bulkStructure);
    this.props.saveBulkParams(bulkParams);
    this.props.dropBulkInput();
  }

  render() {
    return (

Structure Preview

        <Grid container direction="row" justify="center">
          <Grid item >
            <GeometryCanvasWithOptions
              cifdata={this.props.bulkStructure}
              uniqueId="bulk_preview"
              id="bulk_preview"
              x={2} y={2} z={2}
            />
          </Grid>
        </Grid>
        <Grid container direction="row" justify="space-between">
          <Grid item >

Input Cell Parameters

          </Grid>
          <Grid item >
            <Button
              className={this.props.classes.button}
              color="primary"
              raised
              onClick={this.getStructure}
            >
              <MdLoop />{' \u00A0\u00A0'} Update Structure
            </Button>
          </Grid>
        </Grid>
        <Grid container direction="row">
          {Object.keys(this.state.cellParameters).map((name, i) => (
            <Grid
              key={`fc_input_${i}`}
              item
            >
              <FormControl
                className={this.props.classes.formControl}
              >
                <InputLabel
                  htmlFor={`parameter-${i}`}
                  className={this.props.classes.inputLabel}
                >{name}</InputLabel>
                <Input
                  id={`parameter_${i}`}
                  name={`parameter_${i}`}
                  value={this.state.cellParameters[name]}
                  onChange={this.handleCellParameterChange(name)}
                  onKeyDown={(event) => {
                    if (event.nativeEvent.keyCode === 13) {
                      this.getStructure();
                    }
                  }}

                />
              </FormControl>
            </Grid>
          ))}
        </Grid>
        <Grid container direction="row" justify="space-between">
          <Grid item>

Prototype Name

{_.isEmpty(this.props.name) ? 'Name couldnt be determined' :
            {this.props.name}
            }
              {'\u00A0\u00A0'}
              <Link
                className={this.props.classes.buttonLink}
                to={'/prototypeSearch'}
              >
                <Button
                  color="primary"
                  raised
                  onClick={() => this.handoffPrototypeSearch(this.props.name)}
                >
                  Search similar structures
                  <MdChevronRight />
                </Button>
              </Link>

          </Grid>
          <Grid item>

CatKit

              Cut arbitrary slabs using
              <Link
                className={this.props.classes.buttonLink}
                to={'/catkitDemo'}
              >
                <Button
                  color="primary"
                  raised
                  onClick={this.handoffBulkStructure}
                  className={this.props.classes.button}
                >
                CatKit <MdChevronRight />
                </Button>
              </Link>
            .

          </Grid>
        </Grid>

    );
  }

}

CellParameterInput.propTypes = {
  spacegroup: PropTypes.number.isRequired,
  wyckoffPoints: PropTypes.array,
  cellParameters: PropTypes.object,
  bulkStructure: PropTypes.string,
  setCellParameters: PropTypes.func,
  receiveBulkStructure: PropTypes.func,
  receiveBulkCif: PropTypes.func,
  dropBulkInput: PropTypes.func,
  saveBulkParams: PropTypes.func,
  prototypeSearchSaveSearchTerms: PropTypes.func,
  setName: PropTypes.func,
  classes: PropTypes.object,
  name: PropTypes.string,
};

const mapStateToProps = (state) => ({
  cellParameters: state.get('bulkGeneratorReducer').cellParameters,
  name: state.get('bulkGeneratorReducer').name,
  spacegroup: state.get('bulkGeneratorReducer').spacegroup,
  wyckoffPoints: state.get('bulkGeneratorReducer').wyckoffPoints,
  bulkStructure: state.get('bulkGeneratorReducer').bulkStructure,
});

const mapDispatchToProps = (dispatch) => ({
  setCellParameters: (cellParameters) => {
    dispatch(actions.setCellParameters(cellParameters));
  },
  receiveBulkStructure: (bulkStructure) => {
    dispatch(actions.receiveBulkStructure(bulkStructure));
  },
  setName: (name) => {
    dispatch(actions.setName(name));
  },
  receiveBulkCif: (bulkCif) => {
    dispatch(catKitActions.receiveBulkCif(bulkCif));
  },
  dropBulkInput: () => {
    dispatch(catKitActions.dropBulkInput());
  },
  saveBulkParams: (bulkParams) => {
    dispatch(catKitActions.saveBulkParams(bulkParams));
  },
  prototypeSearchSaveSearchTerms: (x) => {
    dispatch(prototypeSearchActions.saveSearchTerms(x));
  },
});

export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles, { withTheme: true })(CellParameterInput));

<commit_msg>Fixed bug in handing wyckoff parameters from bulk generator to catkit demo<commit_after>import _ from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { withStyles } from 'material-ui/styles';
import Grid from 'material-ui/Grid';
import Button from 'material-ui/Button';
import { FormControl } from 'material-ui/Form';
/* import { FormControlLabel } from 'material-ui/Form';*/
import Input, { InputLabel } from 'material-ui/Input';
import { Link } from 'react-router';

import { MdLoop, MdChevronRight } from 'react-icons/lib/md';

import axios from 'axios';
import { apiRoot } from 'utils/constants';
import GeometryCanvasWithOptions from 'components/GeometryCanvasWithOptions';

import * as catKitActions from 'containers/CatKitDemo/actions';
import * as prototypeSearchActions from 'containers/PrototypeSearch/actions';
import * as actions from './actions';
import { styles } from './styles';

const backendRoot = `${apiRoot}/apps/bulkEnumerator`;
const url = `${backendRoot}/get_structure`;

const initialState = {
  loading: false,
  loadingParameters: false,
};

export class CellParameterInput extends React.Component {  // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    this.state = _.merge(initialState,
      _.pick(props, ['cellParameters']));
    this.getStructure = this.getStructure.bind(this);
    this.handleCellParameterChange = this.handleCellParameterChange.bind(this);
    this.handoffBulkStructure = this.handoffBulkStructure.bind(this);
    this.handoffPrototypeSearch = this.handoffPrototypeSearch.bind(this);
  }
  componentDidMount() {
    this.getStructure();
  }

  componentWillReceiveProps(nextProps) {
    const cellParameters = nextProps.cellParameters;
    this.props.setCellParameters(cellParameters);
    this.setState({
      cellParameters,
    });
  }

  getStructure() {
    const params = { params: {
      spacegroup: this.props.spacegroup,
      wyckoffPositions: [this.props.wyckoffPoints.map((point) => point.symbol)],
      wyckoffSpecies: [this.props.wyckoffPoints.map((point) => point.species)],
      cellParams: this.props.cellParameters,

    } };
    axios.get(url, params).then((response) => {
      this.props.setCellParameters(response.data.cell_params);
      this.props.receiveBulkStructure(response.data.std_cif);
      this.props.setName(response.data.name);
    });
  }

  handleCellParameterChange(key) {
    return (event) => {
      const cellParameters = this.props.cellParameters;
      cellParameters[key] = event.target.value;
      this.props.setCellParameters(cellParameters);
      this.setState({
        cellParameters,
      });
    };
  }

  handoffPrototypeSearch(name) {
    this.props.prototypeSearchSaveSearchTerms(`prototype:${name}`);
  }

  handoffBulkStructure() {
    const bulkParams = {
      elements: this.props.wyckoffPoints.map((elem) => elem.species),
      wyckoff: {
        name: this.props.name,
        spacegroup: this.props.spacegroup,
        elements: this.props.wyckoffPoints.map((elem) => elem.species),
        species: this.props.wyckoffPoints.map((elem) => elem.species),
        wyckoff: this.props.wyckoffPoints.map((elem) => elem.symbol),
      },
    };

    this.props.receiveBulkCif(this.props.bulkStructure);
    this.props.saveBulkParams(bulkParams);
    this.props.dropBulkInput();
  }

  render() {
    return (

Structure Preview

        <Grid container direction="row" justify="center">
          <Grid item >
            <GeometryCanvasWithOptions
              cifdata={this.props.bulkStructure}
              uniqueId="bulk_preview"
              id="bulk_preview"
              x={2} y={2} z={2}
            />
          </Grid>
        </Grid>
        <Grid container direction="row" justify="space-between">
          <Grid item >

Input Cell Parameters

          </Grid>
          <Grid item >
            <Button
              className={this.props.classes.button}
              color="primary"
              raised
              onClick={this.getStructure}
            >
              <MdLoop />{' \u00A0\u00A0'} Update Structure
            </Button>
          </Grid>
        </Grid>
        <Grid container direction="row">
          {Object.keys(this.state.cellParameters).map((name, i) => (
            <Grid
              key={`fc_input_${i}`}
              item
            >
              <FormControl
                className={this.props.classes.formControl}
              >
                <InputLabel
                  htmlFor={`parameter-${i}`}
                  className={this.props.classes.inputLabel}
                >{name}</InputLabel>
                <Input
                  id={`parameter_${i}`}
                  name={`parameter_${i}`}
                  value={this.state.cellParameters[name]}
                  onChange={this.handleCellParameterChange(name)}
                  onKeyDown={(event) => {
                    if (event.nativeEvent.keyCode === 13) {
                      this.getStructure();
                    }
                  }}

                />
              </FormControl>
            </Grid>
          ))}
        </Grid>
        <Grid container direction="row" justify="space-between">
          <Grid item>

Prototype Name

{_.isEmpty(this.props.name) ? 'Name couldnt be determined' :
            {this.props.name}
            }
              {'\u00A0\u00A0'}
              <Link
                className={this.props.classes.buttonLink}
                to={'/prototypeSearch'}
              >
                <Button
                  color="primary"
                  raised
                  onClick={() => this.handoffPrototypeSearch(this.props.name)}
                >
                  Search similar structures
                  <MdChevronRight />
                </Button>
              </Link>

          </Grid>
          <Grid item>

CatKit

              Cut arbitrary slabs using
              <Link
                className={this.props.classes.buttonLink}
                to={'/catkitDemo'}
              >
                <Button
                  color="primary"
                  raised
                  onClick={this.handoffBulkStructure}
                  className={this.props.classes.button}
                >
                CatKit <MdChevronRight />
                </Button>
              </Link>
            .

          </Grid>
        </Grid>

    );
  }

}

CellParameterInput.propTypes = {
  spacegroup: PropTypes.number.isRequired,
  wyckoffPoints: PropTypes.array,
  cellParameters: PropTypes.object,
  bulkStructure: PropTypes.string,
  setCellParameters: PropTypes.func,
  receiveBulkStructure: PropTypes.func,
  receiveBulkCif: PropTypes.func,
  dropBulkInput: PropTypes.func,
  saveBulkParams: PropTypes.func,
  prototypeSearchSaveSearchTerms: PropTypes.func,
  setName: PropTypes.func,
  classes: PropTypes.object,
  name: PropTypes.string,
};

const mapStateToProps = (state) => ({
  cellParameters: state.get('bulkGeneratorReducer').cellParameters,
  name: state.get('bulkGeneratorReducer').name,
  spacegroup: state.get('bulkGeneratorReducer').spacegroup,
  wyckoffPoints: state.get('bulkGeneratorReducer').wyckoffPoints,
  bulkStructure: state.get('bulkGeneratorReducer').bulkStructure,
});

const mapDispatchToProps = (dispatch) => ({
  setCellParameters: (cellParameters) => {
    dispatch(actions.setCellParameters(cellParameters));
  },
  receiveBulkStructure: (bulkStructure) => {
    dispatch(actions.receiveBulkStructure(bulkStructure));
  },
  setName: (name) => {
    dispatch(actions.setName(name));
  },
  receiveBulkCif: (bulkCif) => {
    dispatch(catKitActions.receiveBulkCif(bulkCif));
  },
  dropBulkInput: () => {
    dispatch(catKitActions.dropBulkInput());
  },
  saveBulkParams: (bulkParams) => {
    dispatch(catKitActions.saveBulkParams(bulkParams));
  },
  prototypeSearchSaveSearchTerms: (x) => {
    dispatch(prototypeSearchActions.saveSearchTerms(x));
  },
});

export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles, { withTheme: true })(CellParameterInput));

<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 * @format
 */

'use strict';

const RelayModernRecord = require('./RelayModernRecord');
const RelayProfiler = require('../util/RelayProfiler');

const invariant = require('invariant');
const warning = require('warning');

const {
  CONDITION,
  CLIENT_EXTENSION,
  DEFER,
  INLINE_FRAGMENT,
  LINKED_FIELD,
  LINKED_HANDLE,
  MODULE_IMPORT,
  SCALAR_FIELD,
  SCALAR_HANDLE,
  STREAM,
} = require('../util/RelayConcreteNode');
const {generateClientID, isClientID} = require('./ClientID');
const {
  getArgumentValues,
  getHandleStorageKey,
  getStorageKey,
  MODULE_OPERATION_KEY,
  TYPENAME_KEY,
} = require('./RelayStoreUtils');

import type {PayloadData} from '../network/RelayNetworkTypes';
import type {
  NormalizationDefer,
  NormalizationField,
  NormalizationLinkedField,
  NormalizationModuleImport,
  NormalizationNode,
  NormalizationStream,
} from '../util/NormalizationNode';
import type {Record} from '../util/RelayCombinedEnvironmentTypes';
import type {DataID, Variables} from '../util/RelayRuntimeTypes';
import type {
  HandleFieldPayload,
  IncrementalDataPlaceholder,
  ModuleImportPayload,
  MutableRecordSource,
  NormalizationSelector,
} from './RelayStoreTypes';

export type GetDataID = (
  fieldValue: {[string]: mixed},
  typeName: string,
) => mixed;

export type NormalizationOptions = {|
  +getDataID: GetDataID,
  +handleStrippedNulls?: boolean,
  +path?: $ReadOnlyArray<string>,
|};

export type NormalizedResponse = {|
  incrementalPlaceholders: Array<IncrementalDataPlaceholder>,
  fieldPayloads: Array<HandleFieldPayload>,
  moduleImportPayloads: Array<ModuleImportPayload>,
|};

/**
 * Normalizes the results of a query and standard GraphQL response, writing the
 * normalized records/fields into the given MutableRecordSource.
 *
 * If handleStrippedNulls is true, will replace fields on the Selector that
 * are not present in the response with null. Otherwise will leave fields unset.
 */
function normalize(
  recordSource: MutableRecordSource,
  selector: NormalizationSelector,
  response: PayloadData,
  options: NormalizationOptions,
): NormalizedResponse {
  const {dataID, node, variables} = selector;
  const normalizer = new RelayResponseNormalizer(
    recordSource,
    variables,
    options,
  );
  return normalizer.normalizeResponse(node, dataID, response);
}

/**
 * @private
 *
 * Helper for handling payloads.
 */
class RelayResponseNormalizer {
  _handleFieldPayloads: Array<HandleFieldPayload>;
  _handleStrippedNulls: boolean;
  _incrementalPlaceholders: Array<IncrementalDataPlaceholder>;
  _moduleImportPayloads: Array<ModuleImportPayload>;
  _path: Array<string>;
  _recordSource: MutableRecordSource;
  _variables: Variables;
  _getDataId: GetDataID;

  constructor(
    recordSource: MutableRecordSource,
    variables: Variables,
    options: NormalizationOptions,
  ) {
    this._getDataId = options.getDataID;
    this._handleFieldPayloads = [];
    this._handleStrippedNulls = options.handleStrippedNulls === true;
    this._incrementalPlaceholders = [];
    this._moduleImportPayloads = [];
    this._path = options.path ? [...options.path] : [];
    this._recordSource = recordSource;
    this._variables = variables;
  }

  normalizeResponse(
    node: NormalizationNode,
    dataID: DataID,
    data: PayloadData,
  ): NormalizedResponse {
    const record = this._recordSource.get(dataID);
    invariant(
      record,
      'RelayResponseNormalizer(): Expected root record `%s` to exist.',
      dataID,
    );
    this._traverseSelections(node, record, data);
    return {
      incrementalPlaceholders: this._incrementalPlaceholders,
      fieldPayloads: this._handleFieldPayloads,
      moduleImportPayloads: this._moduleImportPayloads,
    };
  }

  _getVariableValue(name: string): mixed {
    invariant(
      this._variables.hasOwnProperty(name),
      'RelayResponseNormalizer(): Undefined variable `%s`.',
      name,
    );
    return this._variables[name];
  }

  _getRecordType(data: PayloadData): string {
    const typeName = (data: any)[TYPENAME_KEY];
    invariant(
      typeName != null,
      'RelayResponseNormalizer(): Expected a typename for record `%s`.',
      JSON.stringify(data, null, 2),
    );
    return typeName;
  }

  _traverseSelections(
    node: NormalizationNode,
    record: Record,
    data: PayloadData,
  ): void {
    for (let i = 0; i < node.selections.length; i++) {
      const selection = node.selections[i];
      switch (selection.kind) {
        case SCALAR_FIELD:
        case LINKED_FIELD:
          this._normalizeField(node, selection, record, data);
          break;
        case CONDITION:
          const conditionValue = this._getVariableValue(selection.condition);
          if (conditionValue === selection.passingValue) {
            this._traverseSelections(selection, record, data);
          }
          break;
        case INLINE_FRAGMENT:
          const typeName = RelayModernRecord.getType(record);
          if (typeName === selection.type) {
            this._traverseSelections(selection, record, data);
          }
          break;
        case LINKED_HANDLE:
        case SCALAR_HANDLE:
          const args = selection.args
            ? getArgumentValues(selection.args, this._variables)
            : {};
          const fieldKey = getStorageKey(selection, this._variables);
          const handleKey = getHandleStorageKey(selection, this._variables);
          this._handleFieldPayloads.push({
            args,
            dataID: RelayModernRecord.getDataID(record),
            fieldKey,
            handle: selection.handle,
            handleKey,
          });
          break;
        case MODULE_IMPORT:
          this._normalizeModuleImport(node, selection, record, data);
          break;
        case DEFER:
          this._normalizeDefer(selection, record, data);
          break;
        case STREAM:
          this._normalizeStream(selection, record, data);
          break;
        case CLIENT_EXTENSION:
          const handleStrippedNulls = this._handleStrippedNulls;
          this._handleStrippedNulls = false;
          this._traverseSelections(selection, record, data);
          this._handleStrippedNulls = handleStrippedNulls;
          break;
        default:
          (selection: empty);
          invariant(
            false,
            'RelayResponseNormalizer(): Unexpected ast kind `%s`.',
            selection.kind,
          );
      }
    }
  }

  _normalizeDefer(
    defer: NormalizationDefer,
    record: Record,
    data: PayloadData,
  ) {
    const isDeferred = defer.if === null || this._getVariableValue(defer.if);
    if (__DEV__) {
      warning(
        typeof isDeferred === 'boolean',
        'RelayResponseNormalizer: Expected value for @defer `if` argument to ' +
          'be a boolean, got `%s`.',
        isDeferred,
      );
    }
    if (isDeferred === false) {
      // If defer is disabled there will be no additional response chunk:
      // normalize the data already present.
      this._traverseSelections(defer, record, data);
    } else {
      // Otherwise data *for this selection* should not be present: enqueue
      // metadata to process the subsequent response chunk.
      this._incrementalPlaceholders.push({
        kind: 'defer',
        label: defer.label,
        path: [...this._path],
        selector: {
          dataID: RelayModernRecord.getDataID(record),
          node: defer,
          variables: this._variables,
        },
        typeName: RelayModernRecord.getType(record),
      });
    }
  }

  _normalizeStream(
    stream: NormalizationStream,
    record: Record,
    data: PayloadData,
  ) {
    // Always normalize regardless of whether streaming is enabled or not,
    // this populates the initial array value (including any items when
    // initial_count > 0).
    this._traverseSelections(stream, record, data);
    const isStreamed = stream.if === null || this._getVariableValue(stream.if);
    if (__DEV__) {
      warning(
        typeof isStreamed === 'boolean',
        'RelayResponseNormalizer: Expected value for @stream `if` argument ' +
          'to be a boolean, got `%s`.',
        isStreamed,
      );
    }
    if (isStreamed === true) {
      // If streaming is enabled, *also* emit metadata to process any
      // response chunks that may be delivered.
      this._incrementalPlaceholders.push({
        kind: 'stream',
        label: stream.label,
        path: [...this._path],
        parentID: RelayModernRecord.getDataID(record),
        node: stream,
        variables: this._variables,
      });
    }
  }

  _normalizeModuleImport(
    parent: NormalizationNode,
    moduleImport: NormalizationModuleImport,
    record: Record,
    data: PayloadData,
  ) {
    invariant(
      typeof data === 'object' && data,
      'RelayResponseNormalizer: Expected data for @module to be an object.',
    );
    const typeName: string = this._getRecordType(data);
    const operationReference = data[MODULE_OPERATION_KEY];
    if (operationReference != null) {
      this._moduleImportPayloads.push({
        data,
        dataID: RelayModernRecord.getDataID(record),
        operationReference,
        path: [...this._path],
        typeName,
        variables: this._variables,
      });
    }
  }

  _normalizeField(
    parent: NormalizationNode,
    selection: NormalizationField,
    record: Record,
    data: PayloadData,
  ) {
    invariant(
      typeof data === 'object' && data,
      'writeField(): Expected data for field `%s` to be an object.',
      selection.name,
    );
    const responseKey = selection.alias || selection.name;
    const storageKey = getStorageKey(selection, this._variables);
    const fieldValue = data[responseKey];
    if (fieldValue == null) {
      if (fieldValue === undefined && !this._handleStrippedNulls) {
        // If we're not stripping nulls, undefined fields are unset
        return;
      }
      if (__DEV__) {
        warning(
          parent.kind === LINKED_FIELD && parent.concreteType == null
            ? true
            : Object.prototype.hasOwnProperty.call(data, responseKey),
          'RelayResponseNormalizer(): Payload did not contain a value ' +
            'for field `%s: %s`. Check that you are parsing with the same ' +
            'query that was used to fetch the payload.',
          responseKey,
          storageKey,
        );
      }
      RelayModernRecord.setValue(record, storageKey, null);
      return;
    }

    if (selection.kind === SCALAR_FIELD) {
      RelayModernRecord.setValue(record, storageKey, fieldValue);
    } else if (selection.kind === LINKED_FIELD) {
      this._path.push(responseKey);
      if (selection.plural) {
        this._normalizePluralLink(selection, record, storageKey, fieldValue);
      } else {
        this._normalizeLink(selection, record, storageKey, fieldValue);
      }
      this._path.pop();
    } else {
      (selection: empty);
      invariant(
        false,
        'RelayResponseNormalizer(): Unexpected ast kind `%s` during normalization.',
        selection.kind,
      );
    }
  }

  _normalizeLink(
    field: NormalizationLinkedField,
    record: Record,
    storageKey: string,
    fieldValue: mixed,
  ): void {
    invariant(
      typeof fieldValue === 'object' && fieldValue,
      'RelayResponseNormalizer: Expected data for field `%s` to be an object.',
      storageKey,
    );
    const nextID =
      this._getDataId(
        fieldValue,
        field.concreteType ?? this._getRecordType(fieldValue),
      ) ||
      // Reuse previously generated client IDs
      RelayModernRecord.getLinkedRecordID(record, storageKey) ||
      generateClientID(RelayModernRecord.getDataID(record), storageKey);
    invariant(
      typeof nextID === 'string',
      'RelayResponseNormalizer: Expected id on field `%s` to be a string.',
      storageKey,
    );
    RelayModernRecord.setLinkedRecordID(record, storageKey, nextID);
    let nextRecord = this._recordSource.get(nextID);
    if (!nextRecord) {
      /* $FlowFixMe(>=0.98.0 site=www,mobile) This comment suppresses an error
       * found when Flow v0.98 was deployed. To see the error delete this
       * comment and run Flow. */
      const typeName = field.concreteType || this._getRecordType(fieldValue);
      nextRecord = RelayModernRecord.create(nextID, typeName);
      this._recordSource.set(nextID, nextRecord);
    } else if (__DEV__) {
      this._validateRecordType(nextRecord, field, fieldValue);
    }
    /* $FlowFixMe(>=0.98.0 site=www,mobile) This comment suppresses an error
     * found when Flow v0.98 was deployed. To see the error delete this comment
     * and run Flow. */
    this._traverseSelections(field, nextRecord, fieldValue);
  }

  _normalizePluralLink(
    field: NormalizationLinkedField,
    record: Record,
    storageKey: string,
    fieldValue: mixed,
  ): void {
    invariant(
      Array.isArray(fieldValue),
      'RelayResponseNormalizer: Expected data for field `%s` to be an array ' +
        'of objects.',
      storageKey,
    );
    const prevIDs = RelayModernRecord.getLinkedRecordIDs(record, storageKey);
    const nextIDs = [];
    fieldValue.forEach((item, nextIndex) => {
      // validate response data
      if (item == null) {
        nextIDs.push(item);
        return;
      }
      this._path.push(String(nextIndex));
      invariant(
        typeof item === 'object',
        'RelayResponseNormalizer: Expected elements for field `%s` to be ' +
          'objects.',
        storageKey,
      );
      const nextID =
        this._getDataId(
          item,
          field.concreteType ?? this._getRecordType(item),
        ) ||
        (prevIDs && prevIDs[nextIndex]) || // Reuse previously generated client IDs:
        generateClientID(
          RelayModernRecord.getDataID(record),
          storageKey,
          nextIndex,
        );
      invariant(
        typeof nextID === 'string',
        'RelayResponseNormalizer: Expected id of elements of field `%s` to ' +
          'be strings.',
        storageKey,
      );

      nextIDs.push(nextID);
      let nextRecord = this._recordSource.get(nextID);
      if (!nextRecord) {
        /* $FlowFixMe(>=0.98.0 site=www,mobile) This comment suppresses an
         * error found when Flow v0.98 was deployed. To see the error delete
         * this comment and run Flow. */
        const typeName = field.concreteType || this._getRecordType(item);
        nextRecord = RelayModernRecord.create(nextID, typeName);
        this._recordSource.set(nextID, nextRecord);
      } else if (__DEV__) {
        this._validateRecordType(nextRecord, field, item);
      }
      /* $FlowFixMe(>=0.98.0 site=www,mobile) This comment suppresses an error
       * found when Flow v0.98 was deployed. To see the error delete this
       * comment and run Flow. */
      this._traverseSelections(field, nextRecord, item);
      this._path.pop();
    });
    RelayModernRecord.setLinkedRecordIDs(record, storageKey, nextIDs);
  }

  /**
   * Warns if the type of the record does not match the type of the field/payload.
   */
  _validateRecordType(
    record: Record,
    field: NormalizationLinkedField,
    payload: Object,
  ): void {
    const typeName =
      field.kind === 'LinkedField'
        ? field.concreteType || this._getRecordType(payload)
        : this._getRecordType(payload);
    warning(
      isClientID(RelayModernRecord.getDataID(record)) ||
        RelayModernRecord.getType(record) === typeName,
      'RelayResponseNormalizer: Invalid record `%s`. Expected %s to be ' +
        'be consistent, but the record was assigned conflicting types `%s` ' +
        'and `%s`. The GraphQL server likely violated the globally unique ' +
        'id requirement by returning the same id for different objects.',
      RelayModernRecord.getDataID(record),
      TYPENAME_KEY,
      RelayModernRecord.getType(record),
      typeName,
    );
  }
}

// eslint-disable-next-line no-func-assign
normalize = RelayProfiler.instrument(
  'RelayResponseNormalizer.normalize',
  normalize,
);

module.exports = {normalize};
<commit_msg>Add additional Flow error suppressions to Relay ahead of the v0.98 deploy<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 * @format
 */

'use strict';

const RelayModernRecord = require('./RelayModernRecord');
const RelayProfiler = require('../util/RelayProfiler');

const invariant = require('invariant');
const warning = require('warning');

const {
  CONDITION,
  CLIENT_EXTENSION,
  DEFER,
  INLINE_FRAGMENT,
  LINKED_FIELD,
  LINKED_HANDLE,
  MODULE_IMPORT,
  SCALAR_FIELD,
  SCALAR_HANDLE,
  STREAM,
} = require('../util/RelayConcreteNode');
const {generateClientID, isClientID} = require('./ClientID');
const {
  getArgumentValues,
  getHandleStorageKey,
  getStorageKey,
  MODULE_OPERATION_KEY,
  TYPENAME_KEY,
} = require('./RelayStoreUtils');

import type {PayloadData} from '../network/RelayNetworkTypes';
import type {
  NormalizationDefer,
  NormalizationField,
  NormalizationLinkedField,
  NormalizationModuleImport,
  NormalizationNode,
  NormalizationStream,
} from '../util/NormalizationNode';
import type {Record} from '../util/RelayCombinedEnvironmentTypes';
import type {DataID, Variables} from '../util/RelayRuntimeTypes';
import type {
  HandleFieldPayload,
  IncrementalDataPlaceholder,
  ModuleImportPayload,
  MutableRecordSource,
  NormalizationSelector,
} from './RelayStoreTypes';

export type GetDataID = (
  fieldValue: {[string]: mixed},
  typeName: string,
) => mixed;

export type NormalizationOptions = {|
  +getDataID: GetDataID,
  +handleStrippedNulls?: boolean,
  +path?: $ReadOnlyArray<string>,
|};

export type NormalizedResponse = {|
  incrementalPlaceholders: Array<IncrementalDataPlaceholder>,
  fieldPayloads: Array<HandleFieldPayload>,
  moduleImportPayloads: Array<ModuleImportPayload>,
|};

/**
 * Normalizes the results of a query and standard GraphQL response, writing the
 * normalized records/fields into the given MutableRecordSource.
 *
 * If handleStrippedNulls is true, will replace fields on the Selector that
 * are not present in the response with null. Otherwise will leave fields unset.
 */
function normalize(
  recordSource: MutableRecordSource,
  selector: NormalizationSelector,
  response: PayloadData,
  options: NormalizationOptions,
): NormalizedResponse {
  const {dataID, node, variables} = selector;
  const normalizer = new RelayResponseNormalizer(
    recordSource,
    variables,
    options,
  );
  return normalizer.normalizeResponse(node, dataID, response);
}

/**
 * @private
 *
 * Helper for handling payloads.
 */
class RelayResponseNormalizer {
  _handleFieldPayloads: Array<HandleFieldPayload>;
  _handleStrippedNulls: boolean;
  _incrementalPlaceholders: Array<IncrementalDataPlaceholder>;
  _moduleImportPayloads: Array<ModuleImportPayload>;
  _path: Array<string>;
  _recordSource: MutableRecordSource;
  _variables: Variables;
  _getDataId: GetDataID;

  constructor(
    recordSource: MutableRecordSource,
    variables: Variables,
    options: NormalizationOptions,
  ) {
    this._getDataId = options.getDataID;
    this._handleFieldPayloads = [];
    this._handleStrippedNulls = options.handleStrippedNulls === true;
    this._incrementalPlaceholders = [];
    this._moduleImportPayloads = [];
    this._path = options.path ? [...options.path] : [];
    this._recordSource = recordSource;
    this._variables = variables;
  }

  normalizeResponse(
    node: NormalizationNode,
    dataID: DataID,
    data: PayloadData,
  ): NormalizedResponse {
    const record = this._recordSource.get(dataID);
    invariant(
      record,
      'RelayResponseNormalizer(): Expected root record `%s` to exist.',
      dataID,
    );
    this._traverseSelections(node, record, data);
    return {
      incrementalPlaceholders: this._incrementalPlaceholders,
      fieldPayloads: this._handleFieldPayloads,
      moduleImportPayloads: this._moduleImportPayloads,
    };
  }

  _getVariableValue(name: string): mixed {
    invariant(
      this._variables.hasOwnProperty(name),
      'RelayResponseNormalizer(): Undefined variable `%s`.',
      name,
    );
    return this._variables[name];
  }

  _getRecordType(data: PayloadData): string {
    const typeName = (data: any)[TYPENAME_KEY];
    invariant(
      typeName != null,
      'RelayResponseNormalizer(): Expected a typename for record `%s`.',
      JSON.stringify(data, null, 2),
    );
    return typeName;
  }

  _traverseSelections(
    node: NormalizationNode,
    record: Record,
    data: PayloadData,
  ): void {
    for (let i = 0; i < node.selections.length; i++) {
      const selection = node.selections[i];
      switch (selection.kind) {
        case SCALAR_FIELD:
        case LINKED_FIELD:
          this._normalizeField(node, selection, record, data);
          break;
        case CONDITION:
          const conditionValue = this._getVariableValue(selection.condition);
          if (conditionValue === selection.passingValue) {
            this._traverseSelections(selection, record, data);
          }
          break;
        case INLINE_FRAGMENT:
          const typeName = RelayModernRecord.getType(record);
          if (typeName === selection.type) {
            this._traverseSelections(selection, record, data);
          }
          break;
        case LINKED_HANDLE:
        case SCALAR_HANDLE:
          const args = selection.args
            ? getArgumentValues(selection.args, this._variables)
            : {};
          const fieldKey = getStorageKey(selection, this._variables);
          const handleKey = getHandleStorageKey(selection, this._variables);
          this._handleFieldPayloads.push({
            args,
            dataID: RelayModernRecord.getDataID(record),
            fieldKey,
            handle: selection.handle,
            handleKey,
          });
          break;
        case MODULE_IMPORT:
          this._normalizeModuleImport(node, selection, record, data);
          break;
        case DEFER:
          this._normalizeDefer(selection, record, data);
          break;
        case STREAM:
          this._normalizeStream(selection, record, data);
          break;
        case CLIENT_EXTENSION:
          const handleStrippedNulls = this._handleStrippedNulls;
          this._handleStrippedNulls = false;
          this._traverseSelections(selection, record, data);
          this._handleStrippedNulls = handleStrippedNulls;
          break;
        default:
          (selection: empty);
          invariant(
            false,
            'RelayResponseNormalizer(): Unexpected ast kind `%s`.',
            selection.kind,
          );
      }
    }
  }

  _normalizeDefer(
    defer: NormalizationDefer,
    record: Record,
    data: PayloadData,
  ) {
    const isDeferred = defer.if === null || this._getVariableValue(defer.if);
    if (__DEV__) {
      warning(
        typeof isDeferred === 'boolean',
        'RelayResponseNormalizer: Expected value for @defer `if` argument to ' +
          'be a boolean, got `%s`.',
        isDeferred,
      );
    }
    if (isDeferred === false) {
      // If defer is disabled there will be no additional response chunk:
      // normalize the data already present.
      this._traverseSelections(defer, record, data);
    } else {
      // Otherwise data *for this selection* should not be present: enqueue
      // metadata to process the subsequent response chunk.
      this._incrementalPlaceholders.push({
        kind: 'defer',
        label: defer.label,
        path: [...this._path],
        selector: {
          dataID: RelayModernRecord.getDataID(record),
          node: defer,
          variables: this._variables,
        },
        typeName: RelayModernRecord.getType(record),
      });
    }
  }

  _normalizeStream(
    stream: NormalizationStream,
    record: Record,
    data: PayloadData,
  ) {
    // Always normalize regardless of whether streaming is enabled or not,
    // this populates the initial array value (including any items when
    // initial_count > 0).
    this._traverseSelections(stream, record, data);
    const isStreamed = stream.if === null || this._getVariableValue(stream.if);
    if (__DEV__) {
      warning(
        typeof isStreamed === 'boolean',
        'RelayResponseNormalizer: Expected value for @stream `if` argument ' +
          'to be a boolean, got `%s`.',
        isStreamed,
      );
    }
    if (isStreamed === true) {
      // If streaming is enabled, *also* emit metadata to process any
      // response chunks that may be delivered.
      this._incrementalPlaceholders.push({
        kind: 'stream',
        label: stream.label,
        path: [...this._path],
        parentID: RelayModernRecord.getDataID(record),
        node: stream,
        variables: this._variables,
      });
    }
  }

  _normalizeModuleImport(
    parent: NormalizationNode,
    moduleImport: NormalizationModuleImport,
    record: Record,
    data: PayloadData,
  ) {
    invariant(
      typeof data === 'object' && data,
      'RelayResponseNormalizer: Expected data for @module to be an object.',
    );
    const typeName: string = this._getRecordType(data);
    const operationReference = data[MODULE_OPERATION_KEY];
    if (operationReference != null) {
      this._moduleImportPayloads.push({
        data,
        dataID: RelayModernRecord.getDataID(record),
        operationReference,
        path: [...this._path],
        typeName,
        variables: this._variables,
      });
    }
  }

  _normalizeField(
    parent: NormalizationNode,
    selection: NormalizationField,
    record: Record,
    data: PayloadData,
  ) {
    invariant(
      typeof data === 'object' && data,
      'writeField(): Expected data for field `%s` to be an object.',
      selection.name,
    );
    const responseKey = selection.alias || selection.name;
    const storageKey = getStorageKey(selection, this._variables);
    const fieldValue = data[responseKey];
    if (fieldValue == null) {
      if (fieldValue === undefined && !this._handleStrippedNulls) {
        // If we're not stripping nulls, undefined fields are unset
        return;
      }
      if (__DEV__) {
        warning(
          parent.kind === LINKED_FIELD && parent.concreteType == null
            ? true
            : Object.prototype.hasOwnProperty.call(data, responseKey),
          'RelayResponseNormalizer(): Payload did not contain a value ' +
            'for field `%s: %s`. Check that you are parsing with the same ' +
            'query that was used to fetch the payload.',
          responseKey,
          storageKey,
        );
      }
      RelayModernRecord.setValue(record, storageKey, null);
      return;
    }

    if (selection.kind === SCALAR_FIELD) {
      RelayModernRecord.setValue(record, storageKey, fieldValue);
    } else if (selection.kind === LINKED_FIELD) {
      this._path.push(responseKey);
      if (selection.plural) {
        this._normalizePluralLink(selection, record, storageKey, fieldValue);
      } else {
        this._normalizeLink(selection, record, storageKey, fieldValue);
      }
      this._path.pop();
    } else {
      (selection: empty);
      invariant(
        false,
        'RelayResponseNormalizer(): Unexpected ast kind `%s` during normalization.',
        selection.kind,
      );
    }
  }

  _normalizeLink(
    field: NormalizationLinkedField,
    record: Record,
    storageKey: string,
    fieldValue: mixed,
  ): void {
    invariant(
      typeof fieldValue === 'object' && fieldValue,
      'RelayResponseNormalizer: Expected data for field `%s` to be an object.',
      storageKey,
    );
    const nextID =
      this._getDataId(
        /* $FlowFixMe(>=0.98.0 site=www,mobile) This comment suppresses an
         * error found when Flow v0.98 was deployed. To see the error delete
         * this comment and run Flow. */
        fieldValue,
        /* $FlowFixMe(>=0.98.0 site=www,mobile) This comment suppresses an
         * error found when Flow v0.98 was deployed. To see the error delete
         * this comment and run Flow. */
        field.concreteType ?? this._getRecordType(fieldValue),
      ) ||
      // Reuse previously generated client IDs
      RelayModernRecord.getLinkedRecordID(record, storageKey) ||
      generateClientID(RelayModernRecord.getDataID(record), storageKey);
    invariant(
      typeof nextID === 'string',
      'RelayResponseNormalizer: Expected id on field `%s` to be a string.',
      storageKey,
    );
    RelayModernRecord.setLinkedRecordID(record, storageKey, nextID);
    let nextRecord = this._recordSource.get(nextID);
    if (!nextRecord) {
      /* $FlowFixMe(>=0.98.0 site=www,mobile) This comment suppresses an error
       * found when Flow v0.98 was deployed. To see the error delete this
       * comment and run Flow. */
      const typeName = field.concreteType || this._getRecordType(fieldValue);
      nextRecord = RelayModernRecord.create(nextID, typeName);
      this._recordSource.set(nextID, nextRecord);
    } else if (__DEV__) {
      this._validateRecordType(nextRecord, field, fieldValue);
    }
    /* $FlowFixMe(>=0.98.0 site=www,mobile) This comment suppresses an error
     * found when Flow v0.98 was deployed. To see the error delete this comment
     * and run Flow. */
    this._traverseSelections(field, nextRecord, fieldValue);
  }

  _normalizePluralLink(
    field: NormalizationLinkedField,
    record: Record,
    storageKey: string,
    fieldValue: mixed,
  ): void {
    invariant(
      Array.isArray(fieldValue),
      'RelayResponseNormalizer: Expected data for field `%s` to be an array ' +
        'of objects.',
      storageKey,
    );
    const prevIDs = RelayModernRecord.getLinkedRecordIDs(record, storageKey);
    const nextIDs = [];
    fieldValue.forEach((item, nextIndex) => {
      // validate response data
      if (item == null) {
        nextIDs.push(item);
        return;
      }
      this._path.push(String(nextIndex));
      invariant(
        typeof item === 'object',
        'RelayResponseNormalizer: Expected elements for field `%s` to be ' +
          'objects.',
        storageKey,
      );
      const nextID =
        this._getDataId(
          /* $FlowFixMe(>=0.98.0 site=www,mobile) This comment suppresses an
           * error found when Flow v0.98 was deployed. To see the error delete
           * this comment and run Flow. */
          item,
          /* $FlowFixMe(>=0.98.0 site=www,mobile) This comment suppresses an
           * error found when Flow v0.98 was deployed. To see the error delete
           * this comment and run Flow. */
          field.concreteType ?? this._getRecordType(item),
        ) ||
        (prevIDs && prevIDs[nextIndex]) || // Reuse previously generated client IDs:
        generateClientID(
          RelayModernRecord.getDataID(record),
          storageKey,
          nextIndex,
        );
      invariant(
        typeof nextID === 'string',
        'RelayResponseNormalizer: Expected id of elements of field `%s` to ' +
          'be strings.',
        storageKey,
      );

      nextIDs.push(nextID);
      let nextRecord = this._recordSource.get(nextID);
      if (!nextRecord) {
        /* $FlowFixMe(>=0.98.0 site=www,mobile) This comment suppresses an
         * error found when Flow v0.98 was deployed. To see the error delete
         * this comment and run Flow. */
        const typeName = field.concreteType || this._getRecordType(item);
        nextRecord = RelayModernRecord.create(nextID, typeName);
        this._recordSource.set(nextID, nextRecord);
      } else if (__DEV__) {
        this._validateRecordType(nextRecord, field, item);
      }
      /* $FlowFixMe(>=0.98.0 site=www,mobile) This comment suppresses an error
       * found when Flow v0.98 was deployed. To see the error delete this
       * comment and run Flow. */
      this._traverseSelections(field, nextRecord, item);
      this._path.pop();
    });
    RelayModernRecord.setLinkedRecordIDs(record, storageKey, nextIDs);
  }

  /**
   * Warns if the type of the record does not match the type of the field/payload.
   */
  _validateRecordType(
    record: Record,
    field: NormalizationLinkedField,
    payload: Object,
  ): void {
    const typeName =
      field.kind === 'LinkedField'
        ? field.concreteType || this._getRecordType(payload)
        : this._getRecordType(payload);
    warning(
      isClientID(RelayModernRecord.getDataID(record)) ||
        RelayModernRecord.getType(record) === typeName,
      'RelayResponseNormalizer: Invalid record `%s`. Expected %s to be ' +
        'be consistent, but the record was assigned conflicting types `%s` ' +
        'and `%s`. The GraphQL server likely violated the globally unique ' +
        'id requirement by returning the same id for different objects.',
      RelayModernRecord.getDataID(record),
      TYPENAME_KEY,
      RelayModernRecord.getType(record),
      typeName,
    );
  }
}

// eslint-disable-next-line no-func-assign
normalize = RelayProfiler.instrument(
  'RelayResponseNormalizer.normalize',
  normalize,
);

module.exports = {normalize};
<|endoftext|>


<commit_before>const HOME_PARTIAL = "home"; // home partial filename

function load() {
    let path = getPath();
    if(path === "" || path === undefined) path = HOME_PARTIAL;

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
        document.getElementById("content").innerHTML =
        this.responseText;
        }
    };
    xhttp.open("GET", `partials/${path}.html`, true);
    xhttp.send();
};

function getPath() {
    return window.location.href.split("#/")[1];
};

function loadHandler(event) {
    event.preventDefault();
    load();
}

window.onhashchange = loadHandler(event);

window.onload = loadHandler(event);<commit_msg>Fixed function abstraction<commit_after>const HOME_PARTIAL = "home"; // home partial filename

function load() {
    let path = getPath();
    if(path === "" || path === undefined) path = HOME_PARTIAL;

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = () => {
        if (this.readyState == 4 && this.status == 200) {
        document.getElementById("content").innerHTML =
        this.responseText;
        }
    };
    xhttp.open("GET", `partials/${path}.html`, true);
    xhttp.send();
}

function getPath() {
    return window.location.href.split("#/")[1];
}

function loadHandler(event) {
    event.preventDefault();
    load();
}

window.onhashchange = (event) => loadHandler(event);

window.onload = (event) => loadHandler(event);<|endoftext|>


<commit_before>/* ***************************************************************************
 * EZ.JWAF/EZ.JCWAP: Easy series Production.
 * Including JWAF(Java-based Web Application Framework)
 * and JCWAP(Java-based Customized Web Application Platform).
 * Copyright (C) 2016-2017 the original author or authors.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of MIT License as published by
 * the Free Software Foundation;
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the MIT License for more details.
 *
 * You should have received a copy of the MIT License along
 * with this library; if not, write to the Free Software Foundation.
 * ***************************************************************************/
/**
 * Description: HeaderController.

 * Created by Jimmybly Lee on 2017/6/30.
 * @author Jimmybly Lee
 */
/* Setup Layout Part - Header */
angular.module('WebApp').controller('HeaderController', ['$rootScope', '$scope', '$ajaxCall', function($rootScope, $scope, $ajaxCall) {
    $scope.$on('$includeContentLoaded', function() {
        Layout.initHeader(); // init header
    });
    $scope.logout = function() {
        bootbox.dialog({
            title: "请确认",
            message: "是否确认退出?",
            buttons: {
                main: {
                    label: " 取 消 ",
                    className: "dark icon-ban btn-outline"
                },
                danger: {
                    label: " 退 出！ ",
                    className: "red icon-logout",
                    callback: function() {
                        $ajaxCall.post({
                            data: {
                                "controller": "LoginController",
                                "method": "logout"
                            },
                            success: function() {
                                $rootScope.reloadToken();
                                $rootScope.$state.go("home");
                            }
                        });
                    }
                }
            }
        });
    }
}]);
<commit_msg>退出登录后，应该跳转到首页<commit_after>/* ***************************************************************************
 * EZ.JWAF/EZ.JCWAP: Easy series Production.
 * Including JWAF(Java-based Web Application Framework)
 * and JCWAP(Java-based Customized Web Application Platform).
 * Copyright (C) 2016-2017 the original author or authors.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of MIT License as published by
 * the Free Software Foundation;
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the MIT License for more details.
 *
 * You should have received a copy of the MIT License along
 * with this library; if not, write to the Free Software Foundation.
 * ***************************************************************************/
/**
 * Description: HeaderController.

 * Created by Jimmybly Lee on 2017/6/30.
 * @author Jimmybly Lee
 */
/* Setup Layout Part - Header */
angular.module('WebApp').controller('HeaderController', ['$rootScope', '$scope', '$ajaxCall', function($rootScope, $scope, $ajaxCall) {
    $scope.$on('$includeContentLoaded', function() {
        Layout.initHeader(); // init header
    });
    $scope.logout = function() {
        bootbox.dialog({
            title: "请确认",
            message: "是否确认退出?",
            buttons: {
                main: {
                    label: " 取 消 ",
                    className: "dark icon-ban btn-outline"
                },
                danger: {
                    label: " 退 出！ ",
                    className: "red icon-logout",
                    callback: function() {
                        $ajaxCall.post({
                            data: {
                                "controller": "LoginController",
                                "method": "logout"
                            },
                            success: function() {
                                $rootScope.$state.go("home");
                                $rootScope.reloadToken();
                            }
                        });
                    }
                }
            }
        });
    }
}]);
<|endoftext|>


<commit_before>import express from 'express';
import cors from 'cors';
import fetch from 'isomorphic-fetch';
import Promise from 'bluebird';
import _ from 'lodash';

import canonize from './canonize';

const __DEV__ = true;

const app = express();

app.use(cors());

app.get('/calc', (req, res) => {
  var a, b;

  if (!req.query.a) {
    a = 0;
  } else {
    try {
      a = Number(req.query.a);
    } catch(e) {
      a = 0;
    }
  }

  if (!req.query.b) {
    b = 0;
  } else {
    try {
      b = Number(req.query.b);
    } catch(e) {
      b = 0;
    }
  }

  const sum = a + b;

  res.send(sum.toString());
});

app.get('/canonize', (req, res) => {
  if (!req.query.username) {
    return res.send('Invalid username');
  }

  const username = canonize(req.query.username);

  res.send(username);

  // res.json({
  //   url: req.query.username,
  //   username
  // });
});

const baseUrl = 'http://pokeapi.co/api/v2';
const pokemonFields = ['id', 'name', 'height', 'weight'];

async function getPokemons(url, i = 0) {
  console.log('getPokemons', url, i);

  const response = await fetch(url);
  const page = await response.json();
  const pokemons = page.results;

  if (__DEV__ && i > 1) {
    return pokemons;
  }

  if (page.next) {
    const pokemons2 = await getPokemons(page.next, i + 1);
    return [
      ...pokemons,
      ...pokemons2
    ]
  }
  return pokemons;
}

async function getPokemon(url) {
  console.log('getPokemon', url);

  const response = await fetch(url);
  const pokemon = await response.json();

  return pokemon;
}

app.get('/', async (req, res) => {
  try {
    const pokemonsUrl = `${baseUrl}/pokemon`;
    const pokemonsInfo = await getPokemons(pokemonsUrl);
    const pokemonsPromises = pokemonsInfo.map(info => {
      return getPokemon(info.url);
    });

    const pokemonsFull = await Promise.all(pokemonsPromises);
    const pokemons = pokemonsFull.map(pokemon => {
      return _.pick(pokemon, pokemonFields);
    })

    const sortedPokemons = _.sortBy(pokemons, (pokemon) => {
      return -pokemon.weight;
    });
    return res.json(sortedPokemons);
  } catch(e) {
    console.log(e);
    res.json({ e });
  }
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
});
<commit_msg>Task 2B<commit_after>import express from 'express';
import cors from 'cors';
import fetch from 'isomorphic-fetch';
import Promise from 'bluebird';
import _ from 'lodash';

import canonize from './canonize';

const __DEV__ = true;

const app = express();

app.use(cors());

app.get('/creds', (req, res) => {

  var result = 'Invalid fullname';

  if (!req.query.fullname) {
    return res.send(result);
  }

  const fullname = req.query.fullname;

  // const re = /^([a-zа-яё\s]+)$/i;
  const re = /[0-9-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]/;
  const Reg = new RegExp(re);

  if (Reg.test(fullname)) {
    return res.send(result);
  }

  const arr = fullname.split(' ');

  switch(arr.length) {
    case 3:
      result = arr[2] + ' ' + arr[0].charAt(0) + '.' + ' ' + arr[1].charAt(0) + '.';
      return res.send(result);
      break;
    case 2:
      result = arr[1] + ' ' + arr[0].charAt(0) + '.';
      return res.send(result);
      break;
    case 1:
      result = arr[0];
      return res.send(result);
      break;
    default:
      return res.send(result);
  }
});

app.get('/calc', (req, res) => {
  var a, b;

  if (!req.query.a) {
    a = 0;
  } else {
    try {
      a = Number(req.query.a);
    } catch(e) {
      a = 0;
    }
  }

  if (!req.query.b) {
    b = 0;
  } else {
    try {
      b = Number(req.query.b);
    } catch(e) {
      b = 0;
    }
  }

  const sum = a + b;

  res.send(sum.toString());
});

app.get('/canonize', (req, res) => {
  if (!req.query.username) {
    return res.send('Invalid username');
  }

  const username = canonize(req.query.username);

  res.send(username);

  // res.json({
  //   url: req.query.username,
  //   username
  // });
});

const baseUrl = 'http://pokeapi.co/api/v2';
const pokemonFields = ['id', 'name', 'height', 'weight'];

async function getPokemons(url, i = 0) {
  console.log('getPokemons', url, i);

  const response = await fetch(url);
  const page = await response.json();
  const pokemons = page.results;

  if (__DEV__ && i > 1) {
    return pokemons;
  }

  if (page.next) {
    const pokemons2 = await getPokemons(page.next, i + 1);
    return [
      ...pokemons,
      ...pokemons2
    ]
  }
  return pokemons;
}

async function getPokemon(url) {
  console.log('getPokemon', url);

  const response = await fetch(url);
  const pokemon = await response.json();

  return pokemon;
}

app.get('/', async (req, res) => {
  try {
    const pokemonsUrl = `${baseUrl}/pokemon`;
    const pokemonsInfo = await getPokemons(pokemonsUrl);
    const pokemonsPromises = pokemonsInfo.map(info => {
      return getPokemon(info.url);
    });

    const pokemonsFull = await Promise.all(pokemonsPromises);
    const pokemons = pokemonsFull.map(pokemon => {
      return _.pick(pokemon, pokemonFields);
    })

    const sortedPokemons = _.sortBy(pokemons, (pokemon) => {
      return -pokemon.weight;
    });
    return res.json(sortedPokemons);
  } catch(e) {
    console.log(e);
    res.json({ e });
  }
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
});
<|endoftext|>


<commit_before>Joshfire.define(['joshfire/class', 'joshfire/tree.ui', 'joshfire/uielements/list', 'joshfire/uielements/panel', 'joshfire/uielements/panel.manager', 'joshfire/uielements/button', 'src/ui-components'], function(Class, UITree, List, Panel, PanelManager, Button, UI) {

  return Class(UITree, {

    buildTree: function() {

      var app = this.app;

      return [
        {
          id: 'header',
          type: Panel,
          htmlClass: 'header',
          children: [
            {
              id: 'prev',
              type: Button,
              label: 'Prev',
              autoShow: false
            },
            UI.uiHeader
          ]
        },
        {
          id: 'content',
          type: PanelManager,
          uiMaster: '/footer',
          children: [
            {
              id: 'itemList',
              //scroller: false, // do not use iScroll it's crappy crap (and doesn't work with a grid made of floats)
              type: List,
              htmlClass: 'abs100',
              loadingTemplate: '

',
              itemTemplate: "<li id='<%=itemHtmlId%>' " +
                            "data-josh-ui-path='<%= path %>' data-josh-grid-id='<%= item.id %>'" +
                            "class='josh-List joshover item-<%= item.source %> mainitemlist " +
                            // grid view
                            "<% if (item.itemType === 'ImageObject') { %>" +
                              "grid" +
                            "<% } else { %>" +
                            // list view
                              "list" +
                            "<% } %>" +
                            "' >" +
                            "<%= itemInner %>" +
                            "
",
              itemInnerTemplate:
                '<% if (item.itemType === "VideoObject") { %>' +
                  '
<%= item.name %>
' +
                  '
<% if (item.description && item.description.length > 70) { %><%= item.description.substring(0, 70) %>…<% } else { %><%= item.description %><% } %>
' +
                  '<% if (item.thumbnail && item.thumbnail[0]) { %>
<img src="<%= item.thumbnail[0].contentURL %>">
<% } %>' +
                  '' +
                '<% } else if ((item.itemType === "ImageObject") && item.thumbnail && item.thumbnail[0]) { %>' +
                  "<div class='thumbnail' style='background-image:url(\"<%=item.thumbnail[0].contentURL%>\")'>
" +
                '<% } else if (item.itemType === "Article/Status") { %>' +
                  '
<%= item.name %>
' +
                '<% } else { %>' +
                  '<%= item.name %>' +
                '<% } %>'
            },
            {
              id: 'detail',
              type: Panel,
              loadingTemplate: '

',
              autoShow: false,
              children: [
                {
                  // Article
                  id: 'article',
                  type: Panel,
                  uiDataMaster: '/content/itemList',
                  forceDataPathRefresh: true,
                  loadingTemplate: '

',
                  innerTemplate:
                    '

<%= data.name %>
' +
                    '<% if (data.author && data.author[0]) { %>
By <%= data.author[0].name %>
<% } %>' +
                    '
' +
                    '<% if (data.articleBody) { %>
<%= data.articleBody %>
<% } %>',
                  onData: function(ui) {
                    var thisEl = app.ui.element('/content/detail/article').htmlEl;
                    if (ui.data.itemType === 'VideoObject' || ui.data.itemType === 'ImageObject') {
                      $(thisEl).hide();
                    }
                    else {
                      $(thisEl).show();
                    }
                  }
                },
                {
                  // Flickr
                  id: 'image',
                  type: Panel,
                  uiDataMaster: '/content/itemList',
                  forceDataPathRefresh: true,
                  loadingTemplate: '

',
                  innerTemplate: '<img src="<%= data.photo %>" />',
                  onData: function(ui) {
                    var thisEl = app.ui.element('/content/detail/image').htmlEl;
                    if (ui.data.source =='flickr') {
                      $(thisEl).show();
                    } else {
                      $(thisEl).hide();
                    }
                  }
                },
                {
                  // Video
                  id: 'video',
                  type: Panel,
                  forceDataPathRefresh: true,
                  loadingTemplate: '

',
                  onData: function(ui) {
                    var thisEl = app.ui.element('/content/detail/video').htmlEl,
                        player = app.ui.element('/content/detail/video/player.youtube');

                    if (ui.data.itemType === 'VideoObject') {
                      player.playWithStaticUrl({
                        url: ui.data.contentURL.replace('http://www.youtube.com/watch?v=', ''),
                        width: '100%'
                      });
                      $(thisEl).show();
                    }
                    else {
                      $(thisEl).hide();
                    }
                  },
                  children: [
                    {
                      id: 'title',
                      type: Panel,
                      uiDataMaster: '/content/itemList',
                      innerTemplate:
                        '

<%= data.name %>
' +
                        '<% if (data.author && data.autor[0]) { %>
By <%= data.author[0].name %>
<% } %>' +
                        '
'
                    },
                    {
                      id: 'player.youtube',
                      type: 'video.youtube',
                      autoShow: true,
                      controls: true,
                      noAutoPlay: false
                    }
                  ]
                }
              ]
            }
          ]
        },
        {
          id: 'footer',
          type: List,
          dataPath: '/datasourcelist/',
          itemInnerTemplate: '<div class="picto item-<%= item.config.col %>">

<%= item.name %>
',
          onData: function() {} // trigger data, WTF?
        }
      ];
    }

  });

});<commit_msg>Phone datasources adapted to new schema<commit_after>Joshfire.define(['joshfire/class', 'joshfire/tree.ui', 'joshfire/uielements/list', 'joshfire/uielements/panel', 'joshfire/uielements/panel.manager', 'joshfire/uielements/button', 'src/ui-components'], function(Class, UITree, List, Panel, PanelManager, Button, UI) {

  return Class(UITree, {

    buildTree: function() {

      var app = this.app;

      return [
        {
          id: 'header',
          type: Panel,
          htmlClass: 'header',
          children: [
            {
              id: 'prev',
              type: Button,
              label: 'Prev',
              autoShow: false
            },
            UI.uiHeader
          ]
        },
        {
          id: 'content',
          type: PanelManager,
          uiMaster: '/footer',
          children: [
            {
              id: 'itemList',
              //scroller: false, // do not use iScroll it's crappy crap (and doesn't work with a grid made of floats)
              type: List,
              htmlClass: 'abs100',
              loadingTemplate: '

',
              itemTemplate: "<li id='<%=itemHtmlId%>' " +
                            "data-josh-ui-path='<%= path %>' data-josh-grid-id='<%= item.id %>'" +
                            "class='josh-List joshover item-<%= item.itemType %> mainitemlist " +
                            // grid view
                            "<% if (item.itemType === 'ImageObject') { %>" +
                              "grid" +
                            "<% } else { %>" +
                            // list view
                              "list" +
                            "<% } %>" +
                            "' >" +
                            "<%= itemInner %>" +
                            "
",
              itemInnerTemplate:
                '<% if (item.itemType === "VideoObject") { %>' +
                  '
<%= item.name %>
' +
                  '
<% if (item.description && item.description.length > 70) { %><%= item.description.substring(0, 70) %>…<% } else { %><%= item.description %><% } %>
' +
                  '<% if (item.thumbnail && item.thumbnail[0]) { %>
<img src="<%= item.thumbnail[0].contentURL %>">
<% } %>' +
                  '' +
                '<% } else if ((item.itemType === "ImageObject") && item.thumbnail && item.thumbnail[0]) { %>' +
                  "<div class='thumbnail' style='background-image:url(\"<%=item.thumbnail[0].contentURL%>\")'>
" +
                '<% } else if (item.itemType === "Article/Status") { %>' +
                  '
<%= item.name %>
' +
                '<% } else { %>' +
                  '<%= item.name %>' +
                '<% } %>'
            },
            {
              id: 'detail',
              type: Panel,
              loadingTemplate: '

',
              autoShow: false,
              children: [
                {
                  // Article
                  id: 'article',
                  type: Panel,
                  uiDataMaster: '/content/itemList',
                  forceDataPathRefresh: true,
                  loadingTemplate: '

',
                  innerTemplate:
                    '

<%= data.name %>
' +
                    '<% if (data.author && data.author[0]) { %>
By <%= data.author[0].name %>
<% } %>' +
                    '
' +
                    '<% if (data.articleBody) { %>
<%= data.articleBody %>
<% } %>',
                  onData: function(ui) {
                    var thisEl = app.ui.element('/content/detail/article').htmlEl;
                    if (ui.data.itemType === 'VideoObject' || ui.data.itemType === 'ImageObject') {
                      $(thisEl).hide();
                    }
                    else {
                      $(thisEl).show();
                    }
                  }
                },
                {
                  // Flickr
                  id: 'image',
                  type: Panel,
                  uiDataMaster: '/content/itemList',
                  forceDataPathRefresh: true,
                  loadingTemplate: '

',
                  innerTemplate: '<img src="<%= data.contentURL %>" alt="" />',
                  onData: function(ui) {
                    var thisEl = app.ui.element('/content/detail/image').htmlEl;
                    if (ui.data.itemType === 'ImageObject') {
                      $(thisEl).show();
                    } else {
                      $(thisEl).hide();
                    }
                  }
                },
                {
                  // Video
                  id: 'video',
                  type: Panel,
                  forceDataPathRefresh: true,
                  loadingTemplate: '

',
                  onData: function(ui) {
                    var thisEl = app.ui.element('/content/detail/video').htmlEl,
                        player = app.ui.element('/content/detail/video/player.youtube');

                    if ((ui.data.itemType === 'VideoObject') && ui.data.publisher && (ui.data.publisher.name === 'Youtube')) {
                      player.playWithStaticUrl({
                        url: ui.data.url.replace('http://www.youtube.com/watch?v=', ''),
                        width: '100%'
                      });
                      $(thisEl).show();
                    }
                    else {
                      $(thisEl).hide();
                    }
                  },
                  children: [
                    {
                      id: 'title',
                      type: Panel,
                      uiDataMaster: '/content/itemList',
                      innerTemplate:
                        '

<%= data.name %>
' +
                        '<% if (data.author && data.autor[0]) { %>
By <%= data.author[0].name %>
<% } %>' +
                        '
'
                    },
                    {
                      id: 'player.youtube',
                      type: 'video.youtube',
                      autoShow: true,
                      controls: true,
                      noAutoPlay: false
                    }
                  ]
                }
              ]
            }
          ]
        },
        {
          id: 'footer',
          type: List,
          dataPath: '/datasourcelist/',
          itemInnerTemplate: '<div class="picto item-<%= item.config.col %>">

<%= item.name %>
',
          onData: function() {} // trigger data, WTF?
        }
      ];
    }

  });

});<|endoftext|>


<commit_before>// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

import { action, computed, observable } from 'mobx'

export default class SuiteState {
  constructor(UiState, suite) {
    this.filteredTests = computed(() =>
      suite.tests.filter(UiState.filterFunction)
    )
  }
}
<commit_msg>fixed lint<commit_after>// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

import { computed } from 'mobx'

export default class SuiteState {
  constructor(UiState, suite) {
    this.filteredTests = computed(() =>
      suite.tests.filter(UiState.filterFunction)
    )
  }
}
<|endoftext|>


<commit_before>/* eslint-disable react/prefer-stateless-function */
/* eslint-disable react/prefer-es6-class */
import React, { Component } from 'react';
import createReactClass from 'create-react-class';
import { Picker } from 'react-native';
import { connectStyle } from 'native-base-shoutem-theme';

import mapPropsToStyleNames from '../utils/mapPropsToStyleNames';

export default class PickerNB extends Component {
  render() {
    return (
      <Picker ref={c => (this._root = c)} {...this.props}>
        {this.props.children}
      </Picker>
    );
  }
}

// eslint-disable-next-line react/no-multi-comp
PickerNB.Item = createReactClass({
  render() {
    return <Picker.Item {...this.props} />;
  }
});

PickerNB.propTypes = {
  ...Picker.propTypes
};

const StyledPickerNB = connectStyle(
  'NativeBase.PickerNB',
  {},
  mapPropsToStyleNames
)(PickerNB);

export { StyledPickerNB as PickerNB };
<commit_msg>picker import<commit_after>/* eslint-disable react/prefer-stateless-function */
/* eslint-disable react/prefer-es6-class */
import React, { Component } from 'react';
import createReactClass from 'create-react-class';
import Picker from '@react-native-community/picker';
import { connectStyle } from 'native-base-shoutem-theme';

import mapPropsToStyleNames from '../utils/mapPropsToStyleNames';

export default class PickerNB extends Component {
  render() {
    return (
      <Picker ref={c => (this._root = c)} {...this.props}>
        {this.props.children}
      </Picker>
    );
  }
}

// eslint-disable-next-line react/no-multi-comp
PickerNB.Item = createReactClass({
  render() {
    return <Picker.Item {...this.props} />;
  }
});

PickerNB.propTypes = {
  ...Picker.propTypes
};

const StyledPickerNB = connectStyle(
  'NativeBase.PickerNB',
  {},
  mapPropsToStyleNames
)(PickerNB);

export { StyledPickerNB as PickerNB };
<|endoftext|>


<commit_before>import { get, set } from '@ember/object';
import Component from '@ember/component';
import { inject as service } from '@ember/service';
import { reads } from '@ember/object/computed';

const SYSTEM_SERVICES = [
  {label: 'Etcd', value: 'etcd'},
  {label: 'Controller Manager', value: 'controller-manager'},
  {label: 'Scheduler', value: 'scheduler'},
];

// **NOTE** backend needs capitalized value
const RESOURCE_KINDS = [
  {label: 'Pod', value: 'Pod'},
  {label: 'Node', value: 'Node'},
  {label: 'Deployment', value: 'Deployment'},
  {label: 'Statefulset', value: 'Statefulset'},
  {label: 'Daemonset', value: 'Daemonset'},
];
export default Component.extend({
  globalStore: service(),
  scope: service(),
  clusterId: reads('scope.currentCluster.id'),

  init(...args) {
    this._super(...args);
    this.set('systemServices', SYSTEM_SERVICES);
    this.set('resourceKinds', RESOURCE_KINDS);
  },

  nodes: function() {
    const clusterId = get(this, 'clusterId');
    return get(this, 'globalStore').all('node').filterBy('clusterId', clusterId);
  }.property('clusterId'),

  isEventTarget: function() {
    const t = get(this, 'model._targetType');
    return t === 'warningEvent' || t ===  'normalEvent';
  }.property('model._targetType'),

  setEventType(t) {
    if (t === 'warningEvent') {
      set(this, 'model.targetEvent.eventType', 'Warning');
    }
    if (t === 'normalEvent') {
      set(this, 'model.targetEvent.eventType', 'Normal');
    }
  },
  targetTypeChanged: function() {
    const t = get(this, 'model._targetType');
    this.setEventType(t);
  }.observes('model._targetType'),

  actions: {
    // todo, don't know that this is needed
    noop() {
    },
  }
});
<commit_msg>Update alert<commit_after>import { get, set } from '@ember/object';
import Component from '@ember/component';
import { inject as service } from '@ember/service';
import { reads } from '@ember/object/computed';

export default Component.extend({
  globalStore: service(),
  scope: service(),
  clusterId: reads('scope.currentCluster.id'),

  init() {
    this._super(...arguments);
    const resourceKinds = get(this, 'globalStore')
          .getById('schema', 'targetevent')
          .optionsFor('resourceKind').sort().map(value => ({
            label: value,
            value,
          }));
    const systemServices = get(this, 'globalStore')
          .getById('schema', 'targetsystemservice')
          .optionsFor('condition').sort().map(value => ({
            label: value,
            value,
          }));
    this.set('resourceKinds', resourceKinds);
    this.set('systemServices', systemServices);
  },

  nodes: function() {
    const clusterId = get(this, 'clusterId');
    return get(this, 'globalStore').all('node').filterBy('clusterId', clusterId);
  }.property('clusterId'),

  isEventTarget: function() {
    const t = get(this, 'model._targetType');
    return t === 'warningEvent' || t ===  'normalEvent';
  }.property('model._targetType'),

  setEventType(t) {
    if (t === 'warningEvent') {
      set(this, 'model.targetEvent.eventType', 'Warning');
    }
    if (t === 'normalEvent') {
      set(this, 'model.targetEvent.eventType', 'Normal');
    }
  },
  targetTypeChanged: function() {
    const t = get(this, 'model._targetType');
    this.setEventType(t);
  }.observes('model._targetType'),

  actions: {
    // todo, don't know that this is needed
    noop() {
    },
  }
});
<|endoftext|>


<commit_before>Ext.ns("org.systemsbiology.addama.js");

org.systemsbiology.addama.js.Viewport = Ext.extend(Object, {
    constructor: function(config) {
        Ext.apply(this, config);

        org.systemsbiology.addama.js.Viewport.superclass.constructor.call(this);

        this.drawViewport();
    },

    drawViewport: function() {
        var addamaBanner = Ext.DomHelper.append(Ext.getBody(), '

', true);
        var appengineLogo = Ext.DomHelper.append(Ext.getBody(), '

', true);
        var link1 = Ext.DomHelper.append(Ext.getBody(), '
API Keys
', true);
        var link2 = Ext.DomHelper.append(Ext.getBody(), '
Addama Open Source Project
', true);
        var link3 = Ext.DomHelper.append(Ext.getBody(), '
Institute for Systems Biology
', true);
        var link4 = Ext.DomHelper.append(Ext.getBody(), '
Shmulevich Lab
', true);
        var link5 = Ext.DomHelper.append(Ext.getBody(), '
Code for Systems Biology
', true);
        var link6 = Ext.DomHelper.append(Ext.getBody(), '
PMID 19265554
', true);

        var headerPanel = new Ext.Panel({
            region: "north",
            border: false,
            frame: false,
            layout: "border",
            height: 99,
            defaults: { border: false, frame: false },
            items:[
                { contentEl: this.topbarEl, region: "north", height: 30 },
                { contentEl: addamaBanner.id, region: "center" },
                { contentEl: appengineLogo.id, region: "east", width: 130 }
            ]
        });

        if (this.tabs && this.tabs.length) {
            var firstTab = this.tabs[0];
            if (firstTab && !firstTab.title) {
                firstTab.title = "Main";
            }
            Ext.each(this.tabs, function(tab) {
                if (tab && !tab.title) {
                    tab.title = "...";
                }
            });
            if (this.activateAjaxMonitor) {
                var ajaxMonitor = new org.systemsbiology.addama.js.AjaxMonitor();
                this.tabs.push(ajaxMonitor.gridPanel);
            }
        }

        var tabPanel = new Ext.TabPanel({
            region: "center",
            items: this.tabs,
            activeTab: 0,
            border: true,
            margins: "5 5 5 5",
            padding: "5 5 5 5"
        });

        var footerPanel = new Ext.Panel({
            region:"south",
            height: 33,
            layout: "hbox",
            border: false,
            frame: true,
            padding: "1 1 1 1",
            margins: "1 1 1 1",
            layoutConfig: { pack: "center", align: "middle", defaultMargins: "0 10 0 0" },
            items:[ link1.dom, link2.dom, link3.dom, link4.dom, link5.dom, link6.dom ]
        });

        new Ext.Viewport({
            layout:'border',
            items:[ headerPanel, tabPanel, footerPanel ]
        });
    }
});

org.systemsbiology.addama.js.AjaxMonitor = Ext.extend(Object, {
    SEQUENCE_ID: 1,
    GRID_DATA: [],

    constructor: function(config) {
        Ext.apply(this, config);

        org.systemsbiology.addama.js.AjaxMonitor.superclass.constructor.call(this);

        this.createGrid();
        Ext.Ajax.on('requestcomplete', this.addResponseToGrid, this);
    },

    createGrid: function() {
        this.store = new Ext.data.JsonStore({
            storeId: "store-ajax-monitor",
            root: "responses",
            idProperty: "id",
            sortInfo: {field: "id", direction: "DESC"},
            fields: [
                { name: "id", type: "int"},
                { name: "method" },
                { name: "uri" },
                { name: "statusCode" },
                { name: "statusText" },
                { name: "responseText" },
                { name: "isJson", type: "boolean" }
            ]
        });

        this.gridPanel = new Ext.grid.GridPanel({
            region: "center",
            store: this.store,
            columns: [
                { header: "ID", width: 50, dataIndex: 'id', type: "int", sortable: true, hidden: true },
                { header: "Method", width: 75, dataIndex: 'method' },
                { header: "URI", width: 200, dataIndex: 'uri', sortable: true },
                { header: "Status Code", width: 75, dataIndex: 'statusCode', sortable: true },
                { header: "Status Text", width: 100, dataIndex: 'statusText' },
                { header: "Response Text", width: 300, dataIndex: 'responseText', hidden: true }
            ],
            stripeRows: true,
            columnLines: true,
            frame:true,
            title: "Requests",
            collapsible: false,
            animCollapse: false,
            iconCls: 'icon-grid'
        });
        this.gridPanel.on("rowclick", this.showResponseContent, this);
    },

    addResponseToGrid: function(connection, response, options) {
        var contentType = response.getResponseHeader("Content-Type");
        var isJson = (contentType != undefined && contentType.indexOf("ation/json") > 0);

        var newData = {
            id:this.incrementedId(),
            method: options.method,
            uri: options.url,
            statusCode: response.status,
            statusText: response.statusText,
            responseText: response.responseText,
            isJson: isJson
        };
        this.GRID_DATA.push(newData);
        this.store.loadData({responses:this.GRID_DATA});
    },

    showResponseContent: function(g, rowIndex, e) {
        var data = this.store.getAt(rowIndex).data;
        var responseText = data.responseText;
        if (data.isJson) {
            var json = Ext.util.JSON.decode(responseText);
            var stringify = JSON.stringify(json, null, "\u00a0\u00a0\u00a0\u00a0");
            responseText = Ext.util.Format.nl2br(stringify);
        }

        new Ext.Window({
            width:800,
            height:400,
            autoScroll: true,
            modal: true,
            title: "Response Content",
            html: responseText
        }).show();
    },

    incrementedId: function() {
        return this.SEQUENCE_ID++;
    }

});

org.systemsbiology.addama.js.AppsPanel = Ext.extend(Object, {
    constructor: function(config) {
        Ext.apply(this, config);

        org.systemsbiology.addama.js.AppsPanel.superclass.constructor.call(this);

        Ext.Ajax.request({
            url: "/addama/apps",
            method: "get",
            success: function(o) {
                var json = Ext.util.JSON.decode(o.responseText);
                if (json && json.items) {
                    var html = "";
                    Ext.each(json.items, function(item) {
                        html += "
" + item.label + "
";
                    });
                    new Ext.Panel({
                        contentEl: this.contentEl,
                        html: "
" + html + "
"
                    });
                }
            },
            scope: this
        });

    }
});

org.systemsbiology.addama.js.ServicesPanel = Ext.extend(Object, {
    constructor: function(config) {
        Ext.apply(this, config);

        org.systemsbiology.addama.js.ServicesPanel.superclass.constructor.call(this);

        Ext.Ajax.request({
            url: "/addama/services",
            method: "get",
            success: function(o) {
                var json = Ext.util.JSON.decode(o.responseText);
                if (json && json.items) {
                    var html = "";
                    Ext.each(json.items, function(item) {
                        html += "
" + item.label + "
";
                    });
                    new Ext.Panel({
                        contentEl: this.contentEl,
                        html: "
" + html + "
"
                    });
                }
            },
            scope: this
        });

    }
});
<commit_msg>changed width of url field<commit_after>Ext.ns("org.systemsbiology.addama.js");

org.systemsbiology.addama.js.Viewport = Ext.extend(Object, {
    constructor: function(config) {
        Ext.apply(this, config);

        org.systemsbiology.addama.js.Viewport.superclass.constructor.call(this);

        this.drawViewport();
    },

    drawViewport: function() {
        var addamaBanner = Ext.DomHelper.append(Ext.getBody(), '

', true);
        var appengineLogo = Ext.DomHelper.append(Ext.getBody(), '

', true);
        var link1 = Ext.DomHelper.append(Ext.getBody(), '
API Keys
', true);
        var link2 = Ext.DomHelper.append(Ext.getBody(), '
Addama Open Source Project
', true);
        var link3 = Ext.DomHelper.append(Ext.getBody(), '
Institute for Systems Biology
', true);
        var link4 = Ext.DomHelper.append(Ext.getBody(), '
Shmulevich Lab
', true);
        var link5 = Ext.DomHelper.append(Ext.getBody(), '
Code for Systems Biology
', true);
        var link6 = Ext.DomHelper.append(Ext.getBody(), '
PMID 19265554
', true);

        var headerPanel = new Ext.Panel({
            region: "north",
            border: false,
            frame: false,
            layout: "border",
            height: 99,
            defaults: { border: false, frame: false },
            items:[
                { contentEl: this.topbarEl, region: "north", height: 30 },
                { contentEl: addamaBanner.id, region: "center" },
                { contentEl: appengineLogo.id, region: "east", width: 130 }
            ]
        });

        if (this.tabs && this.tabs.length) {
            var firstTab = this.tabs[0];
            if (firstTab && !firstTab.title) {
                firstTab.title = "Main";
            }
            Ext.each(this.tabs, function(tab) {
                if (tab && !tab.title) {
                    tab.title = "...";
                }
            });
            if (this.activateAjaxMonitor) {
                var ajaxMonitor = new org.systemsbiology.addama.js.AjaxMonitor();
                this.tabs.push(ajaxMonitor.gridPanel);
            }
        }

        var tabPanel = new Ext.TabPanel({
            region: "center",
            items: this.tabs,
            activeTab: 0,
            border: true,
            margins: "5 5 5 5",
            padding: "5 5 5 5"
        });

        var footerPanel = new Ext.Panel({
            region:"south",
            height: 33,
            layout: "hbox",
            border: false,
            frame: true,
            padding: "1 1 1 1",
            margins: "1 1 1 1",
            layoutConfig: { pack: "center", align: "middle", defaultMargins: "0 10 0 0" },
            items:[ link1.dom, link2.dom, link3.dom, link4.dom, link5.dom, link6.dom ]
        });

        new Ext.Viewport({
            layout:'border',
            items:[ headerPanel, tabPanel, footerPanel ]
        });
    }
});

org.systemsbiology.addama.js.AjaxMonitor = Ext.extend(Object, {
    SEQUENCE_ID: 1,
    GRID_DATA: [],

    constructor: function(config) {
        Ext.apply(this, config);

        org.systemsbiology.addama.js.AjaxMonitor.superclass.constructor.call(this);

        this.createGrid();
        Ext.Ajax.on('requestcomplete', this.addResponseToGrid, this);
    },

    createGrid: function() {
        this.store = new Ext.data.JsonStore({
            storeId: "store-ajax-monitor",
            root: "responses",
            idProperty: "id",
            sortInfo: {field: "id", direction: "DESC"},
            fields: [
                { name: "id", type: "int"},
                { name: "method" },
                { name: "uri" },
                { name: "statusCode" },
                { name: "statusText" },
                { name: "responseText" },
                { name: "isJson", type: "boolean" }
            ]
        });

        this.gridPanel = new Ext.grid.GridPanel({
            region: "center",
            store: this.store,
            columns: [
                { header: "ID", width: 50, dataIndex: 'id', type: "int", sortable: true, hidden: true },
                { header: "Method", width: 75, dataIndex: 'method' },
                { header: "URI", width: 400, dataIndex: 'uri', sortable: true },
                { header: "Status Code", width: 75, dataIndex: 'statusCode', sortable: true },
                { header: "Status Text", width: 100, dataIndex: 'statusText' },
                { header: "Response Text", width: 300, dataIndex: 'responseText', hidden: true }
            ],
            stripeRows: true,
            columnLines: true,
            frame:true,
            title: "Requests",
            collapsible: false,
            animCollapse: false,
            iconCls: 'icon-grid'
        });
        this.gridPanel.on("rowclick", this.showResponseContent, this);
    },

    addResponseToGrid: function(connection, response, options) {
        var contentType = response.getResponseHeader("Content-Type");
        var isJson = (contentType != undefined && contentType.indexOf("ation/json") > 0);

        var newData = {
            id:this.incrementedId(),
            method: options.method,
            uri: options.url,
            statusCode: response.status,
            statusText: response.statusText,
            responseText: response.responseText,
            isJson: isJson
        };
        this.GRID_DATA.push(newData);
        this.store.loadData({responses:this.GRID_DATA});
    },

    showResponseContent: function(g, rowIndex, e) {
        var data = this.store.getAt(rowIndex).data;
        var responseText = data.responseText;
        if (data.isJson) {
            var json = Ext.util.JSON.decode(responseText);
            var stringify = JSON.stringify(json, null, "\u00a0\u00a0\u00a0\u00a0");
            responseText = Ext.util.Format.nl2br(stringify);
        }

        new Ext.Window({
            width:800,
            height:400,
            autoScroll: true,
            modal: true,
            title: "Response Content",
            html: responseText
        }).show();
    },

    incrementedId: function() {
        return this.SEQUENCE_ID++;
    }

});

org.systemsbiology.addama.js.AppsPanel = Ext.extend(Object, {
    constructor: function(config) {
        Ext.apply(this, config);

        org.systemsbiology.addama.js.AppsPanel.superclass.constructor.call(this);

        Ext.Ajax.request({
            url: "/addama/apps",
            method: "get",
            success: function(o) {
                var json = Ext.util.JSON.decode(o.responseText);
                if (json && json.items) {
                    var html = "";
                    Ext.each(json.items, function(item) {
                        html += "
" + item.label + "
";
                    });
                    new Ext.Panel({
                        contentEl: this.contentEl,
                        html: "
" + html + "
"
                    });
                }
            },
            scope: this
        });

    }
});

org.systemsbiology.addama.js.ServicesPanel = Ext.extend(Object, {
    constructor: function(config) {
        Ext.apply(this, config);

        org.systemsbiology.addama.js.ServicesPanel.superclass.constructor.call(this);

        Ext.Ajax.request({
            url: "/addama/services",
            method: "get",
            success: function(o) {
                var json = Ext.util.JSON.decode(o.responseText);
                if (json && json.items) {
                    var html = "";
                    Ext.each(json.items, function(item) {
                        html += "
" + item.label + "
";
                    });
                    new Ext.Panel({
                        contentEl: this.contentEl,
                        html: "
" + html + "
"
                    });
                }
            },
            scope: this
        });

    }
});
<|endoftext|>