<commit_before>var socketIo = require('socket.io');
var defaultCommands = require('./default-commands/socket.io');

function deepClone(base) {
  if (!base || typeof base != 'object')
    return base;

  var cloned = Object.create(null);
  Object.keys(base).forEach(function(key) {
    cloned[key] = deepClone(base[key]);
  });
  return cloned;
}

function sanitizeBackendMessage(envelope) {
  return {
    statusCode: envelope.statusCode,
    body: deepClone(envelope.body)
  };
}
exports.sanitizeBackendMessage = sanitizeBackendMessage;

exports.register = function(application, server, params) {
  params = params || {};
  var connection = params.connection;
  if (!connection)
    throw new Error('Connection to the backend is required!');

  if (!server)
    throw new Error('A server instance is required!');

  function createRequestHandler(command, socket, requestBuilder) {
    return (function(data) {
      if (requestBuilder)
        data = requestBuilder(data);
      connection.emitMessage(command, data);
    });
  }

  function createBackendMessageHandler(socket) {
    return (function(envelope) {
      var event = envelope.type;

      var data;
      var resultTypeMatch = envelope.type.match(/^(.+)\.test$/);
      if (resultTypeMatch && unifiedCommandSet[resultTypeMatch[1]]) {
        var command = unifiedCommandSet[resultTypeMatch[1]];
        if (command.responseBuilder)
          data = command.responseBuilder(envelope);
        if (command.responseEvent)
          event = command.responseEvent;
      }

      if (!data)
        data = sanitizeBackendMessage(envelope);

      socket.emit(event, data);
    });
  }

  function createErrorHandler(socket) {
    return (function(error) {
      socket.emit('error', error);
    });
  }

  var commandSets = [defaultCommands].concat(params.plugins || []);
  var unifiedCommandSet = {};
  commandSets.forEach(function(commandSet) {
    if (typeof commandSet == 'string')
      commandSet = require(commandSet);

    Object.keys(commandSet).forEach(function(command) {
      var definition = commandSet[command];
      if (!definition || definition.method) // ignore REST command
        return;
      unifiedCommandSet[command] = definition;
    });
  });

  var registeredCommands = [];
  Object.keys(unifiedCommandSet).forEach(function(command) {
    var definition = unifiedCommandSet[command];
    if (!definition || typeof definition != 'object') // ignore not a command definition
      return;
    registeredCommands.push({ command:    command,
                              definition: definition });
  });

  var io = socketIo.listen(server);
  io.sockets.on('connection', function(socket) {
    application.emit('connection', socket);

    var messageHandlers = [];
    registeredCommands.forEach(function(command) {
      socket.on(command.command,
                createRequestHandler(command.command,
                                     socket,
                                     command.definition.requestBuilder));
    });

    var backendMessageHandler = createBackendMessageHandler(socket);
    connection.on('message', backendMessageHandler);

    var errorHandler = createErrorHandler(socket);
    connection.on('error', errorHandler);

    socket.on('disconnect', function() {
      connection.removeListener('message', backendMessageHandler);
      connection.removeListener('error', errorHandler);
      socket.removeAllListeners();
    });
  });

  return registeredCommands;
}
<commit_msg>Handle messages with ".result" suffix correctly<commit_after>var socketIo = require('socket.io');
var defaultCommands = require('./default-commands/socket.io');

function deepClone(base) {
  if (!base || typeof base != 'object')
    return base;

  var cloned = Object.create(null);
  Object.keys(base).forEach(function(key) {
    cloned[key] = deepClone(base[key]);
  });
  return cloned;
}

function sanitizeBackendMessage(envelope) {
  return {
    statusCode: envelope.statusCode,
    body: deepClone(envelope.body)
  };
}
exports.sanitizeBackendMessage = sanitizeBackendMessage;

exports.register = function(application, server, params) {
  params = params || {};
  var connection = params.connection;
  if (!connection)
    throw new Error('Connection to the backend is required!');

  if (!server)
    throw new Error('A server instance is required!');

  function createRequestHandler(command, socket, requestBuilder) {
    return (function(data) {
      if (requestBuilder)
        data = requestBuilder(data);
      connection.emitMessage(command, data);
    });
  }

  function createBackendMessageHandler(socket) {
    return (function(envelope) {
      var event = envelope.type;

      var data;
      var resultTypeMatch = envelope.type.match(/^(.+)\.result$/);
      if (resultTypeMatch && unifiedCommandSet[resultTypeMatch[1]]) {
        var command = unifiedCommandSet[resultTypeMatch[1]];
        if (command.responseBuilder)
          data = command.responseBuilder(envelope);
        if (command.responseEvent)
          event = command.responseEvent;
      }

      if (!data)
        data = sanitizeBackendMessage(envelope);

      socket.emit(event, data);
    });
  }

  function createErrorHandler(socket) {
    return (function(error) {
      socket.emit('error', error);
    });
  }

  var commandSets = [defaultCommands].concat(params.plugins || []);
  var unifiedCommandSet = {};
  commandSets.forEach(function(commandSet) {
    if (typeof commandSet == 'string')
      commandSet = require(commandSet);

    Object.keys(commandSet).forEach(function(command) {
      var definition = commandSet[command];
      if (!definition || definition.method) // ignore REST command
        return;
      unifiedCommandSet[command] = definition;
    });
  });

  var registeredCommands = [];
  Object.keys(unifiedCommandSet).forEach(function(command) {
    var definition = unifiedCommandSet[command];
    if (!definition || typeof definition != 'object') // ignore not a command definition
      return;
    registeredCommands.push({ command:    command,
                              definition: definition });
  });

  var io = socketIo.listen(server);
  io.sockets.on('connection', function(socket) {
    application.emit('connection', socket);

    var messageHandlers = [];
    registeredCommands.forEach(function(command) {
      socket.on(command.command,
                createRequestHandler(command.command,
                                     socket,
                                     command.definition.requestBuilder));
    });

    var backendMessageHandler = createBackendMessageHandler(socket);
    connection.on('message', backendMessageHandler);

    var errorHandler = createErrorHandler(socket);
    connection.on('error', errorHandler);

    socket.on('disconnect', function() {
      connection.removeListener('message', backendMessageHandler);
      connection.removeListener('error', errorHandler);
      socket.removeAllListeners();
    });
  });

  return registeredCommands;
}
<|endoftext|>


<commit_before>import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import Avatar from './avatar';
import AvatarOverlay from './avatar_overlay';
import DisplayName from './display_name';
import MediaGallery from './media_gallery';
import VideoPlayer from './video_player';
import StatusContent from './status_content';
import StatusActionBar from './status_action_bar';
import IconButton from './icon_button';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import emojify from '../emoji';
import escapeTextContentForBrowser from 'escape-html';
import ImmutablePureComponent from 'react-immutable-pure-component';
import scheduleIdleTask from '../features/ui/util/schedule_idle_task';

const messages = defineMessages({
  collapse: { id: 'status.collapse', defaultMessage: 'Collapse' },
  uncollapse: { id: 'status.uncollapse', defaultMessage: 'Uncollapse' },
});

class StatusUnextended extends ImmutablePureComponent {

  static contextTypes = {
    router: PropTypes.object,
  };

  static propTypes = {
    status: ImmutablePropTypes.map,
    account: ImmutablePropTypes.map,
    wrapped: PropTypes.bool,
    onReply: PropTypes.func,
    onFavourite: PropTypes.func,
    onReblog: PropTypes.func,
    onDelete: PropTypes.func,
    onOpenMedia: PropTypes.func,
    onOpenVideo: PropTypes.func,
    onBlock: PropTypes.func,
    me: PropTypes.number,
    boostModal: PropTypes.bool,
    autoPlayGif: PropTypes.bool,
    muted: PropTypes.bool,
    intersectionObserverWrapper: PropTypes.object,
    intl: PropTypes.object.isRequired,
  };

  state = {
    isExpanded: false,
    isIntersecting: true, // assume intersecting until told otherwise
    isHidden: false, // set to true in requestIdleCallback to trigger un-render
    isCollapsed: false,
  }

  // Avoid checking props that are functions (and whose equality will always
  // evaluate to false. See react-immutable-pure-component for usage.
  updateOnProps = [
    'status',
    'account',
    'wrapped',
    'me',
    'boostModal',
    'autoPlayGif',
    'muted',
  ]

  updateOnStates = ['isExpanded']

  shouldComponentUpdate (nextProps, nextState) {
    if (nextState.isCollapsed !== this.state.isCollapsed) {
      // If the collapsed state of the element has changed then we definitely
      // need to re-update.
      return true;
    } else if (!nextState.isIntersecting && nextState.isHidden) {
      // It's only if we're not intersecting (i.e. offscreen) and isHidden is true
      // that either "isIntersecting" or "isHidden" matter, and then they're
      // the only things that matter.
      return this.state.isIntersecting || !this.state.isHidden;
    } else if (nextState.isIntersecting && !this.state.isIntersecting) {
      // If we're going from a non-intersecting state to an intersecting state,
      // (i.e. offscreen to onscreen), then we definitely need to re-render
      return true;
    }
    // Otherwise, diff based on "updateOnProps" and "updateOnStates"
    return super.shouldComponentUpdate(nextProps, nextState);
  }

  componentDidUpdate (prevProps, prevState) {
    if (prevState.isCollapsed !== this.state.isCollapsed) this.saveHeight();
  }

  componentDidMount () {
    const node = this.node;

    if (!this.props.intersectionObserverWrapper) {
      // TODO: enable IntersectionObserver optimization for notification statuses.
      // These are managed in notifications/index.js rather than status_list.js
      return;
    }
    this.props.intersectionObserverWrapper.observe(
      this.props.id,
      this.node,
      this.handleIntersection
    );

    if (node.clientHeight > 400 && !(this.props.status.get('reblog', null) !== null && typeof this.props.status.get('reblog') === 'object')) this.setState({ isCollapsed: true });

    this.componentMounted = true;
  }

  componentWillUnmount () {
    this.componentMounted = false;
  }

  handleIntersection = (entry) => {
    // Edge 15 doesn't support isIntersecting, but we can infer it
    // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/12156111/
    // https://github.com/WICG/IntersectionObserver/issues/211
    const isIntersecting = (typeof entry.isIntersecting === 'boolean') ?
      entry.isIntersecting : entry.intersectionRect.height > 0;
    this.setState((prevState) => {
      if (prevState.isIntersecting && !isIntersecting) {
        scheduleIdleTask(this.hideIfNotIntersecting);
      }
      return {
        isIntersecting: isIntersecting,
        isHidden: false,
      };
    });
  }

  hideIfNotIntersecting = () => {
    if (!this.componentMounted) {
      return;
    }

    // When the browser gets a chance, test if we're still not intersecting,
    // and if so, set our isHidden to true to trigger an unrender. The point of
    // this is to save DOM nodes and avoid using up too much memory.
    // See: https://github.com/tootsuite/mastodon/issues/2900
    this.setState((prevState) => ({ isHidden: !prevState.isIntersecting }));
  }

  saveHeight = () => {
    if (this.node && this.node.children.length !== 0) {
      this.height = this.node.clientHeight;
    }
  }

  handleRef = (node) => {
    this.node = node;
    this.saveHeight();
  }

  handleClick = () => {
    const { status, isCollapsed } = this.props;
    if (isCollapsed) this.handleCollapsedClick();
    else this.context.router.history.push(`/statuses/${status.getIn(['reblog', 'id'], status.get('id'))}`);
  }

  handleAccountClick = (e) => {
    if (e.button === 0) {
      const id = Number(e.currentTarget.getAttribute('data-id'));
      e.preventDefault();
      this.context.router.history.push(`/accounts/${id}`);
    }
  }

  handleExpandedToggle = () => {
    this.setState({ isExpanded: !this.state.isExpanded, isCollapsed: false });
  };

  handleCollapsedClick = () => {
    this.setState({ isCollapsed: !this.state.isCollapsed, isExpanded: false });
  }

  render () {
    let media = null;
    let mediaType = null;
    let thumb = null;
    let statusAvatar;

    // Exclude intersectionObserverWrapper from `other` variable
    // because intersection is managed in here.
    const { status, account, intersectionObserverWrapper, intl, ...other } = this.props;
    const { isExpanded, isIntersecting, isHidden, isCollapsed } = this.state;

    if (status === null) {
      return null;
    }

    if (!isIntersecting && isHidden) {
      return (
        <div ref={this.handleRef} data-id={status.get('id')} style={{ height: `${this.height}px`, opacity: 0, overflow: 'hidden' }}>
          {status.getIn(['account', 'display_name']) || status.getIn(['account', 'username'])}
          {status.get('content')}

      );
    }

    if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') {
      let displayName = status.getIn(['account', 'display_name']);

      if (displayName.length === 0) {
        displayName = status.getIn(['account', 'username']);
      }

      const displayNameHTML = { __html: emojify(escapeTextContentForBrowser(displayName)) };

      return (

            <FormattedMessage id='status.reblogged_by' defaultMessage='{name} boosted' values={{ name:  }} />

          <Status {...other} wrapped status={status.get('reblog')} account={status.get('account')} />

      );
    }

    if (status.get('media_attachments').size > 0 && !this.props.muted) {
      if (status.get('media_attachments').some(item => item.get('type') === 'unknown')) {

      } else if (status.getIn(['media_attachments', 0, 'type']) === 'video') {
        media = <VideoPlayer media={status.getIn(['media_attachments', 0])} sensitive={status.get('sensitive')} onOpenVideo={this.props.onOpenVideo} />;
        mediaType = ;
        if (!status.get('sensitive') && !(status.get('spoiler_text').length > 0)) thumb = status.getIn(['media_attachments', 0]).get('preview_url');
      } else {
        media = <MediaGallery media={status.get('media_attachments')} sensitive={status.get('sensitive')} height={110} onOpenMedia={this.props.onOpenMedia} autoPlayGif={this.props.autoPlayGif} />;
        mediaType = status.get('media_attachments').size > 1 ?  : ;
        if (!status.get('sensitive') && !(status.get('spoiler_text').length > 0)) thumb = status.getIn(['media_attachments', 0]).get('preview_url');
      }
    }

    if (account === undefined || account === null) {
      statusAvatar = <Avatar src={status.getIn(['account', 'avatar'])} staticSrc={status.getIn(['account', 'avatar_static'])} size={48} />;
    }else{
      statusAvatar = <AvatarOverlay staticSrc={status.getIn(['account', 'avatar_static'])} overlaySrc={account.get('avatar_static')} />;
    }

    return (
      <div className={`status ${this.props.muted ? 'muted' : ''} status-${status.get('visibility')} ${isCollapsed ? 'status-collapsed' : ''}`} data-id={status.get('id')} ref={this.handleRef} style={{ backgroundImage: thumb && isCollapsed ? 'url(' + thumb + ')' : 'none' }}>

            {mediaType}
            <IconButton
              className='status__collapse-button'
              animate flip
              active={isCollapsed}
              title={isCollapsed ? intl.formatMessage(messages.uncollapse) : intl.formatMessage(messages.collapse)}
              icon='angle-double-up'
              onClick={this.handleCollapsedClick}
            />

              {statusAvatar}

            <DisplayName account={status.get('account')} />

        <StatusContent status={status} onClick={this.handleClick} expanded={isExpanded} onExpandedToggle={this.handleExpandedToggle} onHeightUpdate={this.saveHeight}>

          {isCollapsed ? null : media}

        </StatusContent>

        {isCollapsed ? null : <StatusActionBar status={status} account={account} {...other} />}

    );
  }

}

const Status = injectIntl(StatusUnextended);
export default Status;
<commit_msg>Expand toot by clicking on body [fixed!]<commit_after>import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import Avatar from './avatar';
import AvatarOverlay from './avatar_overlay';
import DisplayName from './display_name';
import MediaGallery from './media_gallery';
import VideoPlayer from './video_player';
import StatusContent from './status_content';
import StatusActionBar from './status_action_bar';
import IconButton from './icon_button';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import emojify from '../emoji';
import escapeTextContentForBrowser from 'escape-html';
import ImmutablePureComponent from 'react-immutable-pure-component';
import scheduleIdleTask from '../features/ui/util/schedule_idle_task';

const messages = defineMessages({
  collapse: { id: 'status.collapse', defaultMessage: 'Collapse' },
  uncollapse: { id: 'status.uncollapse', defaultMessage: 'Uncollapse' },
});

class StatusUnextended extends ImmutablePureComponent {

  static contextTypes = {
    router: PropTypes.object,
  };

  static propTypes = {
    status: ImmutablePropTypes.map,
    account: ImmutablePropTypes.map,
    wrapped: PropTypes.bool,
    onReply: PropTypes.func,
    onFavourite: PropTypes.func,
    onReblog: PropTypes.func,
    onDelete: PropTypes.func,
    onOpenMedia: PropTypes.func,
    onOpenVideo: PropTypes.func,
    onBlock: PropTypes.func,
    me: PropTypes.number,
    boostModal: PropTypes.bool,
    autoPlayGif: PropTypes.bool,
    muted: PropTypes.bool,
    intersectionObserverWrapper: PropTypes.object,
    intl: PropTypes.object.isRequired,
  };

  state = {
    isExpanded: false,
    isIntersecting: true, // assume intersecting until told otherwise
    isHidden: false, // set to true in requestIdleCallback to trigger un-render
    isCollapsed: false,
  }

  // Avoid checking props that are functions (and whose equality will always
  // evaluate to false. See react-immutable-pure-component for usage.
  updateOnProps = [
    'status',
    'account',
    'wrapped',
    'me',
    'boostModal',
    'autoPlayGif',
    'muted',
  ]

  updateOnStates = ['isExpanded']

  shouldComponentUpdate (nextProps, nextState) {
    if (nextState.isCollapsed !== this.state.isCollapsed) {
      // If the collapsed state of the element has changed then we definitely
      // need to re-update.
      return true;
    } else if (!nextState.isIntersecting && nextState.isHidden) {
      // It's only if we're not intersecting (i.e. offscreen) and isHidden is true
      // that either "isIntersecting" or "isHidden" matter, and then they're
      // the only things that matter.
      return this.state.isIntersecting || !this.state.isHidden;
    } else if (nextState.isIntersecting && !this.state.isIntersecting) {
      // If we're going from a non-intersecting state to an intersecting state,
      // (i.e. offscreen to onscreen), then we definitely need to re-render
      return true;
    }
    // Otherwise, diff based on "updateOnProps" and "updateOnStates"
    return super.shouldComponentUpdate(nextProps, nextState);
  }

  componentDidUpdate (prevProps, prevState) {
    if (prevState.isCollapsed !== this.state.isCollapsed) this.saveHeight();
  }

  componentDidMount () {
    const node = this.node;

    if (!this.props.intersectionObserverWrapper) {
      // TODO: enable IntersectionObserver optimization for notification statuses.
      // These are managed in notifications/index.js rather than status_list.js
      return;
    }
    this.props.intersectionObserverWrapper.observe(
      this.props.id,
      this.node,
      this.handleIntersection
    );

    if (node.clientHeight > 400 && !(this.props.status.get('reblog', null) !== null && typeof this.props.status.get('reblog') === 'object')) this.setState({ isCollapsed: true });

    this.componentMounted = true;
  }

  componentWillUnmount () {
    this.componentMounted = false;
  }

  handleIntersection = (entry) => {
    // Edge 15 doesn't support isIntersecting, but we can infer it
    // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/12156111/
    // https://github.com/WICG/IntersectionObserver/issues/211
    const isIntersecting = (typeof entry.isIntersecting === 'boolean') ?
      entry.isIntersecting : entry.intersectionRect.height > 0;
    this.setState((prevState) => {
      if (prevState.isIntersecting && !isIntersecting) {
        scheduleIdleTask(this.hideIfNotIntersecting);
      }
      return {
        isIntersecting: isIntersecting,
        isHidden: false,
      };
    });
  }

  hideIfNotIntersecting = () => {
    if (!this.componentMounted) {
      return;
    }

    // When the browser gets a chance, test if we're still not intersecting,
    // and if so, set our isHidden to true to trigger an unrender. The point of
    // this is to save DOM nodes and avoid using up too much memory.
    // See: https://github.com/tootsuite/mastodon/issues/2900
    this.setState((prevState) => ({ isHidden: !prevState.isIntersecting }));
  }

  saveHeight = () => {
    if (this.node && this.node.children.length !== 0) {
      this.height = this.node.clientHeight;
    }
  }

  handleRef = (node) => {
    this.node = node;
    this.saveHeight();
  }

  handleClick = () => {
    const { status } = this.props;
    const { isCollapsed } = this.state;
    if (isCollapsed) this.handleCollapsedClick();
    else this.context.router.history.push(`/statuses/${status.getIn(['reblog', 'id'], status.get('id'))}`);
  }

  handleAccountClick = (e) => {
    if (e.button === 0) {
      const id = Number(e.currentTarget.getAttribute('data-id'));
      e.preventDefault();
      this.context.router.history.push(`/accounts/${id}`);
    }
  }

  handleExpandedToggle = () => {
    this.setState({ isExpanded: !this.state.isExpanded, isCollapsed: false });
  };

  handleCollapsedClick = () => {
    this.setState({ isCollapsed: !this.state.isCollapsed, isExpanded: false });
  }

  render () {
    let media = null;
    let mediaType = null;
    let thumb = null;
    let statusAvatar;

    // Exclude intersectionObserverWrapper from `other` variable
    // because intersection is managed in here.
    const { status, account, intersectionObserverWrapper, intl, ...other } = this.props;
    const { isExpanded, isIntersecting, isHidden, isCollapsed } = this.state;

    if (status === null) {
      return null;
    }

    if (!isIntersecting && isHidden) {
      return (
        <div ref={this.handleRef} data-id={status.get('id')} style={{ height: `${this.height}px`, opacity: 0, overflow: 'hidden' }}>
          {status.getIn(['account', 'display_name']) || status.getIn(['account', 'username'])}
          {status.get('content')}

      );
    }

    if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') {
      let displayName = status.getIn(['account', 'display_name']);

      if (displayName.length === 0) {
        displayName = status.getIn(['account', 'username']);
      }

      const displayNameHTML = { __html: emojify(escapeTextContentForBrowser(displayName)) };

      return (

            <FormattedMessage id='status.reblogged_by' defaultMessage='{name} boosted' values={{ name:  }} />

          <Status {...other} wrapped status={status.get('reblog')} account={status.get('account')} />

      );
    }

    if (status.get('media_attachments').size > 0 && !this.props.muted) {
      if (status.get('media_attachments').some(item => item.get('type') === 'unknown')) {

      } else if (status.getIn(['media_attachments', 0, 'type']) === 'video') {
        media = <VideoPlayer media={status.getIn(['media_attachments', 0])} sensitive={status.get('sensitive')} onOpenVideo={this.props.onOpenVideo} />;
        mediaType = ;
        if (!status.get('sensitive') && !(status.get('spoiler_text').length > 0)) thumb = status.getIn(['media_attachments', 0]).get('preview_url');
      } else {
        media = <MediaGallery media={status.get('media_attachments')} sensitive={status.get('sensitive')} height={110} onOpenMedia={this.props.onOpenMedia} autoPlayGif={this.props.autoPlayGif} />;
        mediaType = status.get('media_attachments').size > 1 ?  : ;
        if (!status.get('sensitive') && !(status.get('spoiler_text').length > 0)) thumb = status.getIn(['media_attachments', 0]).get('preview_url');
      }
    }

    if (account === undefined || account === null) {
      statusAvatar = <Avatar src={status.getIn(['account', 'avatar'])} staticSrc={status.getIn(['account', 'avatar_static'])} size={48} />;
    }else{
      statusAvatar = <AvatarOverlay staticSrc={status.getIn(['account', 'avatar_static'])} overlaySrc={account.get('avatar_static')} />;
    }

    return (
      <div className={`status ${this.props.muted ? 'muted' : ''} status-${status.get('visibility')} ${isCollapsed ? 'status-collapsed' : ''}`} data-id={status.get('id')} ref={this.handleRef} style={{ backgroundImage: thumb && isCollapsed ? 'url(' + thumb + ')' : 'none' }}>

            {mediaType}
            <IconButton
              className='status__collapse-button'
              animate flip
              active={isCollapsed}
              title={isCollapsed ? intl.formatMessage(messages.uncollapse) : intl.formatMessage(messages.collapse)}
              icon='angle-double-up'
              onClick={this.handleCollapsedClick}
            />

              {statusAvatar}

            <DisplayName account={status.get('account')} />

        <StatusContent status={status} onClick={this.handleClick} expanded={isExpanded} onExpandedToggle={this.handleExpandedToggle} onHeightUpdate={this.saveHeight}>

          {isCollapsed ? null : media}

        </StatusContent>

        {isCollapsed ? null : <StatusActionBar status={status} account={account} {...other} />}

    );
  }

}

const Status = injectIntl(StatusUnextended);
export default Status;
<|endoftext|>


<commit_before>'use strict';
global.visualizer = {};
if (config.visualizer.enabled) {
  global.visualizer = {

    drawPosition(rv, position, text, color) {
      rv.text(text, position.x, position.y + 0.2, {
        color: color,
        font: 0.7,
        opacity: 0.5,
      });
    },

    drawPath(rv, path, color) {
      if (path.length) {
        rv.poly(path.map((p) => [p.x, p.y]), {
          stroke: color,
          strokeWidth: 0.1,
          opacity: 0.5,
        });
      }
    },

    /**
     * draw fixed paths in room
     */
    showRoomPaths() {
      for (const room of _.values(Game.rooms)) {
        const rv = room.visual;
        const paths = room.getMemoryPaths();
        for (const route of _.values(paths)) {
          this.drawPath(rv, route.path, 'white');
        }
      }
    },

    /**
     * draw creep paths from using moveTo
     */
    showCreepPaths() {
      for (const creep of _.values(Game.creeps)) {
        const rv = creep.room.visual;
        if (creep.memory._move) {
          const path = Room.deserializePath(creep.memory._move.path);
          this.drawPath(rv, path, 'red');
        }
      }
    },

    /**
     * draw structures
     */
    showStructures() {
      for (const room of _.values(Game.rooms)) {
        const rv = room.visual;
        if (room.memory.position && room.memory.position.structure) {
          const structures = room.memory.position.structure;
          for (const structType of Object.keys(structures)) {
            const text = structType.substr(0, 1).toUpperCase() + structType.substr(1, 1);
            for (const structure of structures[structType]) {
              this.drawPosition(rv, structure, text, 'blue');
            }
          }
        }
      }
    },

    showBlockers() {
      for (const room of _.values(Game.rooms)) {
        const rv = room.visual;
        if (room.memory.walls && room.memory.walls.layer) {
          for (const layer of Object.keys(room.memory.walls.layer)) {
            for (const pos of room.memory.walls.layer[layer]) {
              this.drawPosition(rv, pos, layer, 'blue');
              rv.rect(pos.x - 0.5, pos.y - 0.5, 1, 1, {
                fill: 'transparent',
                stroke: 'blue',
              });
            }
          }
        }
        if (room.memory.walls && room.memory.walls.ramparts) {
          for (const pos of room.memory.walls.ramparts) {
            rv.circle(pos, {
              radius: 0.5,
              fill: 'transparent',
              stroke: 'blue',
            });
          }
        }
      }
    },

    /**
     * draw creep positions
     */
    showCreeps() {
      for (const room of _.values(Game.rooms)) {
        const rv = room.visual;
        if (room.memory.position) {
          const creeps = room.memory.position.creep;
          for (const positionName of Object.keys(creeps)) {
            if (creeps[positionName]) {
              if (creeps[positionName].x || creeps[positionName].y) {
                const text = positionName.substr(0, 1);
                this.drawPosition(rv, creeps[positionName], text, 'yellow');
              } else {
                const text = positionName.substr(0, 1);
                for (const towerfiller of creeps[positionName]) {
                  this.drawPosition(rv, towerfiller, text, 'yellow');
                }
              }
            }
          }
        }
      }
    },

    showCostMatrix(roomName, costMatrixCallback) {
      const rv = new RoomVisual(roomName);
      const cm = costMatrixCallback(roomName);
      if (cm) {
        for (let x = 0; x < 50; ++x) {
          for (let y = 0; y < 50; ++y) {
            rv.rect(x - 0.5, y - 0.5, 1, 1, {
              fill: 'pink',
              opacity: Math.pow(cm.get(x, y) / 255, 1 / 4),
            });
          }
        }
      }
    },

    showCostMatrixes() {
      for (const room of _.values(Game.rooms)) {
        this.showCostMatrix(room.name, room.getCostMatrixCallback());
      }
    },

    showSearch(search) {
      if (search) {
        const rv = {};
        const getRV = (pos) => {
          if (!rv[pos.roomName]) {
            rv[pos.roomName] = new RoomVisual(pos.roomName);
          }
          return rv[pos.roomName];
        };
        let prevPos = search.path[0];
        const style = {
          color: search.incomplete ? 'red' : 'green',
        };
        for (const pi of search.path) {
          if (prevPos.roomName === pi.roomName) {
            getRV(pi).line(prevPos, pi, style);
          } else {
            const dx = prevPos.x === 0 ? -0.5 : prevPos.x === 49 ? 0.5 : 0;
            const dy = prevPos.y === 0 ? -0.5 : prevPos.y === 49 ? 0.5 : 0;
            getRV(prevPos).line(prevPos.x, prevPos.y, prevPos.x + dx, prevPos.y + dy, style);
            getRV(pi).line(pi.x, pi.y, pi.x - dx, pi.y - dy, style);
          }
          prevPos = pi;
        }
      }
    },

    render() {
      if (config.visualizer.showCostMatrixes) {
        this.showCostMatrixes();
      }
      if (config.visualizer.showRoomPaths) {
        this.showRoomPaths();
      }
      if (config.visualizer.showCreepPaths) {
        this.showCreepPaths();
      }
      if (config.visualizer.showStructures) {
        this.showStructures();
      }
      if (config.visualizer.showCreeps) {
        this.showCreeps();
      }
      if (config.visualizer.showBlockers) {
        this.showBlockers();
      }
    },
  };
}

global.visualizer.myRoomDatasDraw = function(roomName) {
  const fontSize = 0.65;
  const room = Game.rooms[roomName];
  const energy = (room.memory.energyStats && Math.floor(room.memory.energyStats.average)) ||
    room.energyAvailable;
  const storedE = room.storage ? room.storage.store[RESOURCE_ENERGY] : 0;
  const queueL = room.memory.queue ? room.memory.queue.length : 0;
  const rclP = Math.floor(100 * (room.controller.progressTotal ? room.controller.progress / room.controller.progressTotal : 1));

  const color = (coeff) => `rgb(${Math.floor(-(coeff - 1) * 255)},${Math.floor(coeff * 255)},0)`;
  const lines = [
    {label: `Energy Average :`, value: energy, coeff: energy / room.energyCapacityAvailable},
    {label: `Stored Energy :`, value: storedE, coeff: Math.min(storedE, 500000) / 500000},
    {label: `Queue length :`, value: queueL, coeff: (20 - Math.min(queueL, 20)) / 20},
    {label: `RCL ${room.controller.level} progress :`, value: rclP, coeff: rclP / 100},
  ];
  if (config.stats.summary && Memory.summary) {
    const rclSpeed = Math.floor(room.memory.upgraderUpgrade / (Game.time % 100 || 1));
    lines.push({label: `RCL speed:`, value: rclSpeed, coeff: rclSpeed / 50});
  }
  if (room.memory.queue.length) {
    const lowestInQueue = [
      _.chain(room.memory.queue).sortBy((creep) => creep.ttl).value()[0],
      room.memory.queue[0],
    ];
    const labels = ['ttl', 'priority'];
    let lowest;
    for (let id = 0; id < 2; id++) {
      lowest = lowestInQueue[id];
      lines.push({label: `Lowest ${labels[id]}: ${lowest.role} --> ${(lowest.routing && lowest.routing.targetRoom) || '?'} | TTL: ${lowest.ttl || '?'}`});
    }
  }
  let y = 0;
  let line;
  for (line of lines) {
    room.visual.text(line.label, 0.5, 0.75 + 2 * y * fontSize, {
      color: 'rgb(255,255,255)',
      font: fontSize,
      align: 'left',
    });
    if (line.value !== undefined) {
      room.visual.text(`${line.value}`, 6, 1.5 * fontSize + 2 * y * fontSize, {
        color: color(line.coeff),
        font: fontSize * 2,
        align: 'left',
      });
    }
    y++;
  }

  if (config.stats.summary && Memory.summary) {
    const highterQueue = _.chain(Memory.myRooms)
      .map((roomName) => {
        return {length: -Memory.rooms[roomName].queue.length, roomName: roomName};
      }).sortBy((roomRet) => -Memory.rooms[roomRet.roomName].queue.length).value()[0];
    const output = `=========================
      Game time: ${Game.time}
      Progress: ${(Game.gcl.progress - Memory.progress) / 100}/${Memory.myRooms.length * 15}
      ConstructionSites: ${Object.keys(Memory.constructionSites).length}
      -------------------------
      No storage: ${Memory.summary.storageNoString}
      Low storage: ${Memory.summary.storageLowString}
      Middle storage: ${Memory.summary.storageMiddleString}
      High storage: ${Memory.summary.storageHighString}
      -------------------------
      Power storage: ${Memory.summary.storagePower}
      -------------------------
      Upgrade less: ${Memory.summary.upgradeLess}
      -------------------------
      Highter queue: ${highterQueue.roomName}:${-highterQueue.length}
      =========================`;
    const lines = output.split('\n');
    let l = 0;
    for (l; l < lines.length; l++) {
      room.visual.text(lines[l], 25, 25 + (l * (fontSize - 0.05)), {font: fontSize});
    }
  }
};
<commit_msg>remove redundant code in queue sort<commit_after>'use strict';
global.visualizer = {};
if (config.visualizer.enabled) {
  global.visualizer = {

    drawPosition(rv, position, text, color) {
      rv.text(text, position.x, position.y + 0.2, {
        color: color,
        font: 0.7,
        opacity: 0.5,
      });
    },

    drawPath(rv, path, color) {
      if (path.length) {
        rv.poly(path.map((p) => [p.x, p.y]), {
          stroke: color,
          strokeWidth: 0.1,
          opacity: 0.5,
        });
      }
    },

    /**
     * draw fixed paths in room
     */
    showRoomPaths() {
      for (const room of _.values(Game.rooms)) {
        const rv = room.visual;
        const paths = room.getMemoryPaths();
        for (const route of _.values(paths)) {
          this.drawPath(rv, route.path, 'white');
        }
      }
    },

    /**
     * draw creep paths from using moveTo
     */
    showCreepPaths() {
      for (const creep of _.values(Game.creeps)) {
        const rv = creep.room.visual;
        if (creep.memory._move) {
          const path = Room.deserializePath(creep.memory._move.path);
          this.drawPath(rv, path, 'red');
        }
      }
    },

    /**
     * draw structures
     */
    showStructures() {
      for (const room of _.values(Game.rooms)) {
        const rv = room.visual;
        if (room.memory.position && room.memory.position.structure) {
          const structures = room.memory.position.structure;
          for (const structType of Object.keys(structures)) {
            const text = structType.substr(0, 1).toUpperCase() + structType.substr(1, 1);
            for (const structure of structures[structType]) {
              this.drawPosition(rv, structure, text, 'blue');
            }
          }
        }
      }
    },

    showBlockers() {
      for (const room of _.values(Game.rooms)) {
        const rv = room.visual;
        if (room.memory.walls && room.memory.walls.layer) {
          for (const layer of Object.keys(room.memory.walls.layer)) {
            for (const pos of room.memory.walls.layer[layer]) {
              this.drawPosition(rv, pos, layer, 'blue');
              rv.rect(pos.x - 0.5, pos.y - 0.5, 1, 1, {
                fill: 'transparent',
                stroke: 'blue',
              });
            }
          }
        }
        if (room.memory.walls && room.memory.walls.ramparts) {
          for (const pos of room.memory.walls.ramparts) {
            rv.circle(pos, {
              radius: 0.5,
              fill: 'transparent',
              stroke: 'blue',
            });
          }
        }
      }
    },

    /**
     * draw creep positions
     */
    showCreeps() {
      for (const room of _.values(Game.rooms)) {
        const rv = room.visual;
        if (room.memory.position) {
          const creeps = room.memory.position.creep;
          for (const positionName of Object.keys(creeps)) {
            if (creeps[positionName]) {
              if (creeps[positionName].x || creeps[positionName].y) {
                const text = positionName.substr(0, 1);
                this.drawPosition(rv, creeps[positionName], text, 'yellow');
              } else {
                const text = positionName.substr(0, 1);
                for (const towerfiller of creeps[positionName]) {
                  this.drawPosition(rv, towerfiller, text, 'yellow');
                }
              }
            }
          }
        }
      }
    },

    showCostMatrix(roomName, costMatrixCallback) {
      const rv = new RoomVisual(roomName);
      const cm = costMatrixCallback(roomName);
      if (cm) {
        for (let x = 0; x < 50; ++x) {
          for (let y = 0; y < 50; ++y) {
            rv.rect(x - 0.5, y - 0.5, 1, 1, {
              fill: 'pink',
              opacity: Math.pow(cm.get(x, y) / 255, 1 / 4),
            });
          }
        }
      }
    },

    showCostMatrixes() {
      for (const room of _.values(Game.rooms)) {
        this.showCostMatrix(room.name, room.getCostMatrixCallback());
      }
    },

    showSearch(search) {
      if (search) {
        const rv = {};
        const getRV = (pos) => {
          if (!rv[pos.roomName]) {
            rv[pos.roomName] = new RoomVisual(pos.roomName);
          }
          return rv[pos.roomName];
        };
        let prevPos = search.path[0];
        const style = {
          color: search.incomplete ? 'red' : 'green',
        };
        for (const pi of search.path) {
          if (prevPos.roomName === pi.roomName) {
            getRV(pi).line(prevPos, pi, style);
          } else {
            const dx = prevPos.x === 0 ? -0.5 : prevPos.x === 49 ? 0.5 : 0;
            const dy = prevPos.y === 0 ? -0.5 : prevPos.y === 49 ? 0.5 : 0;
            getRV(prevPos).line(prevPos.x, prevPos.y, prevPos.x + dx, prevPos.y + dy, style);
            getRV(pi).line(pi.x, pi.y, pi.x - dx, pi.y - dy, style);
          }
          prevPos = pi;
        }
      }
    },

    render() {
      if (config.visualizer.showCostMatrixes) {
        this.showCostMatrixes();
      }
      if (config.visualizer.showRoomPaths) {
        this.showRoomPaths();
      }
      if (config.visualizer.showCreepPaths) {
        this.showCreepPaths();
      }
      if (config.visualizer.showStructures) {
        this.showStructures();
      }
      if (config.visualizer.showCreeps) {
        this.showCreeps();
      }
      if (config.visualizer.showBlockers) {
        this.showBlockers();
      }
    },
  };
}

global.visualizer.myRoomDatasDraw = function(roomName) {
  const fontSize = 0.65;
  const room = Game.rooms[roomName];
  const energy = (room.memory.energyStats && Math.floor(room.memory.energyStats.average)) ||
    room.energyAvailable;
  const storedE = room.storage ? room.storage.store[RESOURCE_ENERGY] : 0;
  const queueL = room.memory.queue ? room.memory.queue.length : 0;
  const rclP = Math.floor(100 * (room.controller.progressTotal ? room.controller.progress / room.controller.progressTotal : 1));

  const color = (coeff) => `rgb(${Math.floor(-(coeff - 1) * 255)},${Math.floor(coeff * 255)},0)`;
  const lines = [
    {label: `Energy Average :`, value: energy, coeff: energy / room.energyCapacityAvailable},
    {label: `Stored Energy :`, value: storedE, coeff: Math.min(storedE, 500000) / 500000},
    {label: `Queue length :`, value: queueL, coeff: (20 - Math.min(queueL, 20)) / 20},
    {label: `RCL ${room.controller.level} progress :`, value: rclP, coeff: rclP / 100},
  ];
  if (config.stats.summary && Memory.summary) {
    const rclSpeed = Math.floor(room.memory.upgraderUpgrade / (Game.time % 100 || 1));
    lines.push({label: `RCL speed:`, value: rclSpeed, coeff: rclSpeed / 50});
  }
  if (room.memory.queue.length) {
    const lowestInQueue = [
      _.chain(room.memory.queue).sortBy((creep) => creep.ttl).value()[0],
      room.memory.queue[0],
    ];
    const labels = ['ttl', 'priority'];
    let lowest;
    for (let id = 0; id < 2; id++) {
      lowest = lowestInQueue[id];
      lines.push({label: `Lowest ${labels[id]}: ${lowest.role} --> ${(lowest.routing && lowest.routing.targetRoom) || '?'} | TTL: ${lowest.ttl || '?'}`});
    }
  }
  let y = 0;
  let line;
  for (line of lines) {
    room.visual.text(line.label, 0.5, 0.75 + 2 * y * fontSize, {
      color: 'rgb(255,255,255)',
      font: fontSize,
      align: 'left',
    });
    if (line.value !== undefined) {
      room.visual.text(`${line.value}`, 6, 1.5 * fontSize + 2 * y * fontSize, {
        color: color(line.coeff),
        font: fontSize * 2,
        align: 'left',
      });
    }
    y++;
  }

  if (config.stats.summary && Memory.summary) {
    const highterQueue = _.sortBy(Memory.myRooms, (roomName) => -Memory.rooms[roomName].queue.length)[0];
    const output = `=========================
      Game time: ${Game.time}
      Progress: ${(Game.gcl.progress - Memory.progress) / 100}/${Memory.myRooms.length * 15}
      ConstructionSites: ${Object.keys(Memory.constructionSites).length}
      -------------------------
      No storage: ${Memory.summary.storageNoString}
      Low storage: ${Memory.summary.storageLowString}
      Middle storage: ${Memory.summary.storageMiddleString}
      High storage: ${Memory.summary.storageHighString}
      -------------------------
      Power storage: ${Memory.summary.storagePower}
      -------------------------
      Upgrade less: ${Memory.summary.upgradeLess}
      -------------------------
      Highter queue: ${highterQueue.roomName}:${-highterQueue.length}
      =========================`;
    const lines = output.split('\n');
    let l = 0;
    for (l; l < lines.length; l++) {
      room.visual.text(lines[l], 25, 25 + (l * (fontSize - 0.05)), {font: fontSize});
    }
  }
};
<|endoftext|>


<commit_before>/**
 * @ngdoc controller
 * @name core.controller:AuthenticationController
 * @requires $controller
 * @requires $location
 * @requires $scope
 * @requires $window
 * @requires core.service:User
 * @example
 *

 *      <element ng-controller="AuthenticationController"></element>
 *

 *
 * @description
 *  This authentication controller contains login and logout methods. These methods based on user credentials
 *  will modify the user role and provide the necessary token to navigate to pages which require access based on roles.
 *  Extends {@link core.controller:AbstractController 'AbstractController'}
 *
 **/
core.controller('AuthenticationController', function ($controller, $location, $scope, $window, UserService, StorageService) {

    angular.extend(this, $controller('AbstractController', {
        $scope: $scope
    }));

    $scope.user = UserService.getCurrentUser();

    $scope.reset = function () {
        $scope.user.clearValidationResults();
        for (var key in $scope.forms) {
            if (!$scope.forms[key].$pristine) {
                $scope.forms[key].$setPristine();
            }
        }
        $scope.account = {
            email: '',
            password: ''
        };
        $scope.closeModal();
    };

    $scope.reset();

    /**
     * @ngdoc method
     * @name core.controller:AuthenticationController#$scope.login
     * @methodOf core.controller:AuthenticationController
     * @returns {void} returns void
     *
     * @description
     *  The login method deletes the default 'appConfig.roleAnonymous' and its specific token based on user role found in
     *  user credentials.
     */
    $scope.login = function (page) {

        StorageService.delete("token");
        StorageService.delete("role");

        var authorizeUrl = StorageService.get("post_authorize_url");

        // NOTE: simular in setup.js and authService.js
        var path = '';
        if (typeof page != 'undefined') {
            path = "/" + location.pathname.split("/")[1] + "/" + page;
        } else if (authorizeUrl) {
            path = authorizeUrl;
        } else {
            path = location.pathname;
        }

        if (appConfig.mockRole) {
            $window.open(appConfig.authService + "/token?referrer=" + encodeURIComponent(location.origin + path + location.search) + "&mock=" + appConfig.mockRole, "_self");
        } else {
            $window.open(appConfig.authService + "/token?referrer=" + encodeURIComponent(location.origin + path + location.search), "_self");
        }

    };

    /**
     * @ngdoc method
     * @name core.controller:AuthenticationController#$scope.logout
     * @methodOf core.controller:AuthenticationController
     * @returns {void} returns void
     *
     * @description
     *  The logout method will delete the session storage token, will set the sessionStorage role to default 'appConfig.roleAnonymous' and will
     *  direct to the default home page
     */
    $scope.logout = function () {
        StorageService.delete("token");
        StorageService.set("role", appConfig.anonymousRole);
        $scope.user.logout();
        angular.element(".dropdown").dropdown("toggle");
        $window.location.assign("/");
    };

});
<commit_msg>Use $browser.baseHref()) rather than literal "/".<commit_after>/**
 * @ngdoc controller
 * @name core.controller:AuthenticationController
 * @requires $controller
 * @requires $location
 * @requires $scope
 * @requires $window
 * @requires core.service:User
 * @example
 *

 *      <element ng-controller="AuthenticationController"></element>
 *

 *
 * @description
 *  This authentication controller contains login and logout methods. These methods based on user credentials
 *  will modify the user role and provide the necessary token to navigate to pages which require access based on roles.
 *  Extends {@link core.controller:AbstractController 'AbstractController'}
 *
 **/
core.controller('AuthenticationController', function ($browser, $controller, $location, $scope, $window, UserService, StorageService) {

    angular.extend(this, $controller('AbstractController', {
        $scope: $scope
    }));

    $scope.user = UserService.getCurrentUser();

    $scope.reset = function () {
        $scope.user.clearValidationResults();
        for (var key in $scope.forms) {
            if (!$scope.forms[key].$pristine) {
                $scope.forms[key].$setPristine();
            }
        }
        $scope.account = {
            email: '',
            password: ''
        };
        $scope.closeModal();
    };

    $scope.reset();

    /**
     * @ngdoc method
     * @name core.controller:AuthenticationController#$scope.login
     * @methodOf core.controller:AuthenticationController
     * @returns {void} returns void
     *
     * @description
     *  The login method deletes the default 'appConfig.roleAnonymous' and its specific token based on user role found in
     *  user credentials.
     */
    $scope.login = function (page) {

        StorageService.delete("token");
        StorageService.delete("role");

        var authorizeUrl = StorageService.get("post_authorize_url");

        // NOTE: simular in setup.js and authService.js
        var path = '';
        if (typeof page != 'undefined') {
            path = "/" + location.pathname.split("/")[1] + "/" + page;
        } else if (authorizeUrl) {
            path = authorizeUrl;
        } else {
            path = location.pathname;
        }

        if (appConfig.mockRole) {
            $window.open(appConfig.authService + "/token?referrer=" + encodeURIComponent(location.origin + path + location.search) + "&mock=" + appConfig.mockRole, "_self");
        } else {
            $window.open(appConfig.authService + "/token?referrer=" + encodeURIComponent(location.origin + path + location.search), "_self");
        }

    };

    /**
     * @ngdoc method
     * @name core.controller:AuthenticationController#$scope.logout
     * @methodOf core.controller:AuthenticationController
     * @returns {void} returns void
     *
     * @description
     *  The logout method will delete the session storage token, will set the sessionStorage role to default 'appConfig.roleAnonymous' and will
     *  direct to the default home page
     */
    $scope.logout = function () {
        StorageService.delete("token");
        StorageService.set("role", appConfig.anonymousRole);
        $scope.user.logout();
        angular.element(".dropdown").dropdown("toggle");
        $window.location.assign($browser.baseHref());
    };

});
<|endoftext|>


<commit_before>//Dont change it
requirejs(['ext_editor_1', 'jquery_190', 'raphael_210'],
    function (ext, $, TableComponent) {

        var cur_slide = {};

        ext.set_start_game(function (this_e) {
        });

        ext.set_process_in(function (this_e, data) {
            cur_slide["in"] = data[0];
        });

        ext.set_process_out(function (this_e, data) {
            cur_slide["out"] = data[0];
        });

        ext.set_process_ext(function (this_e, data) {
            cur_slide.ext = data;
            this_e.addAnimationSlide(cur_slide);
            cur_slide = {};
        });

        ext.set_process_err(function (this_e, data) {
            cur_slide['error'] = data[0];
            this_e.addAnimationSlide(cur_slide);
            cur_slide = {};
        });

        ext.set_animate_success_slide(function (this_e, options) {
            var $h = $(this_e.setHtmlSlide('

'));
            this_e.setAnimationHeight(115);
        });

        ext.set_animate_slide(function (this_e, data, options) {
            var $content = $(this_e.setHtmlSlide(ext.get_template('animation'))).find('.animation-content');
            if (!data) {
                console.log("data is undefined");
                return false;
            }

            //YOUR FUNCTION NAME
            var fname = 'puzzle88';

            var checkioInput = data.in || [0, 4, 3, 1, 0, 1, 4, 2, 3, 0, 2, 0];
            var checkioInputStr = fname + '(' + checkioInput.join(", ") + ')';

            var failError = function (dError) {
                $content.find('.call').html('Fail: ' + checkioInputStr);
                $content.find('.output').html(dError.replace(/\n/g, ","));

                $content.find('.output').addClass('error');
                $content.find('.call').addClass('error');
                $content.find('.answer').remove();
                $content.find('.explanation').remove();
                this_e.setAnimationHeight($content.height() + 60);
            };

            if (data.error) {
                failError(data.error);
                return false;
            }

            if (data.ext && data.ext.inspector_fail) {
                failError(data.ext.inspector_result_addon);
                return false;
            }

            var rightResult = data.ext["answer"];
            var userResult = data.out;
            var result = data.ext["result"];
            var result_code = data.ext["result_addon"][0];
            var result_message = data.ext["result_addon"][1];

            //if you need additional info from tests (if exists)
            var explanation = data.ext["explanation"];

            $content.find('.output').html(' Your result: ' + JSON.stringify(userResult));

            if (!result) {
                $content.find('.call').html('Fail: ' + checkioInputStr);
                $content.find('.answer').html(result_message);
                $content.find('.answer').addClass('error');
                $content.find('.output').addClass('error');
                $content.find('.call').addClass('error');
            }
            else {
                $content.find('.call').html('Pass: ' + checkioInputStr);
                $content.find('.answer').remove();
            }

            if (result_code >= 5) {
                var canvas = new PuzzleCanvas($content.find(".explanation")[0]);
                canvas.prepare(checkioInput);
                canvas.run(userResult);
            }

            this_e.setAnimationHeight($content.height() + 60);

        });

        //This is for Tryit (but not necessary)
//        var $tryit;
//        ext.set_console_process_ret(function (this_e, ret) {
//            $tryit.find(".checkio-result").html("Result
" + ret);
//        });
//
//        ext.set_generate_animation_panel(function (this_e) {
//            $tryit = $(this_e.setHtmlTryIt(ext.get_template('tryit'))).find('.tryit-content');
//            $tryit.find('.bn-check').click(function (e) {
//                e.preventDefault();
//                this_e.sendToConsoleCheckiO("something");
//            });
//        });

        function PuzzleCanvas(dom) {
            var colorOrange4 = "#F0801A";
            var colorOrange3 = "#FA8F00";
            var colorOrange2 = "#FAA600";
            var colorOrange1 = "#FABA00";

            var colorBlue4 = "#294270";
            var colorBlue3 = "#006CA9";
            var colorBlue2 = "#65A1CF";
            var colorBlue1 = "#8FC7ED";

            var colorGrey4 = "#737370";
            var colorGrey3 = "#9D9E9E";
            var colorGrey2 = "#C5C6C6";
            var colorGrey1 = "#EBEDED";

            var colorWhite = "#FFFFFF";

            var marble = 20;

            var outerRing = marble * 5;
            var innerRing = marble * 3;

            var pad = 10;
            var size = 360 + 2 * pad;

            var paper = Raphael(dom, size, size);

            var ringsCentres = [
                [size / 2, size / 2],
                [pad + outerRing, pad + outerRing],
                [size - pad - outerRing, pad + outerRing],
                [pad + outerRing, size - pad - outerRing],
                [size - pad - outerRing, size - pad - outerRing]
            ];

            var shift = "T0," + (outerRing + innerRing);

            var positionsAct = [
                "R-90," + ringsCentres[1][0] + "," + ringsCentres[1][1],
                "R90," + ringsCentres[2][0] + "," + ringsCentres[2][1],
                "R180," + ringsCentres[1][0] + "," + ringsCentres[1][1],
                "",
                "R180," + ringsCentres[2][0] + "," + ringsCentres[2][1],
                "R90," + ringsCentres[1][0] + "," + ringsCentres[1][1],
                "R-90," + ringsCentres[2][0] + "," + ringsCentres[2][1],
                shift + "R180," + ringsCentres[3][0] + "," + ringsCentres[3][1],
                shift,
                shift + "R180," + ringsCentres[4][0] + "," + ringsCentres[4][1],
                shift + "R90," + ringsCentres[3][0] + "," + ringsCentres[3][1],
                shift + "R-90," + ringsCentres[4][0] + "," + ringsCentres[4][1]
            ];

            var attrBord = {"stroke": colorBlue4, "stroke-width": 3};

            var marbleColors = [colorGrey3, colorBlue1, "#66CC66", "#FF6666", colorOrange1];

            var holes = paper.set();

            var rings = paper.set();

            this.prepare = function (state) {
                for (var i = 1; i < 5; i++) {
                    paper.circle(ringsCentres[i][0], ringsCentres[i][1], innerRing).attr(
                        {"stroke": colorBlue4, "stroke-width": 3});
                    rings.push(paper.circle(ringsCentres[i][0], ringsCentres[i][1], outerRing).attr(
                        {"stroke": colorBlue4, "stroke-width": 3}));
                }
                for (i = 1; i < 5; i++) {
                    paper.circle(ringsCentres[i][0], ringsCentres[i][1], innerRing + marble).attr(
                        {"stroke": colorGrey1, "stroke-width": marble * 2 - 3});
                }

                var dots = Raphael.pathIntersection(
                    Raphael.format("M{0},{1}A{2},{2},0,1,1,{0},{3}",
                        ringsCentres[1][0], pad, outerRing, pad + outerRing * 2),
                    Raphael.format("M{0},{1}A{2},{2},0,1,0,{0},{3}",
                        ringsCentres[2][0], pad, outerRing, pad + outerRing * 2));
                for (i = 0; i < positionsAct.length; i++) {
                    var hole = paper.set();
                    hole.push(paper.path([
                        ["M", dots[0].x, dots[0].y],
                        ["A", outerRing, outerRing, 0, 0, 1, dots[1].x, dots[1].y],
                        ["A", outerRing, outerRing, 0, 0, 1, dots[0].x, dots[0].y],
                        ["Z"]]).attr(attrBord));
                    hole.push(paper.circle(size / 2, pad + outerRing, marble).attr(
                        {"stroke": colorBlue4, "stroke-width": 2, "fill": marbleColors[state[i]]}));
                    hole.transform(positionsAct[i]);
                    holes.push(hole);
                }

            };

            this.run = function(actions) {
                var i = 0;
                var ringsPositions = {
                    1: [0, 3, 5, 2],
                    2: [1, 4, 6, 3],
                    3: [5, 8, 10, 7],
                    4: [6, 9, 11, 8]
                };

                function rotate() {

                    if (i >= actions.length) {
                        return false;
                    }
                    var act = Number(actions[i]);
                    i++;
                    var wheel = paper.set();
                    var temp = holes[ringsPositions[act][0]];
                    for (var k = 0; k < 4; k++) {
                        wheel.push(temp);
                        var new_temp = holes[ringsPositions[act][(k+1)%4]];
                        holes[ringsPositions[act][(k+1)%4]] = temp;
                        temp = new_temp;
                    }
                    setTimeout(function() {
                        rings[act-1].toFront();
                        wheel.animate({"transform": "...R90," + ringsCentres[act][0] + "," + ringsCentres[act][1]},
                            1000, callback=function(){
                                rings[act-1].toBack();
                                rotate();
                            })}, 100);

                }

                setTimeout(rotate, 500);
            }

        }

    }
);
<commit_msg>update<commit_after>//Dont change it
requirejs(['ext_editor_1', 'jquery_190', 'raphael_210'],
    function (ext, $, TableComponent) {

        var cur_slide = {};

        ext.set_start_game(function (this_e) {
        });

        ext.set_process_in(function (this_e, data) {
            cur_slide["in"] = data[0];
        });

        ext.set_process_out(function (this_e, data) {
            cur_slide["out"] = data[0];
        });

        ext.set_process_ext(function (this_e, data) {
            cur_slide.ext = data;
            this_e.addAnimationSlide(cur_slide);
            cur_slide = {};
        });

        ext.set_process_err(function (this_e, data) {
            cur_slide['error'] = data[0];
            this_e.addAnimationSlide(cur_slide);
            cur_slide = {};
        });

        ext.set_animate_success_slide(function (this_e, options) {
            var $h = $(this_e.setHtmlSlide('

'));
            this_e.setAnimationHeight(115);
        });

        ext.set_animate_slide(function (this_e, data, options) {
            var $content = $(this_e.setHtmlSlide(ext.get_template('animation'))).find('.animation-content');
            if (!data) {
                console.log("data is undefined");
                return false;
            }

            //YOUR FUNCTION NAME
            var fname = 'puzzle88';

            var checkioInput = data.in || [0, 4, 3, 1, 0, 1, 4, 2, 3, 0, 2, 0];
            var checkioInputStr = fname + '((' + checkioInput.join(", ") + '))';

            var failError = function (dError) {
                $content.find('.call').html('Fail: ' + checkioInputStr);
                $content.find('.output').html(dError.replace(/\n/g, ","));

                $content.find('.output').addClass('error');
                $content.find('.call').addClass('error');
                $content.find('.answer').remove();
                $content.find('.explanation').remove();
                this_e.setAnimationHeight($content.height() + 60);
            };

            if (data.error) {
                failError(data.error);
                return false;
            }

            if (data.ext && data.ext.inspector_fail) {
                failError(data.ext.inspector_result_addon);
                return false;
            }

            var rightResult = data.ext["answer"];
            var userResult = data.out;
            var result = data.ext["result"];
            var result_code = data.ext["result_addon"][0];
            var result_message = data.ext["result_addon"][1];

            //if you need additional info from tests (if exists)
            var explanation = data.ext["explanation"];

            $content.find('.output').html(' Your result: ' + JSON.stringify(userResult));

            if (!result) {
                $content.find('.call').html('Fail: ' + checkioInputStr);
                $content.find('.answer').html(result_message);
                $content.find('.answer').addClass('error');
                $content.find('.output').addClass('error');
                $content.find('.call').addClass('error');
            }
            else {
                $content.find('.call').html('Pass: ' + checkioInputStr);
                $content.find('.answer').remove();
            }

            if (result_code >= 5) {
                var canvas = new PuzzleCanvas($content.find(".explanation")[0]);
                canvas.prepare(checkioInput);
                canvas.run(userResult);
            }

            this_e.setAnimationHeight($content.height() + 60);

        });

        //This is for Tryit (but not necessary)
//        var $tryit;
//        ext.set_console_process_ret(function (this_e, ret) {
//            $tryit.find(".checkio-result").html("Result
" + ret);
//        });
//
//        ext.set_generate_animation_panel(function (this_e) {
//            $tryit = $(this_e.setHtmlTryIt(ext.get_template('tryit'))).find('.tryit-content');
//            $tryit.find('.bn-check').click(function (e) {
//                e.preventDefault();
//                this_e.sendToConsoleCheckiO("something");
//            });
//        });

        function PuzzleCanvas(dom) {
            var colorOrange4 = "#F0801A";
            var colorOrange3 = "#FA8F00";
            var colorOrange2 = "#FAA600";
            var colorOrange1 = "#FABA00";

            var colorBlue4 = "#294270";
            var colorBlue3 = "#006CA9";
            var colorBlue2 = "#65A1CF";
            var colorBlue1 = "#8FC7ED";

            var colorGrey4 = "#737370";
            var colorGrey3 = "#9D9E9E";
            var colorGrey2 = "#C5C6C6";
            var colorGrey1 = "#EBEDED";

            var colorWhite = "#FFFFFF";

            var marble = 20;

            var outerRing = marble * 5;
            var innerRing = marble * 3;

            var pad = 10;
            var size = 360 + 2 * pad;

            var paper = Raphael(dom, size, size);

            var ringsCentres = [
                [size / 2, size / 2],
                [pad + outerRing, pad + outerRing],
                [size - pad - outerRing, pad + outerRing],
                [pad + outerRing, size - pad - outerRing],
                [size - pad - outerRing, size - pad - outerRing]
            ];

            var shift = "T0," + (outerRing + innerRing);

            var positionsAct = [
                "R-90," + ringsCentres[1][0] + "," + ringsCentres[1][1],
                "R90," + ringsCentres[2][0] + "," + ringsCentres[2][1],
                "R180," + ringsCentres[1][0] + "," + ringsCentres[1][1],
                "",
                "R180," + ringsCentres[2][0] + "," + ringsCentres[2][1],
                "R90," + ringsCentres[1][0] + "," + ringsCentres[1][1],
                "R-90," + ringsCentres[2][0] + "," + ringsCentres[2][1],
                shift + "R180," + ringsCentres[3][0] + "," + ringsCentres[3][1],
                shift,
                shift + "R180," + ringsCentres[4][0] + "," + ringsCentres[4][1],
                shift + "R90," + ringsCentres[3][0] + "," + ringsCentres[3][1],
                shift + "R-90," + ringsCentres[4][0] + "," + ringsCentres[4][1]
            ];

            var attrBord = {"stroke": colorBlue4, "stroke-width": 3};

            var marbleColors = [colorGrey3, colorBlue1, "#66CC66", "#FF6666", colorOrange1];

            var holes = paper.set();

            var rings = paper.set();

            this.prepare = function (state) {
                for (var i = 1; i < 5; i++) {
                    paper.circle(ringsCentres[i][0], ringsCentres[i][1], innerRing).attr(
                        {"stroke": colorBlue4, "stroke-width": 3});
                    rings.push(paper.circle(ringsCentres[i][0], ringsCentres[i][1], outerRing).attr(
                        {"stroke": colorBlue4, "stroke-width": 3}));
                }
                for (i = 1; i < 5; i++) {
                    paper.circle(ringsCentres[i][0], ringsCentres[i][1], innerRing + marble).attr(
                        {"stroke": colorGrey1, "stroke-width": marble * 2 - 3});
                    paper.text(ringsCentres[i][0], ringsCentres[i][1], i).attr(
                        {"stroke": colorBlue4, "fill": colorBlue4,
                            "font-family": "Roboto", "font-weight": "bold", "font-size": outerRing});
                }

                var dots = Raphael.pathIntersection(
                    Raphael.format("M{0},{1}A{2},{2},0,1,1,{0},{3}",
                        ringsCentres[1][0], pad, outerRing, pad + outerRing * 2),
                    Raphael.format("M{0},{1}A{2},{2},0,1,0,{0},{3}",
                        ringsCentres[2][0], pad, outerRing, pad + outerRing * 2));
                for (i = 0; i < positionsAct.length; i++) {
                    var hole = paper.set();
                    hole.push(paper.path([
                        ["M", dots[0].x, dots[0].y],
                        ["A", outerRing, outerRing, 0, 0, 1, dots[1].x, dots[1].y],
                        ["A", outerRing, outerRing, 0, 0, 1, dots[0].x, dots[0].y],
                        ["Z"]]).attr(attrBord));
                    hole.push(paper.circle(size / 2, pad + outerRing, marble).attr(
                        {"stroke": colorBlue4, "stroke-width": 2, "fill": marbleColors[state[i]]}));
                    hole.transform(positionsAct[i]);
                    holes.push(hole);
                }

            };

            this.run = function(actions) {
                var i = 0;
                var ringsPositions = {
                    1: [0, 3, 5, 2],
                    2: [1, 4, 6, 3],
                    3: [5, 8, 10, 7],
                    4: [6, 9, 11, 8]
                };

                function rotate() {

                    if (i >= actions.length) {
                        return false;
                    }
                    var act = Number(actions[i]);
                    i++;
                    var wheel = paper.set();
                    var temp = holes[ringsPositions[act][0]];
                    for (var k = 0; k < 4; k++) {
                        wheel.push(temp);
                        var new_temp = holes[ringsPositions[act][(k+1)%4]];
                        holes[ringsPositions[act][(k+1)%4]] = temp;
                        temp = new_temp;
                    }
                    setTimeout(function() {
                        rings[act-1].toFront();
                        wheel.animate({"transform": "...R90," + ringsCentres[act][0] + "," + ringsCentres[act][1]},
                            1000, callback=function(){
                                rings[act-1].toBack();
                                rotate();
                            })}, 100);

                }

                setTimeout(rotate, 500);
            }

        }

    }
);
<|endoftext|>


<commit_before>define([
    'base/js/namespace',
    'base/js/events',
    'notebook/js/codecell',
    'jquery'
], function (
    Jupyter,
    events,
    codecell,
    $
){
    'use strict';

    var CodeCell = codecell.CodeCell;

    function patch_CodeCell_execute () {
        console.log('[Freeze] patching CodeCell.prototype.execute')
        var old_execute = CodeCell.prototype.execute;

        CodeCell.prototype.execute = function () {
            if (this.metadata.run_control === undefined ||
                !this.metadata.run_control.frozen
            ) {
                old_execute.apply(this, arguments);
            }
        }
    }

    function set_state(cell, state) {
        if (cell instanceof CodeCell) {
            if (cell.metadata.run_control === undefined)
                cell.metadata.run_control = {};
            if (state === undefined)
                state = 'normal';
            switch(state) {
                case 'normal':
                    var new_run_control_values = {
                        read_only : false,
                        frozen : false
                    };
                    var bg = "";
                    break;
                case 'read_only':
                    var new_run_control_values = {
                            read_only : true,
                            frozen : false
                    };
                    var bg = "#FFFEF0";
                    break;
                case 'frozen':
                    var new_run_control_values = {
                        read_only : true,
                        frozen : true
                    };
                    var bg = "#f0feff";
                    break;
            }
            $.extend(cell.metadata.run_control, new_run_control_values);
            cell.code_mirror.setOption('readOnly', cell.metadata.run_control.read_only);
            var prompt = cell.element.find('div.input_area');
            prompt.css("background-color", bg);
        }
    }

    function set_state_selected (state) {
        var cells = Jupyter.notebook.get_selected_cells();
        for (var i = 0; i < cells.length; i++) {
            set_state(cells[i], state)
        }
    }

    function make_normal_selected () {
        set_state_selected('normal');
    }

    function make_read_only_selected () {
        set_state_selected('read_only');
    }

    function make_frozen_selected () {
        set_state_selected('frozen');
    }

    function initialize_states () {
        var cells = Jupyter.notebook.get_cells();
        for (var i in cells) {
            var cell = cells[i];
            if (cell instanceof CodeCell) {
                var state = 'normal';
                if (cell.metadata.run_control != undefined && cell.metadata.run_control.read_only) {
                    state = cell.metadata.run_control.frozen ? 'frozen' : 'read_only';
                }
                set_state(cell, state);
            }
        }
    }

    function load_extension () {
        Jupyter.toolbar.add_buttons_group([
            {
                id : 'make_normal',
                label : 'lift restrictions from selected cells',
                icon : 'fa-unlock-alt',
                callback : make_normal_selected
            },
            {
                id : 'make_read_only',
                label : 'make selected cells read-only',
                icon: 'fa-lock',
                callback : make_read_only_selected
            },
            {
                id : 'freeze_cells',
                label : 'freeze selected cells',
                icon : 'fa-asterisk',
                callback : make_frozen_selected
            }
        ]);

        if (typeof Jupyter.notebook === "undefined") {
            events.on("notebook_loaded.Notebook", initialize_states)
        } else {
            initialize_states();
        }

        patch_CodeCell_execute();
    }

    return {
        load_jupyter_extension : load_extension,
        load_ipython_extension : load_extension
    }
});
<commit_msg>Extend functionality to work with Markdown cells<commit_after>define([
    'base/js/namespace',
    'base/js/events',
    'notebook/js/codecell',
    'notebook/js/textcell',
    'jquery'
], function (
    Jupyter,
    events,
    codecell,
    textcell,
    $
){
    'use strict';

    var CodeCell = codecell.CodeCell;
    var MarkdownCell = textcell.MarkdownCell;

    function patch_MarkdownCell_unrender () {
        console.log('[Freeze] patching MarkdownCell.prototype.unrender');
        var old_unrender = MarkdownCell.prototype.unrender;

        MarkdownCell.prototype.unrender = function () {
            // console.log('[Freeze] patched unrender applied');
            if (this.metadata.run_control === undefined ||
                !this.metadata.run_control.frozen
            ) {
                old_unrender.apply(this, arguments);
            }
        }
    }

    function patch_CodeCell_execute () {
        console.log('[Freeze] patching CodeCell.prototype.execute');
        var old_execute = CodeCell.prototype.execute;

        CodeCell.prototype.execute = function () {
            if (this.metadata.run_control === undefined ||
                !this.metadata.run_control.frozen
            ) {
                old_execute.apply(this, arguments);
            }
        }
    }

    function set_state(cell, state) {
        if (cell instanceof CodeCell || cell instanceof MarkdownCell) {
            if (cell.metadata.run_control === undefined)
                cell.metadata.run_control = {};
            if (state === undefined)
                state = 'normal';
            switch(state) {
                case 'normal':
                    var new_run_control_values = {
                        read_only : false,
                        frozen : false
                    };
                    var bg = "";
                    break;
                case 'read_only':
                    var new_run_control_values = {
                            read_only : true,
                            frozen : false
                    };
                    var bg = "#FFFEF0";
                    break;
                case 'frozen':
                    var new_run_control_values = {
                        read_only : true,
                        frozen : true
                    };
                    var bg = "#f0feff";
                    break;
            }
            $.extend(cell.metadata.run_control, new_run_control_values);
            cell.code_mirror.setOption('readOnly', cell.metadata.run_control.read_only);
            var prompt = cell.element.find('div.input_area');
            prompt.css("background-color", bg);
        }
    }

    function set_state_selected (state) {
        var cells = Jupyter.notebook.get_selected_cells();
        for (var i = 0; i < cells.length; i++) {
            set_state(cells[i], state)
        }
    }

    function make_normal_selected () {
        set_state_selected('normal');
    }

    function make_read_only_selected () {
        set_state_selected('read_only');
    }

    function make_frozen_selected () {
        set_state_selected('frozen');
    }

    function initialize_states () {
        var cells = Jupyter.notebook.get_cells();
        for (var i in cells) {
            var cell = cells[i];
            if (cell instanceof CodeCell || cell instanceof MarkdownCell) {
                var state = 'normal';
                if (cell.metadata.run_control != undefined && cell.metadata.run_control.read_only) {
                    state = cell.metadata.run_control.frozen ? 'frozen' : 'read_only';
                }
                set_state(cell, state);
            }
        }
    }

    function load_extension () {
        Jupyter.toolbar.add_buttons_group([
            {
                id : 'make_normal',
                label : 'lift restrictions from selected cells',
                icon : 'fa-unlock-alt',
                callback : make_normal_selected
            },
            {
                id : 'make_read_only',
                label : 'make selected cells read-only',
                icon: 'fa-lock',
                callback : make_read_only_selected
            },
            {
                id : 'freeze_cells',
                label : 'freeze selected cells',
                icon : 'fa-asterisk',
                callback : make_frozen_selected
            }
        ]);

        if (typeof Jupyter.notebook === "undefined") {
            events.on("notebook_loaded.Notebook", initialize_states)
        } else {
            initialize_states();
        }

        patch_CodeCell_execute();
        patch_MarkdownCell_unrender();
    }

    return {
        load_jupyter_extension : load_extension,
        load_ipython_extension : load_extension
    }
});
<|endoftext|>


<commit_before>(function() {
    'use strict';

    /**
     * @ngdoc function
     * @name crowbarApp.controller:Upgrade7BackupController
     * @description
     * # Upgrade7BackupController
     * This is the controller used on the Upgrade landing page
     */
    angular.module('crowbarApp')
        .controller('Upgrade7BackupController', Upgrade7BackupController);

    Upgrade7BackupController.$inject = ['$translate', '$state', 'upgradeBackupFactory'];
    // @ngInject
    function Upgrade7BackupController($translate, $state, upgradeBackupFactory) {
        var vm = this;
        vm.backup = {
            completed: false,
            create: createBackup
        };

        function createBackup() {

            var zip_file_path = 'http://www.colorado.edu/conflict/peace/download/peace.zip',
                zip_file_name = 'peaceNew.zip'

            var anchor = angular.element('<a/>');
            anchor.attr({
                href: zip_file_path,
                download: zip_file_name
            })[0].click();

            upgradeBackupFactory.create()
                .then(
                    // When Backup Data has been created successfully
                    function (backupData) {
                        vm.backup.file = backupData;
                    },
                    // In case of backup error
                    function (error) {
                        vm.backup.error = error;
                    }
                )
                .finally(function () {
                    vm.backup.completed = true;
                });
        }

    }
})();
<commit_msg>Modified download code<commit_after>(function() {
    'use strict';

    /**
     * @ngdoc function
     * @name crowbarApp.controller:Upgrade7BackupController
     * @description
     * # Upgrade7BackupController
     * This is the controller used on the Upgrade landing page
     */
    angular.module('crowbarApp')
        .controller('Upgrade7BackupController', Upgrade7BackupController);

    Upgrade7BackupController.$inject = ['$translate', '$state', 'upgradeBackupFactory', '$document'];
    // @ngInject
    function Upgrade7BackupController($translate, $state, upgradeBackupFactory, $document) {
        var vm = this;
        vm.backup = {
            completed: false,
            create: createBackup
        };

        function createBackup() {

            var zip_file_path = 'http://www.colorado.edu/conflict/peace/download/peace.zip',
                zip_file_name = 'peaceNew.zip',
                a = $document[0].createElement('a');

            a.href = zip_file_path;
            a.download = zip_file_name;
            a.click();

            upgradeBackupFactory.create()
                .then(
                    // When Backup Data has been created successfully
                    function (backupData) {
                        vm.backup.file = backupData;
                    },
                    // In case of backup error
                    function (error) {
                        vm.backup.error = error;
                    }
                )
                .finally(function () {
                    vm.backup.completed = true;
                });
        }

    }
})();
<|endoftext|>


<commit_before>/*
 *
 * Copyright 2013 Canonical Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   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.
 *
*/

/* jshint laxcomma:true, sub:true */

function replaceAt(str, index, char) {
    return str.substr(0, index) + char + str.substr(index + char.length);
}

function toCamelCase(str) {
    return str.split('-').map(function(str) {
        return replaceAt(str, 0, str[0].toUpperCase());
    }).join('');
}

var shell = require('shelljs')
   , fs = require('fs')
   , path = require('path')
   , common = require('./common')
   , events = require('../../events')
   , xml_helpers = require(path.join(__dirname, '..', '..', 'util', 'xml-helpers'));

module.exports = {
    www_dir:function(project_dir) {
        return path.join(project_dir, 'www');
    },

    package_name:function (project_dir) {
        var config_path = path.join(project_dir, 'config.xml');
        var widget_doc = xml_helpers.parseElementtreeSync(config_path);
        return widget_doc._root.attrib['id'];
    },
    'source-file':{
        install:function(obj, plugin_dir, project_dir, plugin_id, options) {
            var dest = path.join('build', 'src', 'plugins', plugin_id, path.basename(obj.src));
            common.copyFile(plugin_dir, obj.src, project_dir, dest);

            var cmake = path.join(project_dir, 'build', 'CMakeLists.txt');
            shell.exec('touch ' + cmake);
        },
        uninstall:function(obj, project_dir, plugin_id, options) {
            var dest = path.join(project_dir, 'build', 'src', 'plugins', plugin_id);
            shell.rm(path.join(dest, path.basename(obj.src)));

            var cmake = path.join(project_dir, 'build', 'CMakeLists.txt');
            shell.exec('touch ' + cmake);
        }
    },
    'header-file':{
        install:function(obj, plugin_dir, project_dir, plugin_id, options) {
            var dest = path.join('build', 'src', 'plugins', plugin_id, path.basename(obj.src));
            common.copyFile(plugin_dir, obj.src, project_dir, dest);

            var plugins = path.join(project_dir, 'build', 'src', 'coreplugins.cpp');
            var src = String(fs.readFileSync(plugins));

            src = src.replace('INSERT_HEADER_HERE', '#include "plugins/' + plugin_id + '/' + path.basename(obj.src) +'"\nINSERT_HEADER_HERE');
            var class_name;
            if (plugin_id.match(/\.[^.]+$/)) {
            // old-style plugin name
                class_name = plugin_id.match(/\.[^.]+$/)[0].substr(1);
            } else {
               class_name = plugin_id.match(/\-[^\-]+$/)[0].substr(1);
            }
            class_name = toCamelCase(class_name);
            src = src.replace('INSERT_PLUGIN_HERE', 'INIT_PLUGIN(' + class_name + ');INSERT_PLUGIN_HERE');

            fs.writeFileSync(plugins, src);
        },
        uninstall:function(obj, project_dir, plugin_id, options) {
            var dest = path.join(project_dir, 'build', 'src', 'plugins', plugin_id);
            shell.rm(path.join(dest, path.basename(obj.src)));

            var plugins = path.join(project_dir, 'build', 'src', 'coreplugins.cpp');
            var src = String(fs.readFileSync(plugins));

            src = src.replace('#include "plugins/' + plugin_id + '/' + path.basename(obj.src) +'"', '');
            var class_name;
            if (plugin_id.match(/\.[^.]+$/)) {
                // old-style plugin name
                class_name = plugin_id.match(/\.[^.]+$/)[0].substr(1);
            } else {
                class_name = plugin_id.match(/\-[^\-]+$/)[0].substr(1);
            }
            class_name = toCamelCase(class_name);
            src = src.replace('INIT_PLUGIN(' + class_name + ');', '');

            fs.writeFileSync(plugins, src);
        }
    },
    'resource-file':{
        install:function(obj, plugin_dir, project_dir, plugin_id, options) {
            var dest = path.join('qml', path.basename(obj.src));
            if (obj.targetDir)
                dest = path.join(obj.targetDir, path.basename(obj.src));
            common.copyFile(plugin_dir, obj.src, project_dir, dest);
        },
        uninstall:function(obj, project_dir, plugin_id, options) {
            var dest = path.join(project_dir, 'qml');
            if (obj.targetDir)
                dest = path.join(project_dir, obj.targetDir);
            shell.rm(path.join(dest, path.basename(obj.src)));
        }
    },
    'framework': {
        install:function(obj, plugin_dir, project_dir, plugin_id, options) {
            events.emit('verbose', 'framework.install is not supported for ubuntu');
        },
        uninstall:function(obj, project_dir, plugin_id, options) {
            events.emit('verbose', 'framework.uninstall is not supported for ubuntu');
        }
    },
    'lib-file': {
        install:function(obj, plugin_dir, project_dir, plugin_id, options) {
            events.emit('verbose', 'lib-file.install is not supported for ubuntu');
        },
        uninstall:function(obj, project_dir, plugin_id, options) {
            events.emit('verbose', 'lib-file.uninstall is not supported for ubuntu');
        }
    }
};
<commit_msg>more robust class name detection<commit_after>/*
 *
 * Copyright 2013 Canonical Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   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.
 *
*/

/* jshint laxcomma:true, sub:true */

function replaceAt(str, index, char) {
    return str.substr(0, index) + char + str.substr(index + char.length);
}

function toCamelCase(str) {
    return str.split('-').map(function(str) {
        return replaceAt(str, 0, str[0].toUpperCase());
    }).join('');
}

function findClassName(str) {
    var class_name;

    if (str.match(/\.[^.]+$/)) {
        // old-style plugin name
        class_name = str.match(/\.[^.]+$/)[0].substr(1);
    } else {
        class_name = str.match(/cordova\-plugin\-([\w\-]+)$/)[0].substr(15);
    }

    return class_name;
}

var shell = require('shelljs')
   , fs = require('fs')
   , path = require('path')
   , common = require('./common')
   , events = require('../../events')
   , xml_helpers = require(path.join(__dirname, '..', '..', 'util', 'xml-helpers'));

module.exports = {
    www_dir:function(project_dir) {
        return path.join(project_dir, 'www');
    },

    package_name:function (project_dir) {
        var config_path = path.join(project_dir, 'config.xml');
        var widget_doc = xml_helpers.parseElementtreeSync(config_path);
        return widget_doc._root.attrib['id'];
    },
    'source-file':{
        install:function(obj, plugin_dir, project_dir, plugin_id, options) {
            var dest = path.join('build', 'src', 'plugins', plugin_id, path.basename(obj.src));
            common.copyFile(plugin_dir, obj.src, project_dir, dest);

            var cmake = path.join(project_dir, 'build', 'CMakeLists.txt');
            shell.exec('touch ' + cmake);
        },
        uninstall:function(obj, project_dir, plugin_id, options) {
            var dest = path.join(project_dir, 'build', 'src', 'plugins', plugin_id);
            shell.rm(path.join(dest, path.basename(obj.src)));

            var cmake = path.join(project_dir, 'build', 'CMakeLists.txt');
            shell.exec('touch ' + cmake);
        }
    },
    'header-file':{
        install:function(obj, plugin_dir, project_dir, plugin_id, options) {
            var dest = path.join('build', 'src', 'plugins', plugin_id, path.basename(obj.src));
            common.copyFile(plugin_dir, obj.src, project_dir, dest);

            var plugins = path.join(project_dir, 'build', 'src', 'coreplugins.cpp');
            var src = String(fs.readFileSync(plugins));

            src = src.replace('INSERT_HEADER_HERE', '#include "plugins/' + plugin_id + '/' + path.basename(obj.src) +'"\nINSERT_HEADER_HERE');
            var class_name = findClassName(plugin_id);
            class_name = toCamelCase(class_name);
            src = src.replace('INSERT_PLUGIN_HERE', 'INIT_PLUGIN(' + class_name + ');INSERT_PLUGIN_HERE');

            fs.writeFileSync(plugins, src);
        },
        uninstall:function(obj, project_dir, plugin_id, options) {
            var dest = path.join(project_dir, 'build', 'src', 'plugins', plugin_id);
            shell.rm(path.join(dest, path.basename(obj.src)));

            var plugins = path.join(project_dir, 'build', 'src', 'coreplugins.cpp');
            var src = String(fs.readFileSync(plugins));

            src = src.replace('#include "plugins/' + plugin_id + '/' + path.basename(obj.src) +'"', '');
            var class_name = findClassName(plugin_id);
            class_name = toCamelCase(class_name);
            src = src.replace('INIT_PLUGIN(' + class_name + ');', '');

            fs.writeFileSync(plugins, src);
        }
    },
    'resource-file':{
        install:function(obj, plugin_dir, project_dir, plugin_id, options) {
            var dest = path.join('qml', path.basename(obj.src));
            if (obj.targetDir)
                dest = path.join(obj.targetDir, path.basename(obj.src));
            common.copyFile(plugin_dir, obj.src, project_dir, dest);
        },
        uninstall:function(obj, project_dir, plugin_id, options) {
            var dest = path.join(project_dir, 'qml');
            if (obj.targetDir)
                dest = path.join(project_dir, obj.targetDir);
            shell.rm(path.join(dest, path.basename(obj.src)));
        }
    },
    'framework': {
        install:function(obj, plugin_dir, project_dir, plugin_id, options) {
            events.emit('verbose', 'framework.install is not supported for ubuntu');
        },
        uninstall:function(obj, project_dir, plugin_id, options) {
            events.emit('verbose', 'framework.uninstall is not supported for ubuntu');
        }
    },
    'lib-file': {
        install:function(obj, plugin_dir, project_dir, plugin_id, options) {
            events.emit('verbose', 'lib-file.install is not supported for ubuntu');
        },
        uninstall:function(obj, project_dir, plugin_id, options) {
            events.emit('verbose', 'lib-file.uninstall is not supported for ubuntu');
        }
    }
};
<|endoftext|>