<commit_before>// @flow
import React from 'react'
import {ScrollView} from 'glamorous-native'
import {Markdown} from '../components/markdown'
import LoadingView from '../components/loading'
import {text} from '../../../docs/faqs.json'
import {tracker} from '../../analytics'
import bugsnag from '../../bugsnag'

const faqsUrl = 'https://stodevx.github.io/AAO-React-Native/faqs.json'

export class FaqView extends React.PureComponent {
  static navigationOptions = {
    title: 'FAQs',
  }

  state = {
    text: text,
  }

  componentWillMount() {
    this.fetchData()
  }

  fetchData = async () => {
    let fetched = text
    try {
      let blob: {text: string} = await fetchJson(faqsUrl)
      fetched = blob.text
    } catch (err) {
      tracker.trackException(err.message)
      bugsnag.notify(err)
      console.warn(err.message)
    }

    if (process.env.NODE_ENV === 'development') {
      fetched = text
    }

    this.setState({text: fetched})
  }

  render() {
    if (!this.state.text) {
      return <LoadingView />
    }

    return (
      <ScrollView paddingHorizontal={15}>
        <Markdown source={text} />
      </ScrollView>
    )
  }
}
<commit_msg>Refresh spinner on faq list<commit_after>// @flow
import React from 'react'
import {RefreshControl} from 'react-native'
import {ScrollView} from 'glamorous-native'
import {Markdown} from '../components/markdown'
import LoadingView from '../components/loading'
import {text} from '../../../docs/faqs.json'
import {tracker} from '../../analytics'
import bugsnag from '../../bugsnag'
import delay from 'delay'

const faqsUrl = 'https://stodevx.github.io/AAO-React-Native/faqs.json'

export class FaqView extends React.PureComponent {
  static navigationOptions = {
    title: 'FAQs',
  }

  state = {
    text: text,
    refreshing: false,
  }

  componentWillMount() {
    this.fetchData()
  }

  fetchData = async () => {
    let fetched = text
    try {
      let blob: {text: string} = await fetchJson(faqsUrl)
      fetched = blob.text
    } catch (err) {
      tracker.trackException(err.message)
      bugsnag.notify(err)
      console.warn(err.message)
    }

    if (process.env.NODE_ENV === 'development') {
      fetched = text
    }

    this.setState({text: fetched})
  }

  refresh = async () => {
    const start = Date.now()
    this.setState(() => ({refreshing: true}))

    await this.fetchData()

    // wait 0.5 seconds – if we let it go at normal speed, it feels broken.
    const elapsed = Date.now() - start
    if (elapsed < 500) {
      await delay(500 - elapsed)
    }
    this.setState(() => ({refreshing: false}))
  }

  render() {
    if (!this.state.text) {
      return <LoadingView />
    }

    const refreshControl = (
      <RefreshControl
        refreshing={this.state.refreshing}
        onRefresh={this.refresh}
      />
    )

    return (
      <ScrollView refreshControl={refreshControl} paddingHorizontal={15}>
        <Markdown source={text} />
      </ScrollView>
    )
  }
}
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import LndSyncing from 'components/LndSyncing'
import GlobalError from 'components/GlobalError'
import LoadingBolt from 'components/LoadingBolt'
import Form from 'components/Form'
import ModalRoot from 'components/ModalRoot'
import Nav from 'components/Nav'
import Wallet from 'components/Wallet'
import styles from './App.scss'

class App extends Component {
  componentWillMount() {
    const { fetchTicker, fetchBalance, fetchInfo, newAddress, lnd: { syncing } } = this.props

    fetchTicker()
    fetchBalance()
    fetchInfo()
    newAddress('p2pkh')
  }

  render() {
    const {
      lnd,
      syncPercentage,
      fetchBlockHeight,

      modal: { modalType, modalProps },
      hideModal,
      ticker,
      currentTicker,
      address: { address },
      balance,
      info,
      form,

      openPayForm,
      openRequestForm,
      formProps,
      closeForm,

      error: { error },
      clearError,

      children
    } = this.props

    if (!currentTicker || balance.balanceLoading) {
      return <LoadingBolt />
    }

    return (

        <GlobalError error={error} clearError={clearError} />
        <ModalRoot
          modalType={modalType}
          modalProps={modalProps}
          hideModal={hideModal}
          currentTicker={currentTicker}
          currency={ticker.currency}
        />

        <Form formType={form.formType} formProps={formProps} closeForm={closeForm} />

          <Wallet
            balance={balance}
            address={address}
            info={info}
          />
          {children}

    )
  }
}

App.propTypes = {
  lnd: PropTypes.object.isRequired,

  syncPercentage: PropTypes.number.isRequired,
  fetchBlockHeight: PropTypes.func.isRequired,

  modal: PropTypes.object.isRequired,
  ticker: PropTypes.object.isRequired,
  address: PropTypes.object.isRequired,
  balance: PropTypes.object.isRequired,
  info: PropTypes.object.isRequired,
  form: PropTypes.object.isRequired,
  formProps: PropTypes.object.isRequired,
  closeForm: PropTypes.func.isRequired,
  error: PropTypes.object.isRequired,

  newAddress: PropTypes.func.isRequired,
  fetchInfo: PropTypes.func.isRequired,
  hideModal: PropTypes.func.isRequired,
  fetchTicker: PropTypes.func.isRequired,
  fetchBalance: PropTypes.func.isRequired,
  openPayForm: PropTypes.func.isRequired,
  openRequestForm: PropTypes.func.isRequired,
  clearError: PropTypes.func.isRequired,

  currentTicker: PropTypes.object,

  children: PropTypes.object.isRequired
}

export default App
<commit_msg>fix merge conflicts<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import LndSyncing from 'components/LndSyncing'
import GlobalError from 'components/GlobalError'
import LoadingBolt from 'components/LoadingBolt'
import Form from 'components/Form'
import ModalRoot from 'components/ModalRoot'
import Nav from 'components/Nav'
import Wallet from 'components/Wallet'
import styles from './App.scss'

class App extends Component {
  componentWillMount() {
    const { fetchTicker, fetchBalance, fetchInfo, newAddress, lnd: { syncing } } = this.props

    fetchTicker()
    fetchBalance()
    fetchInfo()
    newAddress('p2pkh')
  }

  render() {
    const {
      lnd,
      syncPercentage,
      fetchBlockHeight,

      modal: { modalType, modalProps },
      hideModal,
      ticker,
      currentTicker,
      address: { address },
      balance,
      info,
      form,

      openPayForm,
      openRequestForm,
      formProps,
      closeForm,

      error: { error },
      clearError,

      children
    } = this.props

    if (!currentTicker || balance.balanceLoading) { return <LoadingBolt /> }

    return (

        <GlobalError error={error} clearError={clearError} />
        <ModalRoot
          modalType={modalType}
          modalProps={modalProps}
          hideModal={hideModal}
          currentTicker={currentTicker}
          currency={ticker.currency}
        />

        <Form formType={form.formType} formProps={formProps} closeForm={closeForm} />

          <Wallet
            balance={balance}
            address={address}
            info={info}
          />
          {children}

    )
  }
}

App.propTypes = {
  lnd: PropTypes.object.isRequired,

  syncPercentage: PropTypes.number.isRequired,
  fetchBlockHeight: PropTypes.func.isRequired,

  modal: PropTypes.object.isRequired,
  ticker: PropTypes.object.isRequired,
  address: PropTypes.object.isRequired,
  balance: PropTypes.object.isRequired,
  info: PropTypes.object.isRequired,
  form: PropTypes.object.isRequired,
  formProps: PropTypes.object.isRequired,
  closeForm: PropTypes.func.isRequired,
  error: PropTypes.object.isRequired,

  newAddress: PropTypes.func.isRequired,
  fetchInfo: PropTypes.func.isRequired,
  hideModal: PropTypes.func.isRequired,
  fetchTicker: PropTypes.func.isRequired,
  fetchBalance: PropTypes.func.isRequired,
  openPayForm: PropTypes.func.isRequired,
  openRequestForm: PropTypes.func.isRequired,
  clearError: PropTypes.func.isRequired,

  currentTicker: PropTypes.object,

  children: PropTypes.object.isRequired
}

export default App
<|endoftext|>


<commit_before>'use strict';

const chalk = require('chalk');
const emoji = require('node-emoji');
const ProgressBar = require('progress');
const imgcat = require('imgcat');
const semver = require('semver');
const osascripts = require('../osascripts/index');

const SearchResultPrinters = {
	'albums': albumPrinterFn,
	'artists': artistPrinterFn,
	'playlists': playlistPrinterFn,
	'tracks': trackPrinterFn
};

function warning(m){
	console.log(
		chalk.yellow(m)
	);
}

function error(e){
	console.log(
		chalk.red(e)
	);
}

function albumPrinterFn(data){
	data.forEach((result) => {
		console.log(
			chalk.green(result.resultIndex + ': ') +
			chalk.blue('Album: ') +
			chalk.green(result.albumName)  +
			chalk.blue(' Artist: ') +
			chalk.green(result.artistNames)
		);
	});
}

function artistPrinterFn(data){
	data.forEach((result) => {
		console.log(
			chalk.green(result.resultIndex + ': ') +
			chalk.blue('Artist: ') +
			chalk.green(result.name)  +
			chalk.blue(' Followers: ') +
			chalk.green(result.followers)
		);
	});
}

function playlistPrinterFn(data){
	data.forEach((result) => {
		console.log(
			chalk.green(result.resultIndex + ': ') +
			chalk.blue('Playlist: ') +
			chalk.green(result.name)  +
			chalk.blue(' Tracks: ') +
			chalk.green(result.noOfTracks)
		);
	});
}

function trackPrinterFn(data){
	data.forEach((result) => {
		console.log(
			chalk.green(result.resultIndex + ': ') +
			chalk.blue('Track: ') +
			chalk.green(result.trackName + ' (' + result.duration + ')')  +
			chalk.blue(' Artist: ') +
			chalk.green(result.artistNames) +
			chalk.blue(' Album: ') +
			chalk.green(result.albumName)
		);
	});
}

function printSearchResults(resultType, data){
	if(SearchResultPrinters[resultType]){
		return SearchResultPrinters[resultType](data);
	}
	else {
		throw new Error(`${resultType} can not be printed.`);
	}
}

function printDurationProgress(result){
	var statusButton = result.status === 'playing' ? ':arrow_forward:' : ':double_vertical_bar:';
	statusButton = emoji.emojify(statusButton);
	new ProgressBar(`${statusButton}  ${result.status} [:bar] ${result.position} of ${result.duration}`, {
		complete: '=',
		incomplete: ' ',
		width: 50,
		total: result.durationSecs
	}).tick(result.positionSecs);
	console.log();
}

function printPlayerStatus(result){
	var artist = `:microphone:  ${chalk.green('Artist:')} ${chalk.green(result.artist)}`;
	var track = `:musical_score:  ${chalk.green('Track:')} ${chalk.green(result.track)}`;
	var album = `:cd:  ${chalk.green('Album:')} ${chalk.green(result.album)}`;
	console.log(emoji.emojify(artist));
	console.log(emoji.emojify(track));
	console.log(emoji.emojify(album));
	console.log();
	printDurationProgress(result);
	printArtwork();
}

function printNext(result){
	var nextTrack = `:fast_forward:  Playing next track: ${chalk.green(result.track)} :musical_score:`;
	console.log(emoji.emojify(nextTrack));
	console.log();
	printPlayerStatus(result);
}

function printPrevious(result){
	var previousTrack = `:rewind:  Playing previous track: ${chalk.green(result.track)} :musical_score:`;
	console.log(emoji.emojify(previousTrack));
	console.log();
	printPlayerStatus(result);
}

function printVolume(volume){
	new ProgressBar(`Volume: [:bar] ${chalk.green(volume)}`, {
		complete: '=',
		incomplete: ' ',
		width: 50,
		total: 100
	}).tick(volume);
	console.log();
}

function printMute(volume){
	var mute = `:no_bell:  Spotify muted.`;
	console.log(emoji.emojify(mute));
	printVolume(volume);
}

function printUnmute(volume){
	var unmute = `:bell:  Spotify unmuted.`;
	console.log(emoji.emojify(unmute));
	printVolume(volume);
}

function printSetVolume(volume){
	var setVolume = `:headphones:  Volume set to ${volume}`;
	console.log(emoji.emojify(setVolume));
	printVolume(volume);
}

function printVolumeIncrease(change, volume){
	var increaseVolume = `:speaker:  Volume increased by ${change}`;
	console.log(emoji.emojify(increaseVolume));
	printVolume(volume);
}

function printVolumeDecrease(change, volume){
	var decreaseVolume = `:speaker:  Volume decreased by ${~change}`;
	console.log(emoji.emojify(decreaseVolume));
	printVolume(volume);
}

function printToggleShuffle(status){
	var description = status ? `${chalk.green('turned ON.')}` : `${chalk.red('turned OFF.')}`;
	var toggleShuffle = `:twisted_rightwards_arrows:  Shuffle ${description}`;
	console.log(emoji.emojify(toggleShuffle));
}

function printToggleRepeat(status){
	var description = status ? `${chalk.green('turned ON.')}` : `${chalk.red('turned OFF.')}`;
	var toggleRepeat = `:repeat:  Repeat ${description}`;
	console.log(emoji.emojify(toggleRepeat));
}

function printConfig(){
	console.log(
		chalk.green('Config set!')
	);
}

function printArtwork() {
	let terminal = require('child_process').execSync(`echo $TERM_PROGRAM`);
	terminal = terminal.toString().trim().replace(/^\n*/, '').replace(/\n*$/, '');
	if(terminal === 'iTerm.app') {
		osascripts.getiTermVersion().then(version => {
			if(semver.gt(version, '2.9.0')) {
				osascripts.getSongArtworkUrl().then((artworkURL) => {
					console.log();
					imgcat(artworkURL, {log: true, height: 8});
				});
			}
		});
	}
}

module.exports = {
	error,
	warning,
	printSearchResults,
	printPlayerStatus,
	printNext,
	printPrevious,
	printVolume,
	printMute,
	printUnmute,
	printSetVolume,
	printVolumeIncrease,
	printVolumeDecrease,
	printToggleShuffle,
	printToggleRepeat,
	printConfig
};<commit_msg>TEST: ignore iterm betas in semver comparison within printArtwork()<commit_after>'use strict';

const chalk = require('chalk');
const emoji = require('node-emoji');
const ProgressBar = require('progress');
const imgcat = require('imgcat');
const semver = require('semver');
const osascripts = require('../osascripts/index');

const SearchResultPrinters = {
	'albums': albumPrinterFn,
	'artists': artistPrinterFn,
	'playlists': playlistPrinterFn,
	'tracks': trackPrinterFn
};

function warning(m){
	console.log(
		chalk.yellow(m)
	);
}

function error(e){
	console.log(
		chalk.red(e)
	);
}

function albumPrinterFn(data){
	data.forEach((result) => {
		console.log(
			chalk.green(result.resultIndex + ': ') +
			chalk.blue('Album: ') +
			chalk.green(result.albumName)  +
			chalk.blue(' Artist: ') +
			chalk.green(result.artistNames)
		);
	});
}

function artistPrinterFn(data){
	data.forEach((result) => {
		console.log(
			chalk.green(result.resultIndex + ': ') +
			chalk.blue('Artist: ') +
			chalk.green(result.name)  +
			chalk.blue(' Followers: ') +
			chalk.green(result.followers)
		);
	});
}

function playlistPrinterFn(data){
	data.forEach((result) => {
		console.log(
			chalk.green(result.resultIndex + ': ') +
			chalk.blue('Playlist: ') +
			chalk.green(result.name)  +
			chalk.blue(' Tracks: ') +
			chalk.green(result.noOfTracks)
		);
	});
}

function trackPrinterFn(data){
	data.forEach((result) => {
		console.log(
			chalk.green(result.resultIndex + ': ') +
			chalk.blue('Track: ') +
			chalk.green(result.trackName + ' (' + result.duration + ')')  +
			chalk.blue(' Artist: ') +
			chalk.green(result.artistNames) +
			chalk.blue(' Album: ') +
			chalk.green(result.albumName)
		);
	});
}

function printSearchResults(resultType, data){
	if(SearchResultPrinters[resultType]){
		return SearchResultPrinters[resultType](data);
	}
	else {
		throw new Error(`${resultType} can not be printed.`);
	}
}

function printDurationProgress(result){
	var statusButton = result.status === 'playing' ? ':arrow_forward:' : ':double_vertical_bar:';
	statusButton = emoji.emojify(statusButton);
	new ProgressBar(`${statusButton}  ${result.status} [:bar] ${result.position} of ${result.duration}`, {
		complete: '=',
		incomplete: ' ',
		width: 50,
		total: result.durationSecs
	}).tick(result.positionSecs);
	console.log();
}

function printPlayerStatus(result){
	var artist = `:microphone:  ${chalk.green('Artist:')} ${chalk.green(result.artist)}`;
	var track = `:musical_score:  ${chalk.green('Track:')} ${chalk.green(result.track)}`;
	var album = `:cd:  ${chalk.green('Album:')} ${chalk.green(result.album)}`;
	console.log(emoji.emojify(artist));
	console.log(emoji.emojify(track));
	console.log(emoji.emojify(album));
	console.log();
	printDurationProgress(result);
	printArtwork();
}

function printNext(result){
	var nextTrack = `:fast_forward:  Playing next track: ${chalk.green(result.track)} :musical_score:`;
	console.log(emoji.emojify(nextTrack));
	console.log();
	printPlayerStatus(result);
}

function printPrevious(result){
	var previousTrack = `:rewind:  Playing previous track: ${chalk.green(result.track)} :musical_score:`;
	console.log(emoji.emojify(previousTrack));
	console.log();
	printPlayerStatus(result);
}

function printVolume(volume){
	new ProgressBar(`Volume: [:bar] ${chalk.green(volume)}`, {
		complete: '=',
		incomplete: ' ',
		width: 50,
		total: 100
	}).tick(volume);
	console.log();
}

function printMute(volume){
	var mute = `:no_bell:  Spotify muted.`;
	console.log(emoji.emojify(mute));
	printVolume(volume);
}

function printUnmute(volume){
	var unmute = `:bell:  Spotify unmuted.`;
	console.log(emoji.emojify(unmute));
	printVolume(volume);
}

function printSetVolume(volume){
	var setVolume = `:headphones:  Volume set to ${volume}`;
	console.log(emoji.emojify(setVolume));
	printVolume(volume);
}

function printVolumeIncrease(change, volume){
	var increaseVolume = `:speaker:  Volume increased by ${change}`;
	console.log(emoji.emojify(increaseVolume));
	printVolume(volume);
}

function printVolumeDecrease(change, volume){
	var decreaseVolume = `:speaker:  Volume decreased by ${~change}`;
	console.log(emoji.emojify(decreaseVolume));
	printVolume(volume);
}

function printToggleShuffle(status){
	var description = status ? `${chalk.green('turned ON.')}` : `${chalk.red('turned OFF.')}`;
	var toggleShuffle = `:twisted_rightwards_arrows:  Shuffle ${description}`;
	console.log(emoji.emojify(toggleShuffle));
}

function printToggleRepeat(status){
	var description = status ? `${chalk.green('turned ON.')}` : `${chalk.red('turned OFF.')}`;
	var toggleRepeat = `:repeat:  Repeat ${description}`;
	console.log(emoji.emojify(toggleRepeat));
}

function printConfig(){
	console.log(
		chalk.green('Config set!')
	);
}

function printArtwork() {
	let terminal = require('child_process').execSync(`echo $TERM_PROGRAM`);
	terminal = terminal.toString().trim().replace(/^\n*/, '').replace(/\n*$/, '');
	if(terminal === 'iTerm.app') {
		osascripts.getiTermVersion().then(version => {
			if version.includes("beta"){
				split = version.split("beta");
				version = split[0];
			}
			if(semver.gt(version, '2.9.0')) {
				osascripts.getSongArtworkUrl().then((artworkURL) => {
					console.log();
					imgcat(artworkURL, {log: true, height: 8});
				});
			}
		});
	}
}

module.exports = {
	error,
	warning,
	printSearchResults,
	printPlayerStatus,
	printNext,
	printPrevious,
	printVolume,
	printMute,
	printUnmute,
	printSetVolume,
	printVolumeIncrease,
	printVolumeDecrease,
	printToggleShuffle,
	printToggleRepeat,
	printConfig
};
<|endoftext|>


<commit_before>define(function (require, exports, module) {
    'use strict';

    var common = require('./common'),
        $ = require('jquery');

    function Modal(element, options) {
        if (!(this instanceof Modal)) {
            return new Modal(element, options);
        }

        this.element = common.query(element);

        this.target = this.getTarget();

        if ($(this.element).data('instance-modal')) {
            return $(this.element).data('instance-modal');
        } else {
            $(this.element).data('instance-modal', this);
        }

        if (!(options && options.slient)) {
            $(this.element).on('click', this.show.bind(this));
        }
    }

    Modal.prototype = {
        constructor: Modal,

        getTarget: function () {
            var target = this.element.dataset['target'];
            if (!target) {
                target = this.element.hash;
            }
            return common.query(target);
        },

        getClose: function () {
            return common.query('[data-toggle=modal-close]', this.target);
        },

        show: function show(e) {
            if (e) {
                e.preventDefault();
            }
            if (this.target.classList.contains('active')) {
                return;
            }
            this.target.classList.add('active');
            $(this.getClose()).one('click', this.hide.bind(this));
        },

        hide: function hide(e) {
            if (e) {
                e.preventDefault();
            }
            if (this.target.classList.contains('active')) {
                this.target.classList.remove('active');
            }
        }
    };

    Modal.live = function live() {
        Modal.die();

        $(document).on('click.modal', '[data-toggle=modal-open]', function (e) {
            var model = new Modal(this, {
                slient: true
            });
            model.show();
        });
    };

    Modal.die = function die() {
        $(document).off('click.modal');
    };

    module.exports = Modal;
});
<commit_msg>优化modal.js中代码结构和语法<commit_after>define(function (require, exports, module) {
    'use strict';

    var $ = require('jquery'),
        common = require('./common');

    function Modal(element, options) {
        if (!(this instanceof Modal)) {
            return new Modal(element, options);
        }

        this.element = common.query(element);

        if ($(this.element).data('instance-modal')) {
            return $(this.element).data('instance-modal');
        } else {
            $(this.element).data('instance-modal', this);
        }

        this.target = this.getTarget();

        if (!(options && options.slient)) {
            $(this.element).on('click', this.show.bind(this));
        }
    }

    Modal.prototype = {
        constructor: Modal,

        getTarget: function () {
            var target = this.element.dataset.target;
            if (!target) {
                target = this.element.hash;
            }
            return common.query(target);
        },

        getClose: function () {
            return common.query('[data-toggle=modal-close]', this.target);
        },

        show: function show(e) {
            if (e) {
                e.preventDefault();
            }
            if (this.target.classList.contains('active')) {
                return;
            }
            this.target.classList.add('active');
            $(this.getClose()).one('click', this.hide.bind(this));
        },

        hide: function hide(e) {
            if (e) {
                e.preventDefault();
            }
            if (this.target.classList.contains('active')) {
                this.target.classList.remove('active');
            }
        }
    };

    Modal.live = function live() {
        Modal.die();

        $(document).on('click.modal', '[data-toggle=modal-open]', function (e) {
            var model = new Modal(this, {
                slient: true
            });
            model.show();
        });
    };

    Modal.die = function die() {
        $(document).off('click.modal');
    };

    module.exports = Modal;
});
<|endoftext|>


<commit_before>'use strict';

// Required settings:
// deathChecker.ignore = ['FOO'] Roles in this array shouldn't be replaced
// deathChecker.copy = ['BAR'] Roles in this array should be replaced
// deathChecker.copyPriority = ['FOOBAR'] Roles in this array should be replaced quickly
//
// Notes:
// - If a role has been found dead and has not been found in either arrays
//   the chat might spam because the deathChecker doesn't know what to do
//
// - If you want to prevent a creep from being copied when it dies,
//   set memory property 'copyOnDeath' to false
var removeQueue = [];

var queueCreep = function(creep, priority) {
    console.log('Hook deathChecker: Found dead creep ' + creep + '. Copying to ' + (priority ? "priority ":"") + "queue...");

    // Clone creep to spawn queue
    AI.exec('creepClone', {
        role: Memory.creeps[creep].role,
        memory: _.clone(Memory.creeps[creep])
    }, priority);

    // Mark cloning as done
    removeQueue.push(creep);
    Memory.creeps[creep].copyOnDeath = "ignore";
};

var deathChecker = function() {

    // Precompile checklist
    var action = {};
    var addToAction = function(type) {
        return function(key) {
            action[key] = type;
        };
    };

    AI.settings.deathChecker.ignore.forEach(addToAction("ignore"));
    AI.settings.deathChecker.copy.forEach(addToAction("copy"));
    AI.settings.deathChecker.copyPriority.forEach(addToAction("copyPriority"));

    var mode;
    for (var i in Memory.creeps) {

        // Ignore when creep is found alive
        if (Game.creeps[i]) {
            continue;
        }

        mode = undefined;

        // Check creep memory
        if (Memory.creeps[i].copyOnDeath !== undefined &&
            [false, 'ignore', 'copy', 'copyPriority'].indexOf(Memory.creeps[i].copyOnDeath) !== -1
        ) {
            mode = Memory.creeps[i].copyOnDeath === false ? 'ignore' : Memory.creeps[i].copyOnDeath;
        }

        // Use role default when no value found
        if (mode === undefined) {
            mode = action[Memory.creeps[i].role];
        }

        if (mode === "ignore") {
            console.log('Hook deathChecker: Found dead creep ' + i + '. Deleting...');
            removeQueue.push(i);

        } else if (mode === "copy") {
            queueCreep(i, false);

        } else if (mode === "copyPriority") {
            queueCreep(i, true);

        } else {
            console.log('Hook deathChecker: Found dead creep ' + i + '. Dunno what to do...');
        }
    }

};

var removeDeaths = function() {
    for (var i = 0; i < removeQueue.length; i++) {
        delete Memory.creeps[removeQueue[i]];
    }
};

function preController() {
    deathChecker();
}

function postController() {
    removeDeaths();
}

module.exports = {
    preController: preController,
    postController: postController,
    test: {
        get removeQueue() { return removeQueue; },
        set removeQueue(value) { removeQueue = value; },
        queueCreep: queueCreep
    }
};
<commit_msg>Fix creeps without roles not getting removed<commit_after>'use strict';

// Required settings:
// deathChecker.ignore = ['FOO'] Roles in this array shouldn't be replaced
// deathChecker.copy = ['BAR'] Roles in this array should be replaced
// deathChecker.copyPriority = ['FOOBAR'] Roles in this array should be replaced quickly
//
// Notes:
// - If a role has been found dead and has not been found in either arrays
//   the chat might spam because the deathChecker doesn't know what to do
//
// - If you want to prevent a creep from being copied when it dies,
//   set memory property 'copyOnDeath' to false
var removeQueue = [];

var queueCreep = function(creep, priority) {
    console.log('Hook deathChecker: Found dead creep ' + creep + '. Copying to ' + (priority ? "priority ":"") + "queue...");

    // Clone creep to spawn queue
    AI.exec('creepClone', {
        role: Memory.creeps[creep].role,
        memory: _.clone(Memory.creeps[creep])
    }, priority);

    // Mark cloning as done
    removeQueue.push(creep);
    Memory.creeps[creep].copyOnDeath = "ignore";
};

var deathChecker = function() {

    // Precompile checklist
    var action = {};
    var addToAction = function(type) {
        return function(key) {
            action[key] = type;
        };
    };

    AI.settings.deathChecker.ignore.forEach(addToAction("ignore"));
    AI.settings.deathChecker.copy.forEach(addToAction("copy"));
    AI.settings.deathChecker.copyPriority.forEach(addToAction("copyPriority"));

    var mode;
    for (var i in Memory.creeps) {

        // Ignore when creep is found alive
        if (Game.creeps[i]) {
            continue;
        }

        mode = undefined;

        // Check creep memory
        if (Memory.creeps[i].copyOnDeath !== undefined &&
            [false, 'ignore', 'copy', 'copyPriority'].indexOf(Memory.creeps[i].copyOnDeath) !== -1
        ) {
            mode = Memory.creeps[i].copyOnDeath === false ? 'ignore' : Memory.creeps[i].copyOnDeath;
        }

        // Use role default when no value found
        if (mode === undefined) {
            if (typeof action[Memory.creeps[i].role] === "string") {
                mode = action[Memory.creeps[i].role];
            } else {
                Game.notify("Found dead creep " + i + " without role. Deleting...");
                mode = "ignore";
            }
        }

        if (mode === "ignore") {
            console.log('Hook deathChecker: Found dead creep ' + i + '. Deleting...');
            removeQueue.push(i);

        } else if (mode === "copy") {
            queueCreep(i, false);

        } else if (mode === "copyPriority") {
            queueCreep(i, true);

        } else {
            console.log('Hook deathChecker: Found dead creep ' + i + '. Dunno what to do...');
        }
    }

};

var removeDeaths = function() {
    for (var i = 0; i < removeQueue.length; i++) {
        delete Memory.creeps[removeQueue[i]];
    }
};

function preController() {
    deathChecker();
}

function postController() {
    removeDeaths();
}

module.exports = {
    preController: preController,
    postController: postController,
    test: {
        get removeQueue() { return removeQueue; },
        set removeQueue(value) { removeQueue = value; },
        queueCreep: queueCreep
    }
};
<|endoftext|>


<commit_before>$(document).ready(function () {
    $("#dictation-form").submit(function (event) {
        event.preventDefault();
        console.log("Entered Click");

        //var field_data = $("#dictation-text").serialize();
        var field_data = 'data=' + "\"{ 'data' : '" + $("#dictation-text").val() + "' }\"";
        console.log(field_data);
        console.log(typeof field_data);
        var action = $(this).attr("action");
        var method = $(this).attr("method");
        console.log(action);

        $.ajax({
            url: action,
            data: field_data,
            type: method,
            error: function (a,b,c){console.log(a,b,c);},
            complete: function (res){console.log(res);}
            });
    });
});<commit_msg>debug<commit_after>$(document).ready(function () {
    $("#dictation-form").submit(function (event) {
        event.preventDefault();
        console.log("Entered Click");

        //var field_data = $("#dictation-text").serialize();
        //var field_data = 'data=' + "\"{ 'data' : '" + $("#dictation-text").val() + "' }\"";
        var field_data = {data: $("#dictation-text").val(),
                            was_anderes: "Test"
                            };
        console.log(field_data);
        console.log(typeof field_data);
        var action = $(this).attr("action");
        var method = $(this).attr("method");
        console.log(action);

        $.ajax({
            url: action,
            data: JSON.stringify(field_data),
            type: method,
            error: function (a,b,c){console.log(a,b,c);},
            complete: function (res){console.log(res);}
            });
    });
});<|endoftext|>


<commit_before>var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');
var path = require('path');

module.exports = {
    entry: {
        'polyfills': './src/polyfills.ts',
        'vendor': './src/vendor.ts',
        'app': './src/main.ts'
    },

    resolve: {
        extensions: ['.ts', '.js']
    },

    module: {
        rules: [
            {
                test: /\.ts$/,
                enforce: 'pre',
                loader: 'tslint-loader'
            },
            {
                test: /\.ts$/,
                loaders: ['ts-loader', 'angular2-template-loader', 'angular2-router-loader']
            },
            {
                test: /\.html$/,
                loader: 'html-loader'
            },
            {
                test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                loader: 'file-loader?name=assets/[name].[hash].[ext]'
            },
            {
                test: /\.css$/,
                exclude: helpers.root('src', 'app'),
                loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader?sourceMap' })
            },
            {
                test: /\.css$/,
                include: helpers.root('src', 'app'),
                loader: 'raw-loader'
            },
            {
                test: /\.scss$/,
                exclude: [/\.global\.scss$/],
                loaders: ['raw-loader', 'sass-loader']
            },
            {
                test: /\.global\.scss$/,
                loaders: ['style-loader', 'css-loader', 'sass-loader']
            }
        ]
    },

    plugins: [
        // Workaround for angular/angular#11580
        new webpack.ContextReplacementPlugin(
            /angular(\\|\/)core(\\|\/)@angular/,
            path.resolve(__dirname, '../src')
        ),

        new webpack.optimize.CommonsChunkPlugin({
            name: ['app', 'vendor', 'polyfills']
        }),

        new HtmlWebpackPlugin({
            template: 'src/index.html'
        })
    ]
};
<commit_msg>removed whitespace<commit_after>var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');
var path = require('path');

module.exports = {
    entry: {
        'polyfills': './src/polyfills.ts',
        'vendor': './src/vendor.ts',
        'app': './src/main.ts'
    },

    resolve: {
        extensions: ['.ts', '.js']
    },

    module: {
        rules: [
            {
                test: /\.ts$/,
                enforce: 'pre',
                loader: 'tslint-loader'
            },
            {
                test: /\.ts$/,
                loaders: ['ts-loader', 'angular2-template-loader', 'angular2-router-loader']
            },
            {
                test: /\.html$/,
                loader: 'html-loader'
            },
            {
                test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                loader: 'file-loader?name=assets/[name].[hash].[ext]'
            },
            {
                test: /\.css$/,
                exclude: helpers.root('src', 'app'),
                loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader?sourceMap' })
            },
            {
                test: /\.css$/,
                include: helpers.root('src', 'app'),
                loader: 'raw-loader'
            },
            {
                test: /\.scss$/,
                exclude: [/\.global\.scss$/],
                loaders: ['raw-loader', 'sass-loader']
            },
            {
                test: /\.global\.scss$/,
                loaders: ['style-loader', 'css-loader', 'sass-loader']
            }
        ]
    },

    plugins: [
        // Workaround for angular/angular#11580
        new webpack.ContextReplacementPlugin(
            /angular(\\|\/)core(\\|\/)@angular/,
            path.resolve(__dirname, '../src')
        ),

        new webpack.optimize.CommonsChunkPlugin({
            name: ['app', 'vendor', 'polyfills']
        }),

        new HtmlWebpackPlugin({
            template: 'src/index.html'
        })
    ]
};
<|endoftext|>


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

    angular.module('scaleApp').controller('nodesController', function($scope, $location, $timeout, $uibModal, navService, nodeService, nodeUpdateService, statusService, stateService, userService, jobTypeService, gridFactory, toastr, poller) {
        var vm = this;

        vm.nodesParams = stateService.getNodesParams();

        vm.stateService = stateService;
        vm.loading = true;
        vm.loadingStatus = true;
        vm.readonly = true;
        vm.actionClicked = false;
        vm.gridOptions = gridFactory.defaultGridOptions();
        vm.gridOptions.data = [];
        vm.showActive = vm.nodesParams.active === 'true';
        vm.nodeType = vm.showActive ? 'Active' : 'Deprecated';
        vm.nodeTotals = '';

        $scope.pauseReason = '';

        var allNodes = [];
        var filteredByOrder = vm.nodesParams.order ? true : false;
        var jobTypes = null;

        vm.colDefs = [
            {
                field: 'hostname',
                displayName: 'Hostname',
                enableFiltering: false,
                width: '25%',
                cellTemplate: 'hostname.html'
            },
            {
                field: 'state',
                displayName: 'State',
                enableFiltering: false,
                enableSorting: false,
                width: '10%',
                cellTemplate: '

 0" tooltip-append-to-body="true" uib-tooltip="{{ row.entity.errors.length === 1 ? row.entity.errors[0].description : row.entity.errors.length + \' Errors\' }}">  0" tooltip-append-to-body="true" uib-tooltip="{{ row.entity.warnings.length === 1 ? row.entity.warnings[0].description : row.entity.warnings.length + \' Warnings\' }}">

'
            },
            {
                field: 'job_executions',
                displayName: 'Job Executions (Last 3 Hrs)',
                enableFiltering: false,
                enableSorting: false,
                width: '25%',
                cellTemplate: 'jobExecutions.html',
                headerCellTemplate: 'jobExecutionsHeader.html'
            },
            {
                field: 'running_jobs',
                displayName: 'Running Jobs',
                enableFiltering: false,
                enableSorting: false,
                cellTemplate: 'runningJobs.html'
            }
        ];

        vm.gridOptions.columnDefs = vm.colDefs;

        vm.toggleActive = function (entity) {
            vm.actionClicked = true;
            var isActive = !entity.is_active;
            nodeUpdateService.updateNode(entity, { pause_reason: '', is_paused: entity.is_paused, is_active: isActive }).then(function (result) {
                var node = _.find(vm.gridOptions.data, { id: result.id });
                entity.is_active = result.is_active;
                if (entity.is_active) {
                    toastr.info(node.hostname + ' Activated');
                } else {
                    toastr.info(node.hostname + ' Deactivated');
                }
            });
        };

        vm.pauseNode = function (entity) {
            $scope.pauseReason = '';
            vm.actionClicked = true;

            $scope.updateReason = function (value) {
                $scope.pauseReason = value;
            };

            var pauseResume = function () {
                var isPaused = entity.state.name !== 'PAUSED';
                nodeUpdateService.updateNode(entity, { pause_reason: $scope.pauseReason, is_paused: isPaused, is_active: entity.is_active }).then(function (result) {
                    var node = _.find(vm.gridOptions.data, { id: result.id });
                    entity.is_paused = result.is_paused;
                    if (entity.is_paused) {
                        toastr.info(node.hostname + ' Paused');
                    } else {
                        toastr.info(node.hostname + ' Resumed');
                    }
                });
            };

            // only prompt for reason when pausing (not resuming)
            if (entity.state.name !== 'PAUSED') {
                var modalInstance = $uibModal.open({
                    animation: true,
                    templateUrl: 'pauseDialog.html',
                    scope: $scope
                });

                modalInstance.result.then(function () {
                    pauseResume();
                });
            } else {
                pauseResume();
            }
        };

        vm.filterResults = function () {
            poller.stopAll();
            stateService.setNodesParams(vm.nodesParams);
            vm.loading = true;
            getNodes();
        };

        vm.updateColDefs = function () {
            vm.gridOptions.columnDefs = gridFactory.applySortConfig(vm.colDefs, vm.nodesParams);
        };

        vm.updateNodeOrder = function (sortArr) {
            vm.nodesParams.order = sortArr.length > 0 ? sortArr : null;
            filteredByOrder = sortArr.length > 0;
            vm.filterResults();
        };

        vm.updateNodeActive = function () {
            formatResults();
        };

        vm.gridOptions.onRegisterApi = function (gridApi) {
            //set gridApi on scope
            vm.gridApi = gridApi;
            vm.gridApi.selection.on.rowSelectionChanged($scope, function (row) {
                if (vm.actionClicked) {
                    vm.actionClicked = false;
                } else {
                    $location.search({});
                    $location.path('/nodes/' + row.entity.id);
                }
            });
            vm.gridApi.core.on.sortChanged($scope, function (grid, sortColumns) {
                _.forEach(vm.gridApi.grid.columns, function (col) {
                    col.colDef.sort = col.sort;
                });
                stateService.setNodesColDefs(vm.gridApi.grid.options.columnDefs);
                var sortArr = [];
                _.forEach(sortColumns, function (col) {
                    sortArr.push(col.sort.direction === 'desc' ? '-' + col.field : col.field);
                });
                vm.updateNodeOrder(sortArr);
            });
        };

        var formatResults = function () {
            var currNodeType = vm.showActive ? 'Active' : 'Deprecated';
            var altNodeType = vm.showActive ? 'Deprecated' : 'Active';
            vm.nodes = _.filter(allNodes, { is_active: vm.showActive });
            vm.nodeTotals = vm.nodes.length + ' ' + currNodeType + ' Nodes / ' + (allNodes.length - vm.nodes.length) + ' ' + altNodeType + ' Nodes';
            var order = $location.search().order;
            if (order) {
                var fieldArr = [];
                var directionArr = [];
                _.forEach(order, function (o) {
                    fieldArr.push(_.startsWith(o, '-') ? _.tail(o).join('') : o);
                    directionArr.push(_.startsWith(order, '-') ? 'desc' : 'asc');
                });
                vm.nodes = _.sortByOrder(vm.nodes, fieldArr, directionArr);
            }
            _.forEach(vm.nodes, function (node) {
                node.running_jobs = getRunningJobs(node);
            });
            vm.gridOptions.totalItems = vm.nodes.length;
            vm.gridOptions.minRowsToShow = vm.nodes.length;
            vm.gridOptions.virtualizationThreshold = vm.nodes.length;
            vm.gridOptions.data = vm.nodes;
        };

        var getRunningJobs = function (entity) {
            var runningJobs = [];
            _.forEach(entity.job_executions.running.by_job_type, function (jobType) {
                runningJobs.push({
                    jobType: _.find(jobTypes, { id: jobType.job_type_id }),
                    count: jobType.count
                });
            });
            return runningJobs;
        };

        var getNodes = function () {
            statusService.getStatus(true).then(null, null, function (data) {
                if (data.$resolved) {
                    vm.nodesError = null;
                    allNodes = data.nodes;
                    formatResults();
                } else {
                    if (data.statusText && data.statusText !== '') {
                        vm.nodesErrorStatus = data.statusText;
                    }
                    vm.nodesError = 'Unable to retrieve nodes.';
                }
                vm.loading = false;
            });
        };

        var initialize = function () {
            jobTypeService.getJobTypesOnce().then(function (data) {
                jobTypes = data.results;
                getNodes();
            });
            stateService.setNodesParams(vm.nodesParams);
            vm.updateColDefs();
            var user = userService.getUserCreds();
            vm.readonly = !(user && user.is_admin);
            navService.updateLocation('nodes');
        };

        initialize();

        $scope.$watchCollection('vm.stateService.getNodesColDefs()', function (newValue, oldValue) {
            if (angular.equals(newValue, oldValue)) {
                return;
            }
            vm.colDefs = newValue;
            vm.updateColDefs();
        });

        $scope.$watchCollection('vm.stateService.getNodesParams()', function (newValue, oldValue) {
            if (angular.equals(newValue, oldValue)) {
                return;
            }
            vm.nodesParams = newValue;
            vm.updateColDefs();
        });

        $scope.$watchCollection('vm.nodes', function (newValue, oldValue) {
            if (angular.equals(newValue, oldValue)) {
                return;
            }
            vm.gridOptions.data = vm.nodes;
        });

        $scope.$watch('vm.showActive', function (newValue, oldValue) {
            if (angular.equals(newValue, oldValue)) {
                return;
            }
            vm.nodesParams.active = newValue.toString();
            vm.showActive = newValue;
            vm.nodeType = newValue ? 'Active' : 'Deprecated';
            formatResults();
            stateService.setNodesParams(vm.nodesParams);
        });
    });
})();
<commit_msg>changed width of hostname column<commit_after>(function () {
    'use strict';

    angular.module('scaleApp').controller('nodesController', function($scope, $location, $timeout, $uibModal, navService, nodeService, nodeUpdateService, statusService, stateService, userService, jobTypeService, gridFactory, toastr, poller) {
        var vm = this;

        vm.nodesParams = stateService.getNodesParams();

        vm.stateService = stateService;
        vm.loading = true;
        vm.loadingStatus = true;
        vm.readonly = true;
        vm.actionClicked = false;
        vm.gridOptions = gridFactory.defaultGridOptions();
        vm.gridOptions.data = [];
        vm.showActive = vm.nodesParams.active === 'true';
        vm.nodeType = vm.showActive ? 'Active' : 'Deprecated';
        vm.nodeTotals = '';

        $scope.pauseReason = '';

        var allNodes = [];
        var filteredByOrder = vm.nodesParams.order ? true : false;
        var jobTypes = null;

        vm.colDefs = [
            {
                field: 'hostname',
                displayName: 'Hostname',
                enableFiltering: false,
                width: '15%',
                cellTemplate: 'hostname.html'
            },
            {
                field: 'state',
                displayName: 'State',
                enableFiltering: false,
                enableSorting: false,
                width: '10%',
                cellTemplate: '

 0" tooltip-append-to-body="true" uib-tooltip="{{ row.entity.errors.length === 1 ? row.entity.errors[0].description : row.entity.errors.length + \' Errors\' }}">  0" tooltip-append-to-body="true" uib-tooltip="{{ row.entity.warnings.length === 1 ? row.entity.warnings[0].description : row.entity.warnings.length + \' Warnings\' }}">

'
            },
            {
                field: 'job_executions',
                displayName: 'Job Executions (Last 3 Hrs)',
                enableFiltering: false,
                enableSorting: false,
                width: '25%',
                cellTemplate: 'jobExecutions.html',
                headerCellTemplate: 'jobExecutionsHeader.html'
            },
            {
                field: 'running_jobs',
                displayName: 'Running Jobs',
                enableFiltering: false,
                enableSorting: false,
                cellTemplate: 'runningJobs.html'
            }
        ];

        vm.gridOptions.columnDefs = vm.colDefs;

        vm.toggleActive = function (entity) {
            vm.actionClicked = true;
            var isActive = !entity.is_active;
            nodeUpdateService.updateNode(entity, { pause_reason: '', is_paused: entity.is_paused, is_active: isActive }).then(function (result) {
                var node = _.find(vm.gridOptions.data, { id: result.id });
                entity.is_active = result.is_active;
                if (entity.is_active) {
                    toastr.info(node.hostname + ' Activated');
                } else {
                    toastr.info(node.hostname + ' Deactivated');
                }
            });
        };

        vm.pauseNode = function (entity) {
            $scope.pauseReason = '';
            vm.actionClicked = true;

            $scope.updateReason = function (value) {
                $scope.pauseReason = value;
            };

            var pauseResume = function () {
                var isPaused = entity.state.name !== 'PAUSED';
                nodeUpdateService.updateNode(entity, { pause_reason: $scope.pauseReason, is_paused: isPaused, is_active: entity.is_active }).then(function (result) {
                    var node = _.find(vm.gridOptions.data, { id: result.id });
                    entity.is_paused = result.is_paused;
                    if (entity.is_paused) {
                        toastr.info(node.hostname + ' Paused');
                    } else {
                        toastr.info(node.hostname + ' Resumed');
                    }
                });
            };

            // only prompt for reason when pausing (not resuming)
            if (entity.state.name !== 'PAUSED') {
                var modalInstance = $uibModal.open({
                    animation: true,
                    templateUrl: 'pauseDialog.html',
                    scope: $scope
                });

                modalInstance.result.then(function () {
                    pauseResume();
                });
            } else {
                pauseResume();
            }
        };

        vm.filterResults = function () {
            poller.stopAll();
            stateService.setNodesParams(vm.nodesParams);
            vm.loading = true;
            getNodes();
        };

        vm.updateColDefs = function () {
            vm.gridOptions.columnDefs = gridFactory.applySortConfig(vm.colDefs, vm.nodesParams);
        };

        vm.updateNodeOrder = function (sortArr) {
            vm.nodesParams.order = sortArr.length > 0 ? sortArr : null;
            filteredByOrder = sortArr.length > 0;
            vm.filterResults();
        };

        vm.updateNodeActive = function () {
            formatResults();
        };

        vm.gridOptions.onRegisterApi = function (gridApi) {
            //set gridApi on scope
            vm.gridApi = gridApi;
            vm.gridApi.selection.on.rowSelectionChanged($scope, function (row) {
                if (vm.actionClicked) {
                    vm.actionClicked = false;
                } else {
                    $location.search({});
                    $location.path('/nodes/' + row.entity.id);
                }
            });
            vm.gridApi.core.on.sortChanged($scope, function (grid, sortColumns) {
                _.forEach(vm.gridApi.grid.columns, function (col) {
                    col.colDef.sort = col.sort;
                });
                stateService.setNodesColDefs(vm.gridApi.grid.options.columnDefs);
                var sortArr = [];
                _.forEach(sortColumns, function (col) {
                    sortArr.push(col.sort.direction === 'desc' ? '-' + col.field : col.field);
                });
                vm.updateNodeOrder(sortArr);
            });
        };

        var formatResults = function () {
            var currNodeType = vm.showActive ? 'Active' : 'Deprecated';
            var altNodeType = vm.showActive ? 'Deprecated' : 'Active';
            vm.nodes = _.filter(allNodes, { is_active: vm.showActive });
            vm.nodeTotals = vm.nodes.length + ' ' + currNodeType + ' Nodes / ' + (allNodes.length - vm.nodes.length) + ' ' + altNodeType + ' Nodes';
            var order = $location.search().order;
            if (order) {
                var fieldArr = [];
                var directionArr = [];
                _.forEach(order, function (o) {
                    fieldArr.push(_.startsWith(o, '-') ? _.tail(o).join('') : o);
                    directionArr.push(_.startsWith(order, '-') ? 'desc' : 'asc');
                });
                vm.nodes = _.sortByOrder(vm.nodes, fieldArr, directionArr);
            }
            _.forEach(vm.nodes, function (node) {
                node.running_jobs = getRunningJobs(node);
            });
            vm.gridOptions.totalItems = vm.nodes.length;
            vm.gridOptions.minRowsToShow = vm.nodes.length;
            vm.gridOptions.virtualizationThreshold = vm.nodes.length;
            vm.gridOptions.data = vm.nodes;
        };

        var getRunningJobs = function (entity) {
            var runningJobs = [];
            _.forEach(entity.job_executions.running.by_job_type, function (jobType) {
                runningJobs.push({
                    jobType: _.find(jobTypes, { id: jobType.job_type_id }),
                    count: jobType.count
                });
            });
            return runningJobs;
        };

        var getNodes = function () {
            statusService.getStatus(true).then(null, null, function (data) {
                if (data.$resolved) {
                    vm.nodesError = null;
                    allNodes = data.nodes;
                    formatResults();
                } else {
                    if (data.statusText && data.statusText !== '') {
                        vm.nodesErrorStatus = data.statusText;
                    }
                    vm.nodesError = 'Unable to retrieve nodes.';
                }
                vm.loading = false;
            });
        };

        var initialize = function () {
            jobTypeService.getJobTypesOnce().then(function (data) {
                jobTypes = data.results;
                getNodes();
            });
            stateService.setNodesParams(vm.nodesParams);
            vm.updateColDefs();
            var user = userService.getUserCreds();
            vm.readonly = !(user && user.is_admin);
            navService.updateLocation('nodes');
        };

        initialize();

        $scope.$watchCollection('vm.stateService.getNodesColDefs()', function (newValue, oldValue) {
            if (angular.equals(newValue, oldValue)) {
                return;
            }
            vm.colDefs = newValue;
            vm.updateColDefs();
        });

        $scope.$watchCollection('vm.stateService.getNodesParams()', function (newValue, oldValue) {
            if (angular.equals(newValue, oldValue)) {
                return;
            }
            vm.nodesParams = newValue;
            vm.updateColDefs();
        });

        $scope.$watchCollection('vm.nodes', function (newValue, oldValue) {
            if (angular.equals(newValue, oldValue)) {
                return;
            }
            vm.gridOptions.data = vm.nodes;
        });

        $scope.$watch('vm.showActive', function (newValue, oldValue) {
            if (angular.equals(newValue, oldValue)) {
                return;
            }
            vm.nodesParams.active = newValue.toString();
            vm.showActive = newValue;
            vm.nodeType = newValue ? 'Active' : 'Deprecated';
            formatResults();
            stateService.setNodesParams(vm.nodesParams);
        });
    });
})();
<|endoftext|>


<commit_before>var _ = require('underscore');
var Backbone = require('backbone');
var AnalysisDefinitionNodesCollection = require('../../../../../../javascripts/cartodb3/data/analysis-definition-nodes-collection');
var AnalysisDefinitionsCollection = require('../../../../../../javascripts/cartodb3/data/analysis-definitions-collection');
var ConfigModel = require('../../../../../../javascripts/cartodb3/data/config-model');
var DeleteLayerConfirmationView = require('../../../../../../javascripts/cartodb3/components/modals/remove-layer/delete-layer-confirmation-view');
var LayerDefinitionModel = require('../../../../../../javascripts/cartodb3/data/layer-definition-model');
var LayerDefinitionsCollection = require('../../../../../../javascripts/cartodb3/data/layer-definitions-collection');
var ModalsServiceModel = require('../../../../../../javascripts/cartodb3/components/modals/modals-service-model');
var UserActions = require('../../../../../../javascripts/cartodb3/data/user-actions');
var UserModel = require('../../../../../../javascripts/cartodb3/data/user-model');
var VisDefinitionModel = require('../../../../../../javascripts/cartodb3/data/vis-definition-model');
var WidgetDefinitionsCollection = require('../../../../../../javascripts/cartodb3/data/widget-definitions-collection');

describe('modals/delete-layer-confirmation-view', function () {
  var view;
  var modalModel;
  var userData;
  var configData;
  var configModel;
  var userModel;
  var analysisDefinitionNodesCollection;
  var layerModel;
  var layerDefinitionsCollection;
  var visDefinitionModel;
  var widgetDefinitionsCollection;
  var analysisDefinitionsCollection;
  var userActions;
  var modals;

  modalModel = new Backbone.Model();

  userData = {
    id: '8c253a9a-94d8-4042-883c-3aa81285e5e6',
    username: 'cdb'
  };

  configData = {
    base_url: '/u/manolo',
    maps_api_template: 'http://{user}.localhost.lan:8181'
  };

  configModel = new ConfigModel(configData);

  userModel = new UserModel(userData, { configModel: configModel });

  analysisDefinitionNodesCollection = new AnalysisDefinitionNodesCollection([], {
    configModel: configModel,
    userModel: userModel
  });

  layerModel = new LayerDefinitionModel({
    id: 'map-123',
    kind: 'carto',
    options: {
      type: 'CartoDB',
      color: '#FABADA',
      table_name: 'foo_bar',
      name: 'foo',
      letter: 'a',
      source: 'map-123',
      table_name_alias: 'foo_foo_bar',
      query: 'SELECT * FROM foo',
      tile_style: 'asdasd',
      visible: true
    }
  }, {
    configModel: configModel,
    parse: true
  });

  layerDefinitionsCollection = new LayerDefinitionsCollection([layerModel], {
    configModel: configModel,
    userModel: userModel,
    analysisDefinitionNodesCollection: analysisDefinitionNodesCollection,
    mapId: 'map-123',
    stateDefinitionModel: {}
  });

  visDefinitionModel = new VisDefinitionModel({
    name: 'foo',
    privacy: 'LINK',
    updated_at: '2016-06-21T15:30:06+00:00',
    type: 'derived',
    tags: ['foo', 'bar'],
    permission: {}
  }, {
    configModel: configModel
  });

  widgetDefinitionsCollection = new WidgetDefinitionsCollection([layerModel], {
    configModel: configModel,
    layerDefinitionsCollection: layerDefinitionsCollection,
    analysisDefinitionNodesCollection: analysisDefinitionNodesCollection,
    mapId: 'map-123'
  });

  analysisDefinitionsCollection = new AnalysisDefinitionsCollection([layerModel], {
    configModel: configModel,
    vizId: 'viz-123',
    layerDefinitionsCollection: layerDefinitionsCollection,
    analysisDefinitionNodesCollection: analysisDefinitionNodesCollection
  });

  userActions = new UserActions({
    userModel: userModel,
    analysisDefinitionNodesCollection: analysisDefinitionNodesCollection,
    analysisDefinitionsCollection: analysisDefinitionsCollection,
    layerDefinitionsCollection: layerDefinitionsCollection,
    widgetDefinitionsCollection: widgetDefinitionsCollection
  });

  modals = new ModalsServiceModel();

  function createViewFn (options = {}) {
    var defaultOptions = {
      userActions: userActions,
      modals: modals,
      layerModel: layerModel,
      modalModel: modalModel,
      visDefinitionModel: visDefinitionModel,
      widgetDefinitionsCollection: widgetDefinitionsCollection
    };

    return new DeleteLayerConfirmationView(_.extend(defaultOptions, options));
  }

  describe('render', function () {
    it('should render properly', function () {
      view = createViewFn();
      view.render();

      expect(view.$('h2')[0].textContent.trim()).toEqual('editor.layers.delete.title');
      expect(view.$('p')[0].textContent.trim()).toEqual('editor.layers.delete.desc');

      expect(view.$('li').length).toEqual(3);
      expect(view.$('li')[0].textContent.trim()).toEqual('editor.layers.delete.link-to-export');

      expect(view.$('button.js-cancel > span')[0].textContent.trim()).toEqual('editor.layers.delete.cancel');
      expect(view.$('button.js-confirm > span')[0].textContent.trim()).toEqual('editor.layers.delete.confirm');
    });

    it('should show the name of the layer to be deleted', function () {
      spyOn(layerModel, 'getName').and.callThrough();

      view = createViewFn();
      view.render();

      expect(layerModel.getName).toHaveBeenCalled();
    });
  });
});
<commit_msg>Fix test<commit_after>var _ = require('underscore');
var Backbone = require('backbone');
var AnalysisDefinitionNodesCollection = require('../../../../../../javascripts/cartodb3/data/analysis-definition-nodes-collection');
var AnalysisDefinitionsCollection = require('../../../../../../javascripts/cartodb3/data/analysis-definitions-collection');
var ConfigModel = require('../../../../../../javascripts/cartodb3/data/config-model');
var DeleteLayerConfirmationView = require('../../../../../../javascripts/cartodb3/components/modals/remove-layer/delete-layer-confirmation-view');
var LayerDefinitionModel = require('../../../../../../javascripts/cartodb3/data/layer-definition-model');
var LayerDefinitionsCollection = require('../../../../../../javascripts/cartodb3/data/layer-definitions-collection');
var ModalsServiceModel = require('../../../../../../javascripts/cartodb3/components/modals/modals-service-model');
var UserActions = require('../../../../../../javascripts/cartodb3/data/user-actions');
var UserModel = require('../../../../../../javascripts/cartodb3/data/user-model');
var VisDefinitionModel = require('../../../../../../javascripts/cartodb3/data/vis-definition-model');
var WidgetDefinitionsCollection = require('../../../../../../javascripts/cartodb3/data/widget-definitions-collection');

describe('modals/delete-layer-confirmation-view', function () {
  var view;
  var modalModel;
  var userData;
  var configData;
  var configModel;
  var userModel;
  var analysisDefinitionNodesCollection;
  var layerModel;
  var layerDefinitionsCollection;
  var visDefinitionModel;
  var widgetDefinitionsCollection;
  var analysisDefinitionsCollection;
  var userActions;
  var modals;

  modalModel = new Backbone.Model();

  userData = {
    id: '8c253a9a-94d8-4042-883c-3aa81285e5e6',
    username: 'cdb'
  };

  configData = {
    base_url: '/u/manolo',
    maps_api_template: 'http://{user}.localhost.lan:8181'
  };

  configModel = new ConfigModel(configData);

  userModel = new UserModel(userData, { configModel: configModel });

  analysisDefinitionNodesCollection = new AnalysisDefinitionNodesCollection([], {
    configModel: configModel,
    userModel: userModel
  });

  layerModel = new LayerDefinitionModel({
    id: 'map-123',
    kind: 'carto',
    options: {
      type: 'CartoDB',
      color: '#FABADA',
      table_name: 'foo_bar',
      name: 'foo',
      letter: 'a',
      source: 'map-123',
      table_name_alias: 'foo_foo_bar',
      query: 'SELECT * FROM foo',
      tile_style: 'asdasd',
      visible: true
    }
  }, {
    configModel: configModel,
    parse: true
  });

  layerDefinitionsCollection = new LayerDefinitionsCollection([layerModel], {
    configModel: configModel,
    userModel: userModel,
    analysisDefinitionNodesCollection: analysisDefinitionNodesCollection,
    mapId: 'map-123',
    stateDefinitionModel: {}
  });

  visDefinitionModel = new VisDefinitionModel({
    name: 'foo',
    privacy: 'LINK',
    updated_at: '2016-06-21T15:30:06+00:00',
    type: 'derived',
    tags: ['foo', 'bar'],
    permission: {}
  }, {
    configModel: configModel
  });

  widgetDefinitionsCollection = new WidgetDefinitionsCollection([layerModel], {
    configModel: configModel,
    layerDefinitionsCollection: layerDefinitionsCollection,
    analysisDefinitionNodesCollection: analysisDefinitionNodesCollection,
    mapId: 'map-123'
  });

  analysisDefinitionsCollection = new AnalysisDefinitionsCollection([layerModel], {
    configModel: configModel,
    vizId: 'viz-123',
    layerDefinitionsCollection: layerDefinitionsCollection,
    analysisDefinitionNodesCollection: analysisDefinitionNodesCollection
  });

  userActions = new UserActions({
    userModel: userModel,
    analysisDefinitionNodesCollection: analysisDefinitionNodesCollection,
    analysisDefinitionsCollection: analysisDefinitionsCollection,
    layerDefinitionsCollection: layerDefinitionsCollection,
    widgetDefinitionsCollection: widgetDefinitionsCollection
  });

  modals = new ModalsServiceModel();

  function createViewFn (options) {
    var defaultOptions = {
      userActions: userActions,
      modals: modals,
      layerModel: layerModel,
      modalModel: modalModel,
      visDefinitionModel: visDefinitionModel,
      widgetDefinitionsCollection: widgetDefinitionsCollection
    };

    return new DeleteLayerConfirmationView(_.extend(defaultOptions, options));
  }

  describe('render', function () {
    it('should render properly', function () {
      view = createViewFn();
      view.render();

      expect(view.$('h2')[0].textContent.trim()).toEqual('editor.layers.delete.title');
      expect(view.$('p')[0].textContent.trim()).toEqual('editor.layers.delete.desc');

      expect(view.$('li').length).toEqual(3);
      expect(view.$('li')[0].textContent.trim()).toEqual('editor.layers.delete.link-to-export');

      expect(view.$('button.js-cancel > span')[0].textContent.trim()).toEqual('editor.layers.delete.cancel');
      expect(view.$('button.js-confirm > span')[0].textContent.trim()).toEqual('editor.layers.delete.confirm');
    });

    it('should show the name of the layer to be deleted', function () {
      spyOn(layerModel, 'getName').and.callThrough();

      view = createViewFn();
      view.render();

      expect(layerModel.getName).toHaveBeenCalled();
    });
  });
});
<|endoftext|>


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

  LD.Bear = function(gameState) {
    Phaser.Sprite.call(this, gameState.game, 300,
      gameState.game.world.height - 50, 'bear');

    this.gameState = gameState;

    this.game.physics.arcade.enable(this);
    this.phy = this.game.physics.arcade;

    this.roar = this.game.add.audio('roar');

    this.body.collideWorldBounds = true;
    this.body.bounce.y = 0.0;
    this.body.bounce.x = 0.0;
    this.body.gravity.y = 700;
    this.body.drag.x = 100;
    this.body.drag.y = 100;

    this.anchor.setTo(0.5, 1);
    this.direction = 1;
    this.acceleration = 1200;

    this.animations.add('run', [0, 1, 2, 3, 4], 5, true);
    this.run();
  };

  LD.Bear.prototype = Object.create(Phaser.Sprite.prototype);
  LD.Bear.prototype.constructor = LD.Bear;

  LD.Bear.prototype.update = function() {
    var platforms = this.gameState.level.platforms;
    this.game.physics.arcade.collide(this, platforms);
    this.game.physics.arcade.collide(this, this.gameState.level.layer[2]);

    if (this.body.touching.down) {
      this.run();
    }

  };

  LD.Bear.prototype.run = function() {
      this.direction = 1;
      this.scale.x = -1;

    // this.body.setSize(43, 35, -7, -5);
    this.body.velocity.x = 10 * this.direction;
    this.animations.play('run');
  };

  // BEEEEEEESSSSS!!!!!

  LD.Bee = function(gameState) {
   Phaser.Sprite.call(this, gameState.game, gameState.game.rnd.integerInRange(0, 360),
      gameState.game.rnd.integerInRange(0, 360), 'bee');

    this.gameState = gameState;

    this.game.physics.arcade.enable(this);
    this.phy = this.game.physics.arcade;
    // this.roar = this.game.add.audio('roar');\\
    this.body.collideWorldBounds = false;
    // this.body.bounce(0.50);
    this.animations.add('fly', [0, 1, 2], 20, true);
    this.animations.play('fly');
  };

  LD.Bee.prototype = Object.create(Phaser.Sprite.prototype);
  LD.Bee.constructor = LD.Bee;

  LD.Bee.prototype.update = function() {
    this.game.physics.arcade.collide(this, this.gameState.level.layer[2]);

    if (this.body.deltaX() > 0){
      this.scale.x = -0.5;
      this.scale.y = 0.5;
    } else {
      this.scale.x = 0.5;
      this.scale.y = 0.5;

    }

    if (this.phy.distanceToXY(this, this.gameState.player.x, this.gameState.player.y) > 150 ) {
    this.phy.moveToXY(this, Math.round(this.gameState.player.x - 50), Math.round(this.gameState.player.y - 100) , 300);
  }
  };

  LD.Enemy = function(gameState) {
    Phaser.Sprite.call(this, gameState.game, 300,
     gameState.game.world.height - 200, 'enemy1');

    this.gameState = gameState;

    this.game.physics.arcade.enable(this);
    this.phy = this.game.physics.arcade;

    this.emitter = this.game.add.emitter(0, 0, 100);
    this.emitter.makeParticles('blood_drop');
    this.emitter.gravity = 200;

    this.enemyPool = this.game.add.group();
    this.enemyPool.enableBody = true;
    this.enemyPool.physicsBodyType = Phaser.Physics.ARCADE;
    this.enemyPool.createMultiple(50, 'enemy1');
    this.enemyPool.setAll('anchor.x', 0.5);
    this.enemyPool.setAll('anchor.y', 0.5);
    this.enemyPool.setAll('outOfBoundsKill', true);
    this.enemyPool.setAll('checkWorldBounds', true);
    this.enemyPool.setAll('bounce', 0.3);
    this.enemyPool.setAll('gravity.y', 700);

    // Set the animation for each sprite
    this.enemyPool.forEach(function (enemy) {
      enemy.animations.add('attack', [ 0, 1, 2, 3, 4, 5, 6 ], 20, true);
      enemy.animations.add('die', [ 7, 8, 9, 10 ], 20, false);

    }, this.phy);

    this.nextEnemyAt = 0;
    this.enemyDelay = 4000;

  };

  LD.Enemy.prototype = Object.create(Phaser.Sprite.prototype);
  LD.Enemy.constructor = LD.Enemy;

  LD.Enemy.prototype.update = function() {
    this.phy.collide(this, this.gameState.level.layer[2]);
    this.phy.collide(this.enemyPool, this.gameState.level.layer[2]);

    if (this.nextEnemyAt < this.game.time.now && this.enemyPool.countDead() > 0) {
      this.nextEnemyAt = this.game.time.now + this.enemyDelay;
      var enemy = this.enemyPool.getFirstExists(false);
      // spawn at a random location top of the screen
      enemy.reset(this.gameState.player.x + 900, this.gameState.game.world.height - 150 );
      // also randomize the speed
      enemy.body.velocity.y = this.game.rnd.integerInRange(30, 360);
      enemy.play('attack');

    }

    this.enemyPool.forEach(function (enemy) {
      // this.phy.moveToXY(enemy, this.gameState.player.x, enemy.y, 100);

      if (enemy.x > this.gameState.player.x) {
        enemy.x -= 2;
        enemy.y += 2;
        } else {
        enemy.x += 2;
         enemy.y += 2;
      }
       if (enemy.body.deltaX() > 0){
          enemy.scale.x = 1;
        } else {
          enemy.scale.x = -1;
        }

      this.phy.overlap(enemy, this.gameState.player, function() {
        if (this.game.controls.fire.isDown) {
          this.explode(enemy.x, enemy.y);
          enemy.kill();
        }
      }, null, this);

    }, this, 200);

    // console.log(this.gameState.player.y, this.gameState.player.x);

  };

  LD.Enemy.prototype.explode = function(x, y) {
    this.emitter.x = x;
    this.emitter.y = y;
    this.emitter.start(true, 2000, null, 200);
  };

}());
<commit_msg>Flying enemies<commit_after>(function() {
  'use strict';

  LD.Bear = function(gameState) {
    Phaser.Sprite.call(this, gameState.game, 300,
      gameState.game.world.height - 50, 'bear');

    this.gameState = gameState;

    this.game.physics.arcade.enable(this);
    this.phy = this.game.physics.arcade;

    this.roar = this.game.add.audio('roar');

    this.body.collideWorldBounds = true;
    this.body.bounce.y = 0.0;
    this.body.bounce.x = 0.0;
    this.body.gravity.y = 700;
    this.body.drag.x = 100;
    this.body.drag.y = 100;

    this.anchor.setTo(0.5, 1);
    this.direction = 1;
    this.acceleration = 1200;

    this.animations.add('run', [0, 1, 2, 3, 4], 5, true);
    this.run();
  };

  LD.Bear.prototype = Object.create(Phaser.Sprite.prototype);
  LD.Bear.prototype.constructor = LD.Bear;

  LD.Bear.prototype.update = function() {
    var platforms = this.gameState.level.platforms;
    this.game.physics.arcade.collide(this, platforms);
    this.game.physics.arcade.collide(this, this.gameState.level.layer[2]);

    if (this.body.touching.down) {
      this.run();
    }

  };

  LD.Bear.prototype.run = function() {
      this.direction = 1;
      this.scale.x = -1;

    // this.body.setSize(43, 35, -7, -5);
    this.body.velocity.x = 10 * this.direction;
    this.animations.play('run');
  };

  // BEEEEEEESSSSS!!!!!

  LD.Bee = function(gameState) {
   Phaser.Sprite.call(this, gameState.game, gameState.game.rnd.integerInRange(0, 360),
      gameState.game.rnd.integerInRange(0, 360), 'bee');

    this.gameState = gameState;

    this.game.physics.arcade.enable(this);
    this.phy = this.game.physics.arcade;
    // this.roar = this.game.add.audio('roar');\\
    this.body.collideWorldBounds = false;
    // this.body.bounce(0.50);
    this.animations.add('fly', [0, 1, 2], 20, true);
    this.animations.play('fly');
  };

  LD.Bee.prototype = Object.create(Phaser.Sprite.prototype);
  LD.Bee.constructor = LD.Bee;

  LD.Bee.prototype.update = function() {
    this.game.physics.arcade.collide(this, this.gameState.level.layer[2]);

    if (this.body.deltaX() > 0){
      this.scale.x = -0.5;
      this.scale.y = 0.5;
    } else {
      this.scale.x = 0.5;
      this.scale.y = 0.5;

    }

    if (this.phy.distanceToXY(this, this.gameState.player.x, this.gameState.player.y) > 150 ) {
    this.phy.moveToXY(this, Math.round(this.gameState.player.x - 50), Math.round(this.gameState.player.y - 100) , 300);
  }
  };

  LD.Enemy = function(gameState) {
    Phaser.Sprite.call(this, gameState.game, 300,
     gameState.game.world.height - 200, 'enemy1');

    this.gameState = gameState;

    this.game.physics.arcade.enable(this);
    this.phy = this.game.physics.arcade;

    this.emitter = this.game.add.emitter(0, 0, 100);
    this.emitter.makeParticles('blood_drop');
    this.emitter.gravity = 200;

    this.enemyPool = this.game.add.group();
    this.enemyPool.enableBody = true;
    this.enemyPool.physicsBodyType = Phaser.Physics.ARCADE;
    this.enemyPool.createMultiple(50, 'enemy1');
    this.enemyPool.setAll('anchor.x', 0.5);
    this.enemyPool.setAll('anchor.y', 0.5);
    this.enemyPool.setAll('outOfBoundsKill', true);
    this.enemyPool.setAll('checkWorldBounds', true);
    this.enemyPool.setAll('bounce', 0.3);
    this.enemyPool.setAll('gravity.y', 700);

    // Set the animation for each sprite
    this.enemyPool.forEach(function (enemy) {
      enemy.animations.add('attack', [ 0, 1, 2, 3, 4, 5, 6 ], 20, true);
      enemy.animations.add('die', [ 7, 8, 9, 10 ], 20, false);

    }, this.phy);

    this.nextEnemyAt = 0;
    this.enemyDelay = 4000;

  };

  LD.Enemy.prototype = Object.create(Phaser.Sprite.prototype);
  LD.Enemy.constructor = LD.Enemy;

  LD.Enemy.prototype.update = function() {
    this.phy.collide(this, this.gameState.level.layer[2]);
    this.phy.collide(this.enemyPool, this.gameState.level.layer[2]);

    if (this.nextEnemyAt < this.game.time.now && this.enemyPool.countDead() > 0) {
      this.nextEnemyAt = this.game.time.now + this.enemyDelay;
      var enemy = this.enemyPool.getFirstExists(false);
      // spawn at a random location top of the screen
      enemy.reset(this.gameState.player.x + 900, this.gameState.game.world.height - 150 );
      // also randomize the speed
      enemy.body.velocity.y = this.game.rnd.integerInRange(30, 360);
      enemy.play('attack');
    }

    this.enemyPool.forEach(function (enemy) {
      this.phy.moveToXY(enemy, this.gameState.player.x, enemy.y, 100);

       if (enemy.body.deltaX() > 0){
          enemy.scale.x = 1;
        } else {
          enemy.scale.x = -1;
        }

      this.phy.overlap(enemy, this.gameState.player, function() {
        if (this.game.controls.fire.isDown) {
          this.explode(enemy.x, enemy.y);
          enemy.kill();
        }
      }, null, this);

    }, this, 200);

    // console.log(this.gameState.player.y, this.gameState.player.x);

  };

  LD.Enemy.prototype.explode = function(x, y) {
    this.emitter.x = x;
    this.emitter.y = y;
    this.emitter.start(true, 2000, null, 200);
  };

}());
<|endoftext|>


<commit_before>;(function($) {

	// Determine whether the test button display and functionality should be enabled.

	function enable(input) {

		var URL = input ? input.val() : $('div.link-mapping-test.admin input.url').val();
		var button = $('div.link-mapping-test.admin span.test');
		if(URL.length > 0) {
			button.fadeTo(250, 1, function() {

				button.removeClass('disabled');
			});
		}
		else {
			button.fadeTo(250, 0.4, function() {

				button.addClass('disabled');
			});
		}
	};

	// Test the link mapping chain for a given URL.

	function test(input) {

		var URL = input ? input.val() : $('div.link-mapping-test.admin input.url').val();
		$.getJSON('admin/misdirection/LinkMapping/getMappingChain', {
			map: URL
		},
		function(JSON) {

			var output = '';
			if(JSON) {

				// Construct the link mapping chain HTML representation.

				$.each(JSON, function(index, object) {

					output += "
";
					if(object['ResponseCode'] !== 404) {
						output += '
' + object['Counter'] + '
';
						output += '
Link Type ' + object['LinkType'] + '
';
						output += '
Mapped Link ' + object['MappedLink'] + '
';
						output += '
Redirect Link ' + object['RedirectLink'] + '
';
						output += '
Response Code ' + object['ResponseCode'] + '
';
						output += '
Priority ' + object['Priority'] + '
';
					}
					else {
						output += '
Maximum
';
						output += '
Response Code ' + object['ResponseCode'] + '
';
					}
					output += '
';
				});
			}
			else {
				output += "
";
				output += '
No Matches
';
				output += '
';
			}

			// Render the link mapping chain.

			$('div.link-mapping-test.admin div.results').html(output);
		});
	};

	// Bind the events dynamically.

	$.entwine('ss', function($) {

		// Trigger an interface update on key press.

		$('div.link-mapping-test.admin input.url').entwine({
			onchange: function() {

				enable($(this));
				$('#Form_EditForm').removeClass('changed');
			},
			onkeydown: function(event) {

				var input = $(this);

				// Trigger a test request on pressing enter.

				if(event.keyCode === 13) {
					if(input.val().length > 0) {
						test();

						// Trigger an interface update.

						$(this).change();
					}
					return false;
				}
			}
		});

		// Trigger an interface update and handle any test request.

		$('div.link-mapping-test.admin span.test').entwine({
			onmouseenter: function() {

				enable();
			},
			onclick: function() {

				if(!$(this).hasClass('disabled')) {

					// Test the link mapping chain for the given URL, and render this to the user.

					test();
				}
			}
		});
	});

})(jQuery);
<commit_msg>Implemented the ability to use the testing interface with the keyboard.<commit_after>;(function($) {

	// Determine whether the test button display and functionality should be enabled.

	function enable(input) {

		var URL = input ? input.val() : $('div.link-mapping-test.admin input.url').val();
		var button = $('div.link-mapping-test.admin span.test');
		if(URL.length > 0) {
			button.fadeTo(250, 1, function() {

				button.removeClass('disabled');
			});
		}
		else {
			button.fadeTo(250, 0.4, function() {

				button.addClass('disabled');
			});
		}
		$('#Form_EditForm').removeClass('changed');
	};

	// Test the link mapping chain for a given URL.

	function test(input) {

		var URL = input ? input.val() : $('div.link-mapping-test.admin input.url').val();
		$.getJSON('admin/misdirection/LinkMapping/getMappingChain', {
			map: URL
		},
		function(JSON) {

			var output = '';
			if(JSON) {

				// Construct the link mapping chain HTML representation.

				$.each(JSON, function(index, object) {

					output += "
";
					if(object['ResponseCode'] !== 404) {
						output += '
' + object['Counter'] + '
';
						output += '
Link Type ' + object['LinkType'] + '
';
						output += '
Mapped Link ' + object['MappedLink'] + '
';
						output += '
Redirect Link ' + object['RedirectLink'] + '
';
						output += '
Response Code ' + object['ResponseCode'] + '
';
						output += '
Priority ' + object['Priority'] + '
';
					}
					else {
						output += '
Maximum
';
						output += '
Response Code ' + object['ResponseCode'] + '
';
					}
					output += '
';
				});
			}
			else {
				output += "
";
				output += '
No Matches
';
				output += '
';
			}

			// Render the link mapping chain.

			$('div.link-mapping-test.admin div.results').html(output);
		});
	};

	// Bind the events dynamically.

	$.entwine('ss', function($) {

		// Trigger an interface update on key press.

		$('div.link-mapping-test.admin input.url').entwine({
			onchange: function() {

				enable($(this));
			},
			onkeydown: function(event) {

				var input = $(this);

				// Trigger a test request on pressing enter.

				if(event.keyCode === 13) {
					if(input.val().length > 0) {
						test();

						// Trigger an interface update.

						input.change();
					}
					return false;
				}
			}
		});

		// Trigger an interface update and handle any test request.

		$('div.link-mapping-test.admin span.test').entwine({
			onmouseenter: function() {

				enable();
			},
			onclick: function() {

				if(!$(this).hasClass('disabled')) {

					// Test the link mapping chain for the given URL, and render this to the user.

					test();
				}
			}
		});
	});

})(jQuery);
<|endoftext|>