<commit_before>/**
 * ng-pub-sub
 * @module service.storage
 */
angular.module('service.storage', [
        'service.notification'
    ])

    .factory('storage', function (notification) {
        'use strict';

        var collection = [
            {user: 'willy1981', text: 'The world won\'t listen!', date: '22.1.2014 10:40:10'},
            {user: 'amanda', text: 'Say it loud? This is ridiculous!', date: '22.1.2014 11:36:45'},
            {user: 'jeff', text: '!@#* - WTF?', date: '22.1.2014 11:53:03'}
        ];

        var get = function () {
            if (angular.isArray(collection)) {
                return collection;
            }

           throw new Error('Storage is not readable!');
        };

        var getCount = function () {
            try {
                return collection.length;
            } catch (e) {
                throw e;
            }
        };

        var add = function (item) {
            if (angular.isObject(item) && !angular.isArray(item)) {
                try {
                    collection.push(item);
                    notification.createMessage(item);
                } catch (e) {
                    throw e;
                }
            } else {
                throw new TypeError('Can not add item - storage item has to be an object.');
            }
        };

        var remove = function (index) {
            if (
                angular.isObject(collection[index]) &&
                !angular.isArray(collection[index])
            ) {
                try {
                    var item = collection[index];

                    collection.splice(index, 1);
                    notification.deleteMessage(item);
                } catch (e) {
                    throw e;
                }
            } else {
                throw new TypeError('Can not delete item - storage item has to be an object.');
            }
        };

        // Reveal public API.
        return {
            getMessages: get,
            getMessageCount: getCount,
            addMessage: add,
            removeMessage: remove
        };
    });
<commit_msg>Fixed code style.<commit_after>/**
 * ng-pub-sub
 * @module service.storage
 */
angular.module('service.storage', [
        'service.notification'
    ])

    .factory('storage', function (notification) {
        'use strict';

        var collection = [
            {user: 'willy1981', text: 'The world won\'t listen!', date: '22.1.2014 10:40:10'},
            {user: 'amanda', text: 'Say it loud? This is ridiculous!', date: '22.1.2014 11:36:45'},
            {user: 'jeff', text: '!@#* - WTF?', date: '22.1.2014 11:53:03'}
        ];

        var get = function () {
            if (angular.isArray(collection)) {
                return collection;
            }

            throw new Error('Storage is not readable!');
        };

        var getCount = function () {
            try {
                return collection.length;
            } catch (e) {
                throw e;
            }
        };

        var add = function (item) {
            if (angular.isObject(item) && !angular.isArray(item)) {
                try {
                    collection.push(item);
                    notification.createMessage(item);
                } catch (e) {
                    throw e;
                }
            } else {
                throw new TypeError('Can not add item - storage item has to be an object.');
            }
        };

        var remove = function (index) {
            if (
                angular.isObject(collection[index]) &&
                !angular.isArray(collection[index])
            ) {
                try {
                    var item = collection[index];

                    collection.splice(index, 1);
                    notification.deleteMessage(item);
                } catch (e) {
                    throw e;
                }
            } else {
                throw new TypeError('Can not delete item - storage item has to be an object.');
            }
        };

        // Reveal public API.
        return {
            getMessages: get,
            getMessageCount: getCount,
            addMessage: add,
            removeMessage: remove
        };
    });
<|endoftext|>


<commit_before>import React, { Children, cloneElement, Component } from 'react';
import { createComponent } from 'react-fela';

const Container = createComponent(
  ({ theme, open }) => ({
    ifMini: {
      '> div:nth-child(2)': {
        clear: 'both',
        transform: open ? 'scaleY(1)' : 'scaleY(0)',
        maxHeight: open ? 500 : 0,
        overflow: 'auto',
        transformOrigin: 'top',
        transition: 'all 0.25s ease-in-out',
      },
    },
  }),
  'div',
  p => Object.keys(p)
);

const Button = createComponent(
  ({ theme, open, inverse, size = 20 }) => ({
    float: 'right',
    padding: theme.space2,
    margin: theme.space3,
    width: Math.round(size * 1.3),
    height: size,
    position: 'relative',
    cursor: 'pointer',
    ifSmallUp: {
      display: 'none',
    },
    '> span': {
      display: 'block',
      position: 'absolute',
      height: Math.round(size / 6),
      borderRadius: Math.round(size / 6),
      width: '100%',
      background: inverse ? theme.light : theme.color,
      left: 0,
      transform: 'rotate(0deg)',
      transition: '.25s ease-in-out',
      ':nth-child(1)': {
        top: open ? Math.round(size / 3) : 0,
        width: open && '0%',
        left: open && '50%',
      },
      ':nth-child(2)': {
        top: Math.round(size / 3),
        transform: open && 'rotate(45deg)',
      },
      ':nth-child(3)': {
        top: Math.round(size / 3),
        transform: open && 'rotate(-45deg)',
      },
      ':nth-child(4)': {
        top: open ? Math.round(size / 3) : Math.round(size / 3) * 2,
        width: open && '0%',
        left: open && '50%',
      },
    },
  }),
  ({ className, onClick }) =>
    (

),
  p => Object.keys(p)
);

class Toggler extends Component {
  render() {
    const {
      className,
      children,
      router,
      pathname,
      query,
      ...props
    } = this.props;
    const open = query.nav === null;

    return (
      <Container className={className} open={open}>
        <Button
          {...props}
          open={open}
          onClick={() =>
            router.push({
              pathname,
              query: { ...query, nav: !open ? null : undefined },
            })}
        />

          {Children.map(children, child => cloneElement(child, props))}

      </Container>
    );
  }
}
export default Toggler;
<commit_msg>fix nav-error<commit_after>import React, { Children, cloneElement, Component } from 'react';
import PropTypes from 'prop-types';
import { createComponent } from 'react-fela';

const Container = createComponent(
  ({ theme, open }) => ({
    ifMini: {
      '> div:nth-child(2)': {
        clear: 'both',
        transform: open ? 'scaleY(1)' : 'scaleY(0)',
        maxHeight: open ? 500 : 0,
        overflow: 'auto',
        transformOrigin: 'top',
        transition: 'all 0.25s ease-in-out',
      },
    },
  }),
  'div',
  p => Object.keys(p)
);

const Button = createComponent(
  ({ theme, open, inverse, size = 20 }) => ({
    float: 'right',
    padding: theme.space2,
    margin: theme.space3,
    width: Math.round(size * 1.3),
    height: size,
    position: 'relative',
    cursor: 'pointer',
    ifSmallUp: {
      display: 'none',
    },
    '> span': {
      display: 'block',
      position: 'absolute',
      height: Math.round(size / 6),
      borderRadius: Math.round(size / 6),
      width: '100%',
      background: inverse ? theme.light : theme.color,
      left: 0,
      transform: 'rotate(0deg)',
      transition: '.25s ease-in-out',
      ':nth-child(1)': {
        top: open ? Math.round(size / 3) : 0,
        width: open && '0%',
        left: open && '50%',
      },
      ':nth-child(2)': {
        top: Math.round(size / 3),
        transform: open && 'rotate(45deg)',
      },
      ':nth-child(3)': {
        top: Math.round(size / 3),
        transform: open && 'rotate(-45deg)',
      },
      ':nth-child(4)': {
        top: open ? Math.round(size / 3) : Math.round(size / 3) * 2,
        width: open && '0%',
        left: open && '50%',
      },
    },
  }),
  ({ className, onClick }) =>
    (

),
  p => Object.keys(p)
);

class Toggler extends Component {
  state = { open: false };

  render() {
    const { className, children, isOpen, ...props } = this.props;
    const { open } = this.state;

    const toggleState = () => this.setState({ open: !open });
    const toggleMenu = this.props.toggleMenu || toggleState;

    return (
      <Container className={className} open={open}>
        <Button
          {...props}
          open={isOpen || open}
          onClick={toggleMenu}
          /* onClick={() =>
            router.push({
              pathname,
              query: { ...query, nav: !open ? null : undefined },
            })} */
        />

          {Children.map(children, child => cloneElement(child, props))}

      </Container>
    );
  }
}
Toggler.PropTypes = {
  toggleMenu: PropTypes.func,
  isOpen: PropTypes.bool,
};
Toggler.defaultProps = {
  toggleMenu: undefined,
  isOpen: false,
};
export default Toggler;
<|endoftext|>


<commit_before>define([
    'jquery',
    'game/model',
    'game/view',
    'game/dataStructures/operation',
    'game/puzzleGenerator',
    'hbs!/onetwotree/public/resources/templates/inputValue',
    'app.config'
], function ($, GameModel, GameView, Operation, PuzzleGenerator,
    _InputValueTemplate, Config) {

    'use strict';

    var model, /* The model for the game. */
        view, /* The view for the game. */
        setAppListeners; /* Function to set any application-wide listeners. */

    function setListeners() {

        /* Set listener on nodes. */
        $('.nodeBox .node').click(function (event) {
            var index = parseInt(event.target.id),
                node = model.puzzle.nodes[index],
                nodeStr = '#' + index + 'node';

            /* Remove any exisiting forms. */
            $('#inputForm').remove();

            /* Inject HTML for this form into node. */
            $(nodeStr).html(_InputValueTemplate(node));
            $('#inputValue').focus();

            /* Display validation feedback as user types input. */
            $('#inputValue').keypress(function () {
                var value,
                    valid = false;

                value = parseInt($('#inputValue').val());

                if ((value < 0) || (value > 100)) {
                    $('#inputForm').attr('class',
                        'form-group has-error');
                } else if (value === 0) {
                    $('#inputForm').attr('class',
                        'form-group');
                } else {
                    valid = true;
                    $('#inputForm').attr('class',
                        'form-group has-success'
                    );
                }

            });

            /* Parse input and process if valid. */
            $('#inputValue').change(function () {
                var value;

                value = parseInt($('#inputValue').val());

                if (value > 0) {
                    model.playTurnNode(index, value);
                    view.render();
                    setListeners();
                }
            });

        });

        /* Set listener on operations. */
        $('.nodeBox .op').click(function () {
            /* Remove any existing forms. */
            $('#inputForm').remove();
        });

        $('.nodeBox .op').change(function (event) {
            var index = parseInt(event.target.id),
                allNodes = model.puzzle.nodes,
                opStr = '#' + index + 'op',
                op;

            switch ($(opStr).val()) {
                case Config.addSymbol:
                    op = Operation.ADD();
                    break;
                case Config.subSymbol:
                    op = Operation.SUB();
                    break;
                case Config.multSymbol:
                    op = Operation.MULT();
                    break;
                case Config.divSymbol:
                    op = Operation.DIV();
                    break;
                default:
                    op = Operation.NULL;
            }

            if (index >= 0 && index < allNodes.length) {
                model.playTurnOp(index, op);
                view.render();
                setListeners();
            }

        });

        setAppListeners();
    }

    /**
     * Constructor for the controller for the game MVC.
     * @param {{timer: boolean,
                    difficulty: string,
                    setAppListeners: function}}
                settings - the user-selected settings for the game
     */
    return function GameController(settings) {

        this.settings = settings;

        setAppListeners = settings.setAppListeners;

        /**
         * Initialize the game controller with a new puzzle, model, and view.
         */
        this.init = function () {

            var puzzleSpecs;

            switch (this.settings.difficulty) {
                case 'Easy':
                    puzzleSpecs = PuzzleGenerator.Easy();
                    break;
                case 'Medium':
                    puzzleSpecs = PuzzleGenerator.Medium();
                    break;
                case 'Hard':
                    puzzleSpecs = PuzzleGenerator.Hard();
                    break;
            }

            model = new GameModel(puzzleSpecs);
            view = new GameView('#board', model);

            this.startGame();
        };

        /**
         * Reset the game board to its initial state.
         */
        this.reset = function () {
            this.cancel();
            model.reset();
            this.startGame();
        };

        /**
         * Cancel this game.
         */
        this.cancel = function () {
            clearInterval(this.pointsTimer);
        };

        /**
         * Start the game.
         */
        this.startGame = function () {
            var that = this,
                i;

            for (i = 0; i < model.puzzle.nodes.length; i++) {
                model.puzzle.nodes[i].verify();
            }

            view.render();
            setListeners();

            /* Start the game timer if applicable. */
            if (settings.timer) {

                this.pointsTimer = setInterval(function () {

                    model.points -= 5;

                    /* Game is over if points have run out. */
                    if (model.points <= 0) {
                        model.gameOver = true;
                    }

                    /*
                     * If game is over (because points have run out or because
                     * game is in winning state), stop the timer.
                     */
                    if (model.gameOver) {
                        clearInterval(that.pointsTimer);
                    }

                    /* Update the points display. */
                    view.renderPoints();

                }, 400);

            }
        };

        this.render = function () {
            view.render();
            setListeners();
        };

    };
});<commit_msg>Reset game board after previous win.<commit_after>define([
    'jquery',
    'game/model',
    'game/view',
    'game/dataStructures/operation',
    'game/puzzleGenerator',
    'hbs!/onetwotree/public/resources/templates/inputValue',
    'app.config'
], function ($, GameModel, GameView, Operation, PuzzleGenerator,
    _InputValueTemplate, Config) {

    'use strict';

    var model, /* The model for the game. */
        view, /* The view for the game. */
        setAppListeners; /* Function to set any application-wide listeners. */

    function setListeners() {

        /* Set listener on nodes. */
        $('.nodeBox .node').click(function (event) {
            var index = parseInt(event.target.id),
                node = model.puzzle.nodes[index],
                nodeStr = '#' + index + 'node';

            /* Remove any exisiting forms. */
            $('#inputForm').remove();

            /* Inject HTML for this form into node. */
            $(nodeStr).html(_InputValueTemplate(node));
            $('#inputValue').focus();

            /* Display validation feedback as user types input. */
            $('#inputValue').keypress(function () {
                var value,
                    valid = false;

                value = parseInt($('#inputValue').val());

                if ((value < 0) || (value > 100)) {
                    $('#inputForm').attr('class',
                        'form-group has-error');
                } else if (value === 0) {
                    $('#inputForm').attr('class',
                        'form-group');
                } else {
                    valid = true;
                    $('#inputForm').attr('class',
                        'form-group has-success'
                    );
                }

            });

            /* Parse input and process if valid. */
            $('#inputValue').change(function () {
                var value;

                value = parseInt($('#inputValue').val());

                if (value > 0) {
                    model.playTurnNode(index, value);
                    view.render();
                    setListeners();
                }
            });

        });

        /* Set listener on operations. */
        $('.nodeBox .op').click(function () {
            /* Remove any existing forms. */
            $('#inputForm').remove();
        });

        $('.nodeBox .op').change(function (event) {
            var index = parseInt(event.target.id),
                allNodes = model.puzzle.nodes,
                opStr = '#' + index + 'op',
                op;

            switch ($(opStr).val()) {
                case Config.addSymbol:
                    op = Operation.ADD();
                    break;
                case Config.subSymbol:
                    op = Operation.SUB();
                    break;
                case Config.multSymbol:
                    op = Operation.MULT();
                    break;
                case Config.divSymbol:
                    op = Operation.DIV();
                    break;
                default:
                    op = Operation.NULL;
            }

            if (index >= 0 && index < allNodes.length) {
                model.playTurnOp(index, op);
                view.render();
                setListeners();
            }

        });

        setAppListeners();
    }

    /**
     * Constructor for the controller for the game MVC.
     * @param {{timer: boolean,
                    difficulty: string,
                    setAppListeners: function}}
                settings - the user-selected settings for the game
     */
    return function GameController(settings) {

        this.settings = settings;

        setAppListeners = settings.setAppListeners;

        /**
         * Initialize the game controller with a new puzzle, model, and view.
         */
        this.init = function () {

            var puzzleSpecs;

            switch (this.settings.difficulty) {
                case 'Easy':
                    puzzleSpecs = PuzzleGenerator.Easy();
                    break;
                case 'Medium':
                    puzzleSpecs = PuzzleGenerator.Medium();
                    break;
                case 'Hard':
                    puzzleSpecs = PuzzleGenerator.Hard();
                    break;
            }

            model = new GameModel(puzzleSpecs);
            view = new GameView('#board', model);

            this.startGame();
        };

        /**
         * Reset the game board to its initial state.
         */
        this.reset = function () {
            this.cancel();
            model.reset();
            this.startGame();
        };

        /**
         * Cancel this game.
         */
        this.cancel = function () {
            clearInterval(this.pointsTimer);
        };

        /**
         * Start the game.
         */
        this.startGame = function () {
            var that = this,
                i;

            for (i = 0; i < model.puzzle.nodes.length; i++) {
                model.puzzle.nodes[i].verify();
            }

            $('#board').removeClass('gameOver');
            $('#alert').empty();
            view.render();
            setListeners();

            /* Start the game timer if applicable. */
            if (settings.timer) {

                this.pointsTimer = setInterval(function () {

                    model.points -= 5;

                    /* Game is over if points have run out. */
                    if (model.points <= 0) {
                        model.gameOver = true;
                    }

                    /*
                     * If game is over (because points have run out or because
                     * game is in winning state), stop the timer.
                     */
                    if (model.gameOver) {
                        clearInterval(that.pointsTimer);
                    }

                    /* Update the points display. */
                    view.renderPoints();

                }, 400);

            }
        };

        this.render = function () {
            view.render();
            setListeners();
        };

    };
});<|endoftext|>


<commit_before>import Ember from "ember";
import config from "../config/environment";
import rollbar from 'rollbar';

export default Ember.Service.extend({
  session: Ember.inject.service(),

  getReason(reason) {
    return reason instanceof Error || typeof reason !== "object" ?
          reason : JSON.stringify(reason);
  },

  error: function(reason) {
    if (reason.status === 0) {
      return;
    }
    console.info(reason);
    if (config.environment === "production" || config.staging) {
      var userName = this.get("session.currentUser.fullName");
      var userId = this.get("session.currentUser.id");
      var error = this.getReason(reason);
      var environment = config.staging ? "staging" : config.environment;
      var version = `${config.APP.SHA} (shared ${config.APP.SHARED_SHA})`;

      var airbrake = new airbrakeJs.Client({
        projectId: config.APP.AIRBRAKE_PROJECT_ID,
        projectKey: config.APP.AIRBRAKE_PROJECT_KEY
      });
      airbrake.setHost(config.APP.AIRBRAKE_HOST);
      airbrake.notify({ error, context: { userId, userName, environment, version } });
      rollbar.error(error);
    }
  }
});
<commit_msg>add user details to rollbar<commit_after>import Ember from "ember";
import config from "../config/environment";
import rollbar from 'rollbar';

export default Ember.Service.extend({
  session: Ember.inject.service(),

  getReason(reason) {
    return reason instanceof Error || typeof reason !== "object" ?
          reason : JSON.stringify(reason);
  },

  error: function(reason) {
    if (reason.status === 0) {
      return;
    }
    console.info(reason);
    if (config.environment === "production" || config.staging) {
      var userName = this.get("session.currentUser.fullName");
      var userId = this.get("session.currentUser.id");
      var error = this.getReason(reason);
      var environment = config.staging ? "staging" : config.environment;
      var version = `${config.APP.SHA} (shared ${config.APP.SHARED_SHA})`;

      var airbrake = new airbrakeJs.Client({
        projectId: config.APP.AIRBRAKE_PROJECT_ID,
        projectKey: config.APP.AIRBRAKE_PROJECT_KEY
      });
      airbrake.setHost(config.APP.AIRBRAKE_HOST);
      airbrake.notify({ error, context: { userId, userName, environment, version } });
      rollbar.error(error, { id: userId, username: userName});
    }
  }
});
<|endoftext|>


<commit_before>'use strict';

require('mocha-eslint')(['lib', 'test'], {
  timeout: 5000,
});
<commit_msg>bump eslint timeout (appveyor can be slow)<commit_after>'use strict';

require('mocha-eslint')(['lib', 'test'], {
  timeout: 20000,
});
<|endoftext|>


<commit_before>const config = require('../../../config')
const authorisedRequest = require('../../lib/authorised-request')

const Order = {
  save (token, data) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order`,
      method: 'POST',
      body: data,
    })
  },

  update (token, id, data) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order/${id}`,
      method: 'PATCH',
      body: data,
    })
  },

  saveSubscribers (token, id, body) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order/${id}/subscriber-list`,
      method: 'PUT',
      body,
    })
  },

  getAssignees (token, id) {
    return authorisedRequest(token, `${config.apiRoot}/v3/omis/order/${id}/assignee`)
  },

  saveAssignees (token, id, body) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order/${id}/assignee`,
      method: 'PATCH',
      body,
    })
  },

  forceSaveAssignees (token, id, body) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order/${id}/assignee?force-delete=1`,
      method: 'PATCH',
      body,
    })
  },

  getSubscribers (token, id) {
    return authorisedRequest(token, `${config.apiRoot}/v3/omis/order/${id}/subscriber-list`)
  },

  getById (token, id) {
    return authorisedRequest(token, `${config.apiRoot}/v3/omis/order/${id}`)
  },

  previewQuote (token, id) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order/${id}/quote/preview`,
      method: 'POST',
    })
  },

  getQuote (token, id) {
    return authorisedRequest(token, `${config.apiRoot}/v3/omis/order/${id}/quote`)
  },

  createQuote (token, id) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order/${id}/quote`,
      method: 'POST',
    })
  },

  cancelQuote (token, id) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order/${id}/quote/cancel`,
      method: 'POST',
    })
  },

  getInvoice (token, id) {
    return authorisedRequest(token, `${config.apiRoot}/v3/omis/order/${id}/invoice`)
  },

  getPayments (token, id) {
    return authorisedRequest(token, `${config.apiRoot}/v3/omis/order/${id}/payment`)
  },

  savePayments (token, id, body) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order/${id}/payment`,
      method: 'POST',
      body,
    })
  },

  complete (token, id, body) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order/${id}/complete`,
      method: 'POST',
      body,
    })
  },
}

module.exports = {
  Order,
}
<commit_msg>Add ability to cancel order to Order model<commit_after>const config = require('../../../config')
const authorisedRequest = require('../../lib/authorised-request')

const Order = {
  save (token, data) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order`,
      method: 'POST',
      body: data,
    })
  },

  update (token, id, data) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order/${id}`,
      method: 'PATCH',
      body: data,
    })
  },

  saveSubscribers (token, id, body) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order/${id}/subscriber-list`,
      method: 'PUT',
      body,
    })
  },

  getAssignees (token, id) {
    return authorisedRequest(token, `${config.apiRoot}/v3/omis/order/${id}/assignee`)
  },

  saveAssignees (token, id, body) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order/${id}/assignee`,
      method: 'PATCH',
      body,
    })
  },

  forceSaveAssignees (token, id, body) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order/${id}/assignee?force-delete=1`,
      method: 'PATCH',
      body,
    })
  },

  getSubscribers (token, id) {
    return authorisedRequest(token, `${config.apiRoot}/v3/omis/order/${id}/subscriber-list`)
  },

  getById (token, id) {
    return authorisedRequest(token, `${config.apiRoot}/v3/omis/order/${id}`)
  },

  previewQuote (token, id) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order/${id}/quote/preview`,
      method: 'POST',
    })
  },

  getQuote (token, id) {
    return authorisedRequest(token, `${config.apiRoot}/v3/omis/order/${id}/quote`)
  },

  createQuote (token, id) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order/${id}/quote`,
      method: 'POST',
    })
  },

  cancelQuote (token, id) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order/${id}/quote/cancel`,
      method: 'POST',
    })
  },

  getInvoice (token, id) {
    return authorisedRequest(token, `${config.apiRoot}/v3/omis/order/${id}/invoice`)
  },

  getPayments (token, id) {
    return authorisedRequest(token, `${config.apiRoot}/v3/omis/order/${id}/payment`)
  },

  savePayments (token, id, body) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order/${id}/payment`,
      method: 'POST',
      body,
    })
  },

  complete (token, id, body) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order/${id}/complete`,
      method: 'POST',
      body,
    })
  },

  cancel (token, id, body) {
    return authorisedRequest(token, {
      url: `${config.apiRoot}/v3/omis/order/${id}/cancel`,
      method: 'POST',
      body,
    })
  },
}

module.exports = {
  Order,
}
<|endoftext|>


<commit_before>// keybindings and command propmpt options

const config = require('../settings/config.js')

const searchAttribute = require('./core/searchAttribute.js')
const showMetamodel = require('./core/showMetamodel.js')
const deleteRestoreConcepts = require('./core/deleteRestoreConcepts.js')

const printMsgHTML = require('./helpers/printMsgHTML.js')
const save = require('./helpers/save.js')
const theme = require('./helpers/theme.js')
const watcher = require('./helpers/watcher.js')

const suggestion = require('./imp/suggestion.js')

const buttonHelpers = require('./buttonHelpers.js')

module.exports = function (
  cy,
  selectedNode,
  selectedEdge,
  srcNode,
  trgNode,
  phase,
  graphNodes
) {
  // help menu for macOs
  const helpMenuMacOS = `• focus on console: ⌘L
• add Edge: ⌘E
• delete element: ⌘⌫
• restore node: ⌘Z
• save as: ⇧⌘S
• view phase metamodel: metamodel
• change color theme: toggle
• clear sidebar: clear
• model validation: validate
• security suggestions: suggestion
• search for attribures: keyword`

  // help menu for Linux and Windows
  const helpMenu = `• focus on console: ctrl+L
• add Edge: ctrl+E
• delete element: ctrl+backspace
• restore node: ctrl+Z
• save as: shift+ctrl+S
• view phase metamodel: metamodel
• change color theme: toggle
• clear sidebar: clear
• model validation: validate
• security suggestions: suggestion
• search for attribures: keyword`

  // adds the url of ASTo docs
  const docsURLBtn = `click to view <button id='url-button' class='menu-btn' style='color: var(--main-tx-color); background-color: var(--main-bg-color); width: 45px; height: 25px;'>docs</button>`

  const cmdID = document.getElementById('cmd-id')
  const labelId = document.getElementById('input-label-id')
  // indicate focus on the console by making the > blue
  cmdID.addEventListener('focus', e => {
    labelId.style.color = config.blue
  })
  // indicate loss of focus on the console by making the > default color
  cmdID.addEventListener('blur', () => {
    labelId.style.color = config.text
  })

  // removes the focus from the console when tapping on the graph container
  cy.on('tap', selection => cmdID.blur())

  // console commands
  const commands = () => {
    const input = document.getElementById('cmd-id').value
    document.getElementById('cmd-id').value = ''

    // declare input of console commmands
    switch (input) {
      case 'help':
        // checks the platform to display the corrent help menu
        process.platform === 'darwin'
          ? printMsgHTML(helpMenuMacOS)
          : printMsgHTML(helpMenu)

        printMsgHTML(docsURLBtn)
        // opens the wiki page with the default browser
        document.getElementById('url-button').addEventListener('click', () => {
          require('electron').shell.openExternal(config.docsURL)
        })
        break
      case 'suggestion':
        if (phase === 'implementation') {
          suggestion(cy)
        }
        break
      case 'validate':
        buttonHelpers.validateHelper(cy, phase)
        break
      case 'metamodel':
        showMetamodel(phase)
        break
      case 'toggle':
        if (config.colorTheme === 'dark') {
          theme.setThemeGraph(cy, 'light')
          config.colorTheme = 'light'
        } else {
          theme.setThemeGraph(cy, 'dark')
          config.colorTheme = 'dark'
        }
        break
      case 'clear':
        document.getElementById('message-area-id').textContent = ''
        break
      case '':
        break
      default:
        searchAttribute(cy, input)
    }
  }

  // declare keydown listeners
  document.addEventListener('keydown', event => {
    let metaKey = ''
    // checks the platform to assign the correct meta key
    process.platform === 'darwin'
      ? (metaKey = event.metaKey)
      : (metaKey = event.ctrlKey)

    // focus on the app console
    if (metaKey === true && event.code === 'KeyL') {
      cmdID.focus()
    }
    // add an edge specific to each phase
    if (metaKey === true && event.code === 'KeyE') {
      // checks for undefined selections
      if (Object.keys(srcNode.out).length !== 0) {
        buttonHelpers.addEdge(cy, srcNode.out, trgNode.out, phase)
        cy.edges().addClass('label-edges')
      }
    }
    // delete nodes or edges with meta + Backspace
    if (metaKey === true && event.code === 'Backspace') {
      deleteRestoreConcepts.deleteConcept(
        cy,
        selectedNode.out,
        selectedEdge.out
      )

      watcher.nodes(graphNodes, cy)
    }
    // restore nodes with meta + z
    if (metaKey === true && event.code === 'KeyZ') {
      deleteRestoreConcepts.restoreNode(cy)

      watcher.nodes(graphNodes, cy)
    }
    // save graph on meta + s
    if (event.shiftKey === true && metaKey === true && event.code === 'KeyS') {
      save(cy)
    }
    // listens for the ENTER key when focus is on the console
    if (document.activeElement === cmdID && event.code === 'Enter') {
      commands()
    }
    // developer mode message when a user wants to reload the app, meta + r
    if (metaKey === true && event.code === 'KeyR') {
      printMsgHTML(
        'Window reload is disabled in default mode.'
      )
      printMsgHTML('Start the app in develper mode it.')
      printMsgHTML('npm run dev')
    }
  })
}
<commit_msg>commands need the ':' prefix<commit_after>// keybindings and command propmpt options

const config = require('../settings/config.js')

const searchAttribute = require('./core/searchAttribute.js')
const showMetamodel = require('./core/showMetamodel.js')
const deleteRestoreConcepts = require('./core/deleteRestoreConcepts.js')

const printMsgHTML = require('./helpers/printMsgHTML.js')
const save = require('./helpers/save.js')
const theme = require('./helpers/theme.js')
const watcher = require('./helpers/watcher.js')

const suggestion = require('./imp/suggestion.js')

const buttonHelpers = require('./buttonHelpers.js')

module.exports = function (
  cy,
  selectedNode,
  selectedEdge,
  srcNode,
  trgNode,
  phase,
  graphNodes
) {
  // help menu for macOs
  const helpMenuMacOS = `• focus on console: ⌘L
• add Edge: ⌘E
• delete element: ⌘⌫
• restore node: ⌘Z
• save as: ⇧⌘S
• view phase metamodel: :metamodel
• change color theme: :toggle
• clear sidebar: :clear
• model validation: :validate
• security suggestions: :suggestion
• search for attribures: :keyword`

  // help menu for Linux and Windows
  const helpMenu = `• focus on console: ctrl+L
• add Edge: ctrl+E
• delete element: ctrl+backspace
• restore node: ctrl+Z
• save as: shift+ctrl+S
• view phase metamodel: :metamodel
• change color theme: :toggle
• clear sidebar: :clear
• model validation: :validate
• security suggestions: :suggestion
• search for attribures: :keyword`

  // adds the url of ASTo docs
  const docsURLBtn = `click to view <button id='url-button' class='menu-btn' style='color: var(--main-tx-color); background-color: var(--main-bg-color); width: 45px; height: 25px;'>docs</button>`

  const cmdID = document.getElementById('cmd-id')
  const labelId = document.getElementById('input-label-id')
  // indicate focus on the console by making the > blue
  cmdID.addEventListener('focus', e => {
    labelId.style.color = config.blue
  })
  // indicate loss of focus on the console by making the > default color
  cmdID.addEventListener('blur', () => {
    labelId.style.color = config.text
  })

  // removes the focus from the console when tapping on the graph container
  cy.on('tap', selection => cmdID.blur())

  // console commands
  const commands = () => {
    const input = document.getElementById('cmd-id').value
    document.getElementById('cmd-id').value = ''

    // declare input of console commmands
    switch (input) {
      case 'help':
        // checks the platform to display the corrent help menu
        process.platform === 'darwin'
          ? printMsgHTML(helpMenuMacOS)
          : printMsgHTML(helpMenu)

        printMsgHTML(docsURLBtn)
        // opens the wiki page with the default browser
        document.getElementById('url-button').addEventListener('click', () => {
          require('electron').shell.openExternal(config.docsURL)
        })
        break
      case ':suggestion':
        if (phase === 'implementation') {
          suggestion(cy)
        }
        break
      case ':validate':
        buttonHelpers.validateHelper(cy, phase)
        break
      case ':metamodel':
        showMetamodel(phase)
        break
      case ':toggle':
        if (config.colorTheme === 'dark') {
          theme.setThemeGraph(cy, 'light')
          config.colorTheme = 'light'
        } else {
          theme.setThemeGraph(cy, 'dark')
          config.colorTheme = 'dark'
        }
        break
      case ':clear':
        document.getElementById('message-area-id').textContent = ''
        break
      case '':
        break
      default:
        searchAttribute(cy, input)
    }
  }

  // declare keydown listeners
  document.addEventListener('keydown', event => {
    let metaKey = ''
    // checks the platform to assign the correct meta key
    process.platform === 'darwin'
      ? (metaKey = event.metaKey)
      : (metaKey = event.ctrlKey)

    // focus on the app console
    if (metaKey === true && event.code === 'KeyL') {
      cmdID.focus()
    }
    // add an edge specific to each phase
    if (metaKey === true && event.code === 'KeyE') {
      // checks for undefined selections
      if (Object.keys(srcNode.out).length !== 0) {
        buttonHelpers.addEdge(cy, srcNode.out, trgNode.out, phase)
        cy.edges().addClass('label-edges')
      }
    }
    // delete nodes or edges with meta + Backspace
    if (metaKey === true && event.code === 'Backspace') {
      deleteRestoreConcepts.deleteConcept(
        cy,
        selectedNode.out,
        selectedEdge.out
      )

      watcher.nodes(graphNodes, cy)
    }
    // restore nodes with meta + z
    if (metaKey === true && event.code === 'KeyZ') {
      deleteRestoreConcepts.restoreNode(cy)

      watcher.nodes(graphNodes, cy)
    }
    // save graph on meta + s
    if (event.shiftKey === true && metaKey === true && event.code === 'KeyS') {
      save(cy)
    }
    // listens for the ENTER key when focus is on the console
    if (document.activeElement === cmdID && event.code === 'Enter') {
      commands()
    }
    // developer mode message when a user wants to reload the app, meta + r
    if (metaKey === true && event.code === 'KeyR') {
      printMsgHTML(
        'Window reload is disabled in default mode.'
      )
      printMsgHTML('Start the app in develper mode it.')
      printMsgHTML('npm run dev')
    }
  })
}
<|endoftext|>


<commit_before>var canvas = document.getElementById("gameCanvas");
var context = document.getContext("2d");

var keys = [];

window.addEventListener("keydown", function(e){
	keys[e.keyCode] = true;
}, false);

window.addEventListener("keyup", function(e){
	delete keys[e.keyCode];
}, false);
<commit_msg>add basic game loop<commit_after>var canvas = document.getElementById("gameCanvas");
var context = canvas.getContext("2d");

var keys = [];

window.addEventListener("keydown", function(e){
	keys[e.keyCode] = true;
}, false);

window.addEventListener("keyup", function(e){
	delete keys[e.keyCode];
}, false);

function game(){
	update();
	render();
}

function update(){
	if(keys[38]) console.log("up")
}

function render(){

}

setInterval(function(){
	game();
}, 1000/30)<|endoftext|>


<commit_before>var button = []; //stores the canvases
for(var i=1; i<10; i++) button[i] = document.getElementById('canvas'+i);

var ctx = []; //stores the context of the canvases
for(var i=1; i<10; i++) ctx[i] = button[i].getContext('2d');

var bDisabled = []; //stores the availability of the button
for(var i=1; i<10; i++) bDisabled[i] = false; //all buttons are enabled in the beginning

var isResult = false;
var content = [];

var xTurn = true; //X:true O:false

function loop(x)
{
    if(!bDisabled[x]){ //button does not currently contain X or O and therefore is enabled.
        bDisabled[x] = true; //button now contains something
        //console.log("Button pressed.");

        button[x].style.webkitTransform = "rotateY(180deg)";

        content[x] = 'x';

        setTimeout(function(){
            ctx[x].lineWidth = 3;
            ctx[x].beginPath();
            ctx[x].moveTo(10, 10);
            ctx[x].lineTo(90, 90);
            ctx[x].moveTo(90, 10);
            ctx[x].lineTo(10, 90);
            ctx[x].stroke();
            ctx[x].closePath();
        }, 300);

    }
}<commit_msg>draw circle when button is clicked and it is circle turn<commit_after>var button = []; //stores the canvases
for(var i=1; i<10; i++) button[i] = document.getElementById('canvas'+i);

var ctx = []; //stores the context of the canvases
for(var i=1; i<10; i++) ctx[i] = button[i].getContext('2d');

var bDisabled = []; //stores the availability of the button
for(var i=1; i<10; i++) bDisabled[i] = false; //all buttons are enabled in the beginning

var isResult = false;
var content = [];

var xTurn = true; //X:true O:false

function loop(x)
{
    if(!bDisabled[x]){ //button does not currently contain X or O and therefore is enabled.
        bDisabled[x] = true; //button now contains something
        //console.log("Button pressed.");

        button[x].style.webkitTransform = "rotateY(180deg)";

        if(xTurn){
            content[x] = 'x';

            setTimeout(function(){
                ctx[x].lineWidth = 3;
                ctx[x].beginPath();
                ctx[x].moveTo(10, 10);
                ctx[x].lineTo(90, 90);
                ctx[x].moveTo(90, 10);
                ctx[x].lineTo(10, 90);
                ctx[x].stroke();
                ctx[x].closePath();
            }, 300);
        }else{
            content[x] = 'o';

            setTimeOut(function(){
                ctx[x].lineWidth = 3;
                ctx[x].beginPath();
                ctx[x].arc(button[x].width/2, button[x].height/2, 0, 2*Math.PI, false);
                ctx[x].stroke;
                ctx[x].closePath();
            })
        }

    }
}<|endoftext|>


<commit_before>var uiModules   = new uiModulesClass();
var markdown = window.markdownit();

$(document).ready(function() {

    var $wish = $('#wish');

    var todoNotificationArea = $('#todos .notification-area');
    var todoNotificationIcon = $('#todos .notification-area > i');
    var todoNotificationText = $('#todos .notification-area > span');

    $('#zone .menu .item').tab({history:false});
    $('.demo.menu .item').tab({history:false});

    $('#todos').ready(function() {
        $.each($('#todos .segment'), function(index, $element){
            var $html, $md;

            $element = $($element);

            $md = $element.find('.md-content-name');
            $html = $element.find('.html-content-name');

            $html.html(markdown.render($md.val()));

            $md = $element.find('.md-content');
            $html = $element.find('.html-content');

            $html.html(markdown.render($md.val()));
        });
    });

    $('#todos').on('click', '.edit.button', function() {
        var $button = $(this);
        var $html = $button.parent().siblings('.html-content');
        var $md = $button.parent().siblings('.md-content');
        var $htmlname = $button.parent().siblings('.html-content-name');
        var $mdname = $button.parent().siblings('.md-content-name');

        if($html.css('display') == 'none') {
            var result = markdown.render($md.val());
            $html.html(result);

            result = markdown.render($mdname.val());
            $htmlname.html(result);

            $button.text('Edit');
        }
        else {
            $button.text('Preview');
        }
        $md.toggle();
        $html.toggle();
        $mdname.toggle();
        $htmlname.toggle();
    });

    $('#todos').on('click', '.save.button', function() {
        var $button = $(this);
        var $mdname = $button.parent().parent().find('input');
        var $md = $button.parent().parent().find('textarea');
        var id = $button.parent().parent().attr('data-tab');

        $.post('/todos/save', {id:id, name: $mdname.val(), content: $md.val()}, function(resp){
            console.log('Saved');
        });
    });

    $('#todos').on('click', '.delete.button', function() {
        var $button = $(this);
        var id = $button.parent().parent().attr('data-tab');

        $.post('/todos/delete', {id:id}, function(resp){
            $('*[data-tab="'+id+'"]').remove();
        });
    });

    $('#new-todo').click(function(e) {
        $button = $(this);
        $.post('/todos/create', function(resp) {
            var $menuItem = $('<a>').addClass('item').attr('data-tab', resp.id)
                                    .html(resp.name);
            var $todoContent = $('<div>').addClass('ui tab basic segment basic')
                                .attr('data-tab', resp.id)
                                .append(
                                    $('<div>').addClass('ui text menu right floated')
                                        .append($('<div>').addClass('ui edit basic button item').text('Edit'))
                                        .append($('<div>').addClass('ui save basic button item').text('Save'))
                                        .append($('<div>').addClass('ui download basic button item').text('Download'))
                                        .append($('<div>').addClass('ui delete basic button item').text('Delete'))
                                )
                                .append(
                                    $('<div>').addClass('ui section divider')
                                )
                                .append(
                                    $('<input>').addClass('ui fluid md-content-name')
                                        .attr('style', 'display:none;').val(resp.name)
                                )
                                .append(
                                    $('<div>').addClass('html-content-name').html(markdown.render(resp.name))
                                )
                                .append(
                                    $('<div>').addClass('ui horizontal divider')
                                )
                                .append(
                                    $('<textarea>').addClass('md-content')
                                        .attr('style', 'display:none;').html(resp.content)
                                )
                                .append(
                                    $('<div>').addClass('html-content')
                                );
            $button.parent().append($menuItem);
            $button.parent().parent().next().prepend($todoContent);
            $button.parent().children().last().tab({history:false});
        })
        .fail(function() {
            uiModules.showError('Something went wrong while creating a Todo');
        });
    })

    $('#reminders').on('click', 'i.delete', function(e){
        var $parentTr = $(this).parents("tr");
        $.post('/reminders/' + $parentTr.attr('id') + '/delete', function(resp) {
            $parentTr.remove();
        })
    });

    $('#wish-form').submit(function(e){
        e.preventDefault();
        var wish = $wish.val();

        $.get('/wish', {wish: wish}, function(resp) {
            var targetType = resp.type;

            if(targetType === 'remind') {
                var value = resp.response;
                var error = resp.error

                if (error) {
                    uiModules.showError(error);
                    return;
                }

                $('#reminders table tbody').append(
                        $('<tr>').attr('id', value.id)
                            .append($('<td>').html(value.m))
                            .append($('<td>').html(value.t))
                            .append($('<td>').html(value.d))
                            .append($('<td>').append($('<i>').addClass('ui delete red icon')))
                );
            }
            else if(targetType === 'comic') {
                var url = resp.response;
                var error = resp.error

                if (error) {
                    uiModules.showError(error);
                    return;
                }

                $('#webcomic-modal iframe').attr('src', url);
                $('#webcomic-modal').modal({
                    onVisible: function () {
                        $("#webcomic-modal").modal("refresh");
                    }
                }).modal('show');

            }
            else {
                uiModules.showError('Invalid type ' + resp.type);
            }
            // $('#reply').addClass('animated slideInDown').html(resp.response.message);
            // setTimeout(function() {
            //     $('#reply').removeClass('animated slideInDown');
            // }, 1000);
        });

        $wish.val(null);
    });

    $.get('/commands', function(resp) {
        $('#commands').html(resp);
    });

    $('#webcomics .button').click(function(e) {
        var $comic = $(this).parent()

        var comic_id = $comic.attr('id');
        var $button = $comic.find('.button');

        $button.addClass('loading');

        $.post('/webcomics/' + comic_id + '/sync', function(response) {
            $comic.find('p').text(response.resp.links_count);
            $comic.find('label').text(response.resp.last_sync);
        }).
        always(function() {
            $button.removeClass('loading');
        });
    })

});
<commit_msg>Removing loading adding disabling<commit_after>var uiModules   = new uiModulesClass();
var markdown = window.markdownit();

$(document).ready(function() {

    var $wish = $('#wish');

    var todoNotificationArea = $('#todos .notification-area');
    var todoNotificationIcon = $('#todos .notification-area > i');
    var todoNotificationText = $('#todos .notification-area > span');

    $('#zone .menu .item').tab({history:false});
    $('.demo.menu .item').tab({history:false});

    $('#todos').ready(function() {
        $.each($('#todos .segment'), function(index, $element){
            var $html, $md;

            $element = $($element);

            $md = $element.find('.md-content-name');
            $html = $element.find('.html-content-name');

            $html.html(markdown.render($md.val()));

            $md = $element.find('.md-content');
            $html = $element.find('.html-content');

            $html.html(markdown.render($md.val()));
        });
    });

    $('#todos').on('click', '.edit.button', function() {
        var $button = $(this);
        var $html = $button.parent().siblings('.html-content');
        var $md = $button.parent().siblings('.md-content');
        var $htmlname = $button.parent().siblings('.html-content-name');
        var $mdname = $button.parent().siblings('.md-content-name');

        if($html.css('display') == 'none') {
            var result = markdown.render($md.val());
            $html.html(result);

            result = markdown.render($mdname.val());
            $htmlname.html(result);

            $button.text('Edit');
        }
        else {
            $button.text('Preview');
        }
        $md.toggle();
        $html.toggle();
        $mdname.toggle();
        $htmlname.toggle();
    });

    $('#todos').on('click', '.save.button', function() {
        var $button = $(this);
        var $mdname = $button.parent().parent().find('input');
        var $md = $button.parent().parent().find('textarea');
        var id = $button.parent().parent().attr('data-tab');

        $.post('/todos/save', {id:id, name: $mdname.val(), content: $md.val()}, function(resp){
            console.log('Saved');
        });
    });

    $('#todos').on('click', '.delete.button', function() {
        var $button = $(this);
        var id = $button.parent().parent().attr('data-tab');

        $.post('/todos/delete', {id:id}, function(resp){
            $('*[data-tab="'+id+'"]').remove();
        });
    });

    $('#new-todo').click(function(e) {
        $button = $(this);
        $.post('/todos/create', function(resp) {
            var $menuItem = $('<a>').addClass('item').attr('data-tab', resp.id)
                                    .html(resp.name);
            var $todoContent = $('<div>').addClass('ui tab basic segment basic')
                                .attr('data-tab', resp.id)
                                .append(
                                    $('<div>').addClass('ui text menu right floated')
                                        .append($('<div>').addClass('ui edit basic button item').text('Edit'))
                                        .append($('<div>').addClass('ui save basic button item').text('Save'))
                                        .append($('<div>').addClass('ui download basic button item').text('Download'))
                                        .append($('<div>').addClass('ui delete basic button item').text('Delete'))
                                )
                                .append(
                                    $('<div>').addClass('ui section divider')
                                )
                                .append(
                                    $('<input>').addClass('ui fluid md-content-name')
                                        .attr('style', 'display:none;').val(resp.name)
                                )
                                .append(
                                    $('<div>').addClass('html-content-name').html(markdown.render(resp.name))
                                )
                                .append(
                                    $('<div>').addClass('ui horizontal divider')
                                )
                                .append(
                                    $('<textarea>').addClass('md-content')
                                        .attr('style', 'display:none;').html(resp.content)
                                )
                                .append(
                                    $('<div>').addClass('html-content')
                                );
            $button.parent().append($menuItem);
            $button.parent().parent().next().prepend($todoContent);
            $button.parent().children().last().tab({history:false});
        })
        .fail(function() {
            uiModules.showError('Something went wrong while creating a Todo');
        });
    })

    $('#reminders').on('click', 'i.delete', function(e){
        var $parentTr = $(this).parents("tr");
        $.post('/reminders/' + $parentTr.attr('id') + '/delete', function(resp) {
            $parentTr.remove();
        })
    });

    $('#wish-form').submit(function(e){
        e.preventDefault();
        var wish = $wish.val();

        $.get('/wish', {wish: wish}, function(resp) {
            var targetType = resp.type;

            if(targetType === 'remind') {
                var value = resp.response;
                var error = resp.error

                if (error) {
                    uiModules.showError(error);
                    return;
                }

                $('#reminders table tbody').append(
                        $('<tr>').attr('id', value.id)
                            .append($('<td>').html(value.m))
                            .append($('<td>').html(value.t))
                            .append($('<td>').html(value.d))
                            .append($('<td>').append($('<i>').addClass('ui delete red icon')))
                );
            }
            else if(targetType === 'comic') {
                var url = resp.response;
                var error = resp.error

                if (error) {
                    uiModules.showError(error);
                    return;
                }

                $('#webcomic-modal iframe').attr('src', url);
                $('#webcomic-modal').modal({
                    onVisible: function () {
                        $("#webcomic-modal").modal("refresh");
                    }
                }).modal('show');

            }
            else {
                uiModules.showError('Invalid type ' + resp.type);
            }
            // $('#reply').addClass('animated slideInDown').html(resp.response.message);
            // setTimeout(function() {
            //     $('#reply').removeClass('animated slideInDown');
            // }, 1000);
        });

        $wish.val(null);
    });

    $.get('/commands', function(resp) {
        $('#commands').html(resp);
    });

    $('#webcomics .button').click(function(e) {
        var $comic = $(this).parent()

        var comic_id = $comic.attr('id');
        var $button = $comic.find('.button');

        $button.addClass('disabled');

        $.post('/webcomics/' + comic_id + '/sync', function(response) {
            $comic.find('p').text(response.resp.links_count);
            $comic.find('label').text(response.resp.last_sync);
        }).
        always(function() {
            $button.removeClass('disabled');
        });
    })

});
<|endoftext|>


<commit_before>
module.exports = function (elements_collection) {
	'use strict';

	var PrimeGenerator = require('ksxnodemodules').prime.PrimeGenerator;

	var addingquantityinput = elements_collection.addingquantityinput;
	var errormessagespan = elements_collection.errormessagespan;
	var outputspan = elements_collection.outputspan;

	addingquantityinput.addEventListener('keydown', (event) => event.keyCode === 13 && main(), false);
	elements_collection.addingbutton.addEventListener('click', main, false);
	elements_collection.resetbutton.addEventListener('click', reset, false);
	elements_collection.getbutton.addEventListener('click', createEditorPane, false);
	elements_collection.htmlElement.addEventListener('keydown', (event) => {
		switch (event.keyCode) {
			case 27:
				reset();
				break;
			case 83:
			case 115:
				if (event.ctrlKey && !event.shiftKey && !event.altKey) {
					createEditorPane();
				}
				break;
		}
	}, false);

	var primegen, length;

	reset();

	function main() {

		var n = parseInt(addingquantityinput.value);

		if (!isFinite(n) || n < 0) {
			msgErr("Invalid input.");
			return;
		}

		msgErr('');

		generateprimes(n);

	}

	function generateprimes(n) {
		for (let prime of primegen) {
			if (!n) break;
			print(', ' + String(prime));
			--n;
		}
	}

	function print(content) {
		outputspan.textContent += content;
		++length;
	}

	function msgErr(error) {
		errormessagespan.textContent = error;
	}

	function reset() {
		primegen = new PrimeGenerator();
		length = 0;
		outputspan.textContent = '2';
		addingquantityinput.value = '';
		msgErr('');
	}

	function createEditorPane() {
		atom.workspace.open("first-" + String(length) + "-primes.txt").then((editor) => editor.setText(outputspan.textContent));
	}

}
<commit_msg>fix a little bug<commit_after>
module.exports = function (elements_collection) {
	'use strict';

	var PrimeGenerator = require('ksxnodemodules').prime.PrimeGenerator;

	var addingquantityinput = elements_collection.addingquantityinput;
	var errormessagespan = elements_collection.errormessagespan;
	var outputspan = elements_collection.outputspan;

	addingquantityinput.addEventListener('keydown', (event) => event.keyCode === 13 && main(), false);
	elements_collection.addingbutton.addEventListener('click', main, false);
	elements_collection.resetbutton.addEventListener('click', reset, false);
	elements_collection.getbutton.addEventListener('click', createEditorPane, false);
	elements_collection.htmlElement.addEventListener('keydown', (event) => {
		switch (event.keyCode) {
			case 27:
				reset();
				break;
			case 83:
			case 115:
				if (event.ctrlKey && !event.shiftKey && !event.altKey) {
					createEditorPane();
				}
				break;
		}
	}, false);

	var primegen, length;

	reset();

	function main() {

		var n = parseInt(addingquantityinput.value);

		if (!isFinite(n) || n < 0) {
			msgErr("Invalid input.");
			return;
		}

		msgErr('');

		generateprimes(n);

	}

	function generateprimes(n) {
		for (let prime of primegen) {
			if (!n) break;
			print(', ' + String(prime));
			--n;
		}
	}

	function print(content) {
		outputspan.textContent += content;
		++length;
	}

	function msgErr(error) {
		errormessagespan.textContent = error;
	}

	function reset() {
		primegen = new PrimeGenerator();
		length = 1;
		outputspan.textContent = '2';
		addingquantityinput.value = '';
		msgErr('');
	}

	function createEditorPane() {
		atom.workspace.open("first-" + String(length) + "-primes.txt").then((editor) => editor.setText(outputspan.textContent));
	}

}
<|endoftext|>


<commit_before>/**
	maintain game logic and supervise game objects

	@namespace GAS
	@class game
**/

GAS.game = {

	/**
		initialize game objects

		@method init
	**/

	init: function() {

		this.weed.init();
		this.food.init();
		this.npc.init();

	},

	/**
		updates not handled by individual objects
		called on every frame

		@method update
	**/

	update: function() {
	},

	/**
		lazy updates not handled by individual objects
		called on every display list cleanup (1-2 seconds)

		@method nudge
	**/

	nudge: function() {
	},

	/**

		weed collection

	**/

	weed: {

		COUNT: 5000,

		list: [],

		/**
			initialize the weed collection

			@method init
		**/

		init: function() {
			var r = GAS.map.RADIUS;
			var i, il, o;

			for (i = 0, il = this.COUNT; i < il; i++) {
				o = GAS.weeds.create(
					GAS.random(-r, r), GAS.random(-r, r), GAS.random(-r, r)	);
				this.list.push(o);
				GAS.map.add(o);
			}
		}

	},

	/**

		food lookups, combination logic, food cloud collection

	**/

	food: {

		INGREDIENT: [],

		list: [],

		/**
			initialize the bolus collection

			@method init
		**/

		init: function() {
			var weed = GAS.game.weed;
			var i, il, c, o;

			// TEMP testing entries
			for (i = 0; i < 16; i++) {
				var s = "";
				for (var j = 0; j < 5; j++) {
					s += "abcdefghijklmnopqrstuvwxyz".charAt(Math.floor(GAS.random(0, 26)));
				}
				this.INGREDIENT[i] = s;
			}

			for (i = 0, il = weed.list.length; i < il; i++) {
				if (Math.random() < 0.25) {
					c = weed.list[i].position;
					o = GAS.bolus.create(c.x, c.y, c.z);
					o.stores = {};
					this.INGREDIENT.enumerate(function(e) {
						o.stores[e] = Math.round(Math.random());
					});
					o.update = this.update;
					this.list.push(o);
					GAS.map.add(o);
				}
			}

		},

		/**
			update a food bolus

			called on EVERY frame for EVERY active bolus
			note that "this" refers to bolus object, not
			the GAS.game.food object

			@method update
		**/

		update: function() {
			// if player slips inside a food bolus, hide it
			// and add to player inventory (if possible)
			if (!this.hidden) {
				var that = this;
				if (this.playerDistance < GAS.bolus.DRAW_RADIUS) {
					GAS.game.food.INGREDIENT.enumerate(function(e) {
						GAS.player.stores[e] = (GAS.player.stores[e] || 0) + (that.stores[e] || 0);
					});
					this.hidden = true;
				}
			}
		}

	},

	/**

		paddler NPC handling and behaviors

	**/

	npc: {

		WATCH_RADIUS: 10,
		EVADE_RADIUS: 3,

		DRIFTING: 0,
		WATCHING: 1,
		EVADING: 2,

		scratch: {
			p: SOAR.vector.create(),
			q: SOAR.quaternion.create(),
			r: SOAR.vector.create()
		},

		prompting: false,

		/**
			initialize the NPC

			@method init
		**/

		init: function() {
			var r = GAS.map.RADIUS;

			this.actor = GAS.paddler.create(
//				GAS.random(-r, r), GAS.random(-r, r), GAS.random(-r, r)	);
			0, 0, -5);
			this.actor.interact = GAS.hud.showCookingDialog;

			// paddler object already has an update method, so swap it out
			var update = this.actor.update;
			this.actor.update = this.update;
			this.actor.updateMotion = update;

			this.actor.behavior = {
				status: this.DRIFTING,
				period: 0,
				target: SOAR.vector.create()
			};
			this.actor.haste = 2;
			GAS.map.add(this.actor);

			this.soundCard = GAS.card.create("sound");
			GAS.map.always.push(this.soundCard);
			this.soundCard.scale = 10;
			this.soundCard.hidden = true;

		},

		/**
			update an NPC's behavior

			called for every NPC on every frame
			"this" refers to the NPC object

			@method update
		**/

		update: function() {
			var p = this.scratch.p;
			var player = GAS.player.avatar;
			var behave = this.behavior;
			var npc = GAS.game.npc;

			switch (behave.status) {

			case npc.DRIFTING:

				// if npc is about to exit the reef, pull em back
				if (this.position.length() > GAS.map.RADIUS) {
					p.copy(this.position).neg().norm().mul(0.01);
					behave.target.add(p).norm();
				}
				// if it's been too long since e changed direction, pick a new target
				if (behave.period <= 0) {
					behave.period = GAS.random(2, 5);
					behave.target.set( GAS.random(-1, 1), GAS.random(-0.5, 0.5), GAS.random(-1, 1) ).norm();
				}

				// keep em pointed at the target and counting down the seconds to the next target
				this.pointTo(behave.target, 0.05);
				behave.period -= SOAR.interval * 0.001;

				// if the player is nearby
				if (this.playerDistance < npc.WATCH_RADIUS) {
					behave.status = npc.WATCHING;
					this.haste = 0;
					npc.soundCard.hidden = true;
				}

				break;

			case npc.WATCHING:

				// point the NPC at the player
				p.copy(player.position).sub(this.position).norm();
				this.pointTo(p, 0.1);

				// if the player is looking at the NPC, prompt them
				if (this.playerDotProduct >= 0.8 && !npc.prompting) {
					GAS.hud.prompt(this, "Cook For");
					npc.prompting = true;
				}
				// if the player is looking away, remove the prompt
				if (this.playerDotProduct < 0.8 && npc.prompting) {
					GAS.hud.prompt();
					npc.prompting = false;
				}

				// player moves too far away, back to drifting
				if (this.playerDistance > npc.WATCH_RADIUS) {
					behave.status = npc.DRIFTING;
					this.haste = 2;
					npc.soundCard.hidden = false;
				}
				// player moves too close, switch to evade
				if (this.playerDistance < npc.EVADE_RADIUS) {
					behave.status = npc.EVADING;
					this.haste = 2;
				}

				break;

			case npc.EVADING:

				// point npc away from player
				behave.target.copy(this.position).sub(player.position).norm();
				//behave.target.cross(player.rotator.up);
				this.pointTo(behave.target, 0.25);

				if (this.playerDistance > npc.EVADE_RADIUS) {
					behave.status = npc.WATCHING;
					this.haste = 0;
				}

				break;

			}

			this.updateMotion();

			npc.soundCard.position.copy(this.position).sub(player.position).norm().mul(100).add(player.position);
		}

	}

};<commit_msg>Implements a "calm" behavioral mode for the paddler NPC.<commit_after>/**
	maintain game logic and supervise game objects

	@namespace GAS
	@class game
**/

GAS.game = {

	/**
		initialize game objects

		@method init
	**/

	init: function() {

		this.weed.init();
		this.food.init();
		this.npc.init();

	},

	/**
		updates not handled by individual objects
		called on every frame

		@method update
	**/

	update: function() {
	},

	/**
		lazy updates not handled by individual objects
		called on every display list cleanup (1-2 seconds)

		@method nudge
	**/

	nudge: function() {
	},

	/**

		weed collection

	**/

	weed: {

		COUNT: 5000,

		list: [],

		/**
			initialize the weed collection

			@method init
		**/

		init: function() {
			var r = GAS.map.RADIUS;
			var i, il, o;

			for (i = 0, il = this.COUNT; i < il; i++) {
				o = GAS.weeds.create(
					GAS.random(-r, r), GAS.random(-r, r), GAS.random(-r, r)	);
				this.list.push(o);
				GAS.map.add(o);
			}
		}

	},

	/**

		food lookups, combination logic, food cloud collection

	**/

	food: {

		INGREDIENT: [],

		list: [],

		/**
			initialize the bolus collection

			@method init
		**/

		init: function() {
			var weed = GAS.game.weed;
			var i, il, c, o;

			// TEMP testing entries
			for (i = 0; i < 16; i++) {
				var s = "";
				for (var j = 0; j < 5; j++) {
					s += "abcdefghijklmnopqrstuvwxyz".charAt(Math.floor(GAS.random(0, 26)));
				}
				this.INGREDIENT[i] = s;
			}

			for (i = 0, il = weed.list.length; i < il; i++) {
				if (Math.random() < 0.25) {
					c = weed.list[i].position;
					o = GAS.bolus.create(c.x, c.y, c.z);
					o.stores = {};
					this.INGREDIENT.enumerate(function(e) {
						o.stores[e] = Math.round(Math.random());
					});
					o.update = this.update;
					this.list.push(o);
					GAS.map.add(o);
				}
			}

		},

		/**
			update a food bolus

			called on EVERY frame for EVERY active bolus
			note that "this" refers to bolus object, not
			the GAS.game.food object

			@method update
		**/

		update: function() {
			// if player slips inside a food bolus, hide it
			// and add to player inventory (if possible)
			if (!this.hidden) {
				var that = this;
				if (this.playerDistance < GAS.bolus.DRAW_RADIUS) {
					GAS.game.food.INGREDIENT.enumerate(function(e) {
						GAS.player.stores[e] = (GAS.player.stores[e] || 0) + (that.stores[e] || 0);
					});
					this.hidden = true;
				}
			}
		}

	},

	/**

		paddler NPC handling and behaviors

	**/

	npc: {

		WATCH_RADIUS: 10,
		EVADE_RADIUS: 3,

		DRIFTING: 0,
		WATCHING: 1,
		EVADING: 2,

		scratch: {
			p: SOAR.vector.create(),
			q: SOAR.quaternion.create(),
			r: SOAR.vector.create()
		},

		prompting: false,

		/**
			initialize the NPC

			@method init
		**/

		init: function() {
			var r = GAS.map.RADIUS;

			this.actor = GAS.paddler.create(
//				GAS.random(-r, r), GAS.random(-r, r), GAS.random(-r, r)	);
			0, 0, -5);

			// paddler object already has an update method, so swap it out
			var update = this.actor.update;
			this.actor.update = this.update;
			this.actor.updateMotion = update;

			// set up remaining NPC-specific stuff
			this.actor.behavior = {
				status: this.DRIFTING,
				period: 0,
				target: SOAR.vector.create(),
				calmed: false
			};
			this.actor.haste = 2;
			this.actor.interact = GAS.hud.showCookingDialog;
/*			var that = this;
			this.actor.interact = function() {
				that.actor.behavior.calmed = true;
				that.prompting = false;
			};
*/
			GAS.map.add(this.actor);

			this.soundCard = GAS.card.create("sound");
			GAS.map.always.push(this.soundCard);
			this.soundCard.scale = 10;
			this.soundCard.hidden = true;

		},

		/**
			update an NPC's behavior

			called for every NPC on every frame
			"this" refers to the NPC object

			@method update
		**/

		update: function() {
			var p = this.scratch.p;
			var player = GAS.player.avatar;
			var behave = this.behavior;
			var npc = GAS.game.npc;

			switch (behave.status) {

			case npc.DRIFTING:

				// if npc is about to exit the reef, pull em back
				if (this.position.length() > GAS.map.RADIUS) {
					p.copy(this.position).neg().norm().mul(0.01);
					behave.target.add(p).norm();
				}
				// if it's been too long since e changed direction, pick a new target
				if (behave.period <= 0) {
					behave.period = GAS.random(2, 5);
					behave.target.set( GAS.random(-1, 1), GAS.random(-0.5, 0.5), GAS.random(-1, 1) ).norm();
				}

				// keep em pointed at the target and counting down the seconds to the next target
				this.pointTo(behave.target, 0.05);
				behave.period -= SOAR.interval * 0.001;

				// if the player is nearby
				if (this.playerDistance < npc.WATCH_RADIUS) {
					behave.status = npc.WATCHING;
					this.haste = 0;
					npc.soundCard.hidden = true;
				}

				break;

			case npc.WATCHING:

				// point the NPC at the player
				p.copy(player.position).sub(this.position).norm();
				this.pointTo(p, 0.1);

				// if the player is looking at the NPC, prompt them
				if (this.playerDotProduct >= 0.8 && !npc.prompting) {
					GAS.hud.prompt(this, behave.calmed ? "Question" : "Cook For");
					npc.prompting = true;
				}
				// if the player is looking away, remove the prompt
				if (this.playerDotProduct < 0.8 && npc.prompting) {
					GAS.hud.prompt();
					npc.prompting = false;
				}

				// player moves too far away, back to drifting
				if (this.playerDistance > npc.WATCH_RADIUS) {
					behave.status = npc.DRIFTING;
					this.haste = behave.calmed ? 1 : 2;
					npc.soundCard.hidden = false;
				}
				// player moves too close, switch to evade
				if (this.playerDistance < npc.EVADE_RADIUS) {
					behave.status = npc.EVADING;
					this.haste = 2;
				}

				break;

			case npc.EVADING:

				// point npc away from player
				behave.target.copy(this.position).sub(player.position).norm();
				this.pointTo(behave.target, 0.25);

				if (this.playerDistance > npc.EVADE_RADIUS) {
					behave.status = npc.WATCHING;
					this.haste = 0;
				}

				break;

			}

			this.updateMotion();

			npc.soundCard.position.copy(this.position).sub(player.position).norm().mul(100).add(player.position);
		}

	}

};<|endoftext|>


<commit_before>$(document).ready(function () {

  var center = new google.maps.LatLng(35.681298, 139.766247);

  var mapOptions = {
    zoom: 12,
    center: center
  };

  var map = new google.maps.Map(document.getElementById('map'), mapOptions);

  var marker = new google.maps.Marker({
    position: map.getCenter(),
    draggable: true,
    map: map
  });

  var geocoder = new google.maps.Geocoder();

  var circle = new google.maps.Circle({
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35,
    map: map,
    center: center,
    radius: 3000
  });

  $("#search").click(function(){

    var address = $("#address").val();

    geocoder.geocode({ 'address': address }, function (results, status) {
      if (status === google.maps.GeocoderStatus.OK) {

        var loc = results[0].geometry.location;
        map.setCenter(loc);
        marker.setPosition(loc);
        circle.setCenter(loc);

        $("#latitude").val(loc.lat());
        $("#longitude").val(loc.lng());
      }
    });
  });

});
<commit_msg>Set circle to follow the marker<commit_after>$(document).ready(function () {

  var center = new google.maps.LatLng(35.681298, 139.766247);

  var mapOptions = {
    zoom: 12,
    center: center
  };

  var map = new google.maps.Map(document.getElementById('map'), mapOptions);

  var marker = new google.maps.Marker({
    position: map.getCenter(),
    draggable: true,
    map: map
  });
  marker.addListener("drag", function() {
    circle.setCenter(marker.getPosition());
  });

  var geocoder = new google.maps.Geocoder();

  var circle = new google.maps.Circle({
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35,
    map: map,
    center: center,
    radius: 3000
  });

  $("#search").click(function(){

    var address = $("#address").val();

    geocoder.geocode({ 'address': address }, function (results, status) {
      if (status === google.maps.GeocoderStatus.OK) {

        var loc = results[0].geometry.location;
        map.setCenter(loc);
        marker.setPosition(loc);
        circle.setCenter(loc);

        $("#latitude").val(loc.lat());
        $("#longitude").val(loc.lng());
      }
    });
  });

});
<|endoftext|>


<commit_before>$(function() {
    window.onload = function() {
    console.log("%c  ~~~  Bob v0.2 - Developed by d4rkd0s  ~~~  ", "color: #FFFFFF; font-size: 12px; background: #3F1338;");
    var game = new Phaser.Game(1156, 650, Phaser.AUTO, '', { preload: preload, create: create, update: update });
    function preload() {
        //setting up starting vars
        score = 0;
        console.log("%c   score: 0   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");
        lives = 3;
        console.log("%c   lives: 3   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");

        //game.load.image('bob', 'assets/images/bob.png');
        game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80);
        console.log("%c   loaded: spritesheet   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('apple', 'assets/images/apple_red.png');
        game.load.image('background', 'assets/images/background.png');
        console.log("%c   loaded: background   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.image('healthbar', 'assets/images/healthbar.png');
        //console.log("%c   loaded: healthbar   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('ocean', 'assets/images/ocean.png');
        console.log("%c   loaded: horse   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('horse', 'assets/images/horse.png');
        console.log("%c   set border: ocean   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        cursors = game.input.keyboard.createCursorKeys();
        console.log("%c   user input: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.audio('jumpsound', 'assets/sounds/jump.wav');

        //walking case switch
        function coroutine(f) {
           var o = f(); // instantiate the coroutine
           o.next(); // execute until the first yield
           return function(x) {
                o.next(x);
            }
        }
        var clock = coroutine(function*(_) {
            while (true) {
                yield _;
                foot = 0;
                yield _;
                foot = 1;
            }
        });

        //walk step speed in ms
        setInterval(clock, 100);
        //notify user (console)
        console.log("%c   walking: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
    }//preload

    function create() {

        //  A simple background for our game
        game.add.sprite(0, 0, 'background');
        console.log("%c   spawned: background   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //Game Objects
        player = game.add.sprite(775, game.world.height - 150, 'bob');
        console.log("%c   spawned: player   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        apple = game.add.sprite(game.world.width / 2, game.world.height / 2, 'apple');

        //var healthbar = game.add.sprite(0,0,'healthbar');
        //healthbar.cropEnabled = true;
        //healthbar.crop.width = (character.health / character.maxHealth) * healthbar.width

        //text = "Score: " . score;
        //style = { font: "32px Arial", fill: "#3D4185", align: "center" };
        //game.add.text(game.world.centerX-300, 0, text, style);
        //sound
        //jumpsound = game.add.audio('jumpsound');
        //jumpsound.allowMultiple = false;

        ocean = game.add.sprite(0, game.world.height - 484, 'ocean');
        console.log("%c   spawned: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");

        //add horse
        horse = game.add.sprite(450, game.world.height - 300, 'horse');

        //ocean
        game.physics.enable(ocean, Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        ocean.body.immovable = true;
        console.log("%c   locked: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #A40E38;");

        //start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(player);
        game.physics.arcade.enableBody(player);
        console.log("%c   physics: bounds(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(horse);
        game.physics.arcade.enableBody(horse);
        game.physics.arcade.enable(apple);
        game.physics.arcade.enableBody(apple);
        player.body.collideWorldBounds = true;
        horse.body.collideWorldBounds = true;
        apple.body.collideWorldBounds = true;
        console.log("%c   collideWorldBounds: enabled   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
    }//create()

    function update() {

        //ocean collision
        game.physics.arcade.collide(player, ocean);
        game.physics.arcade.collide(player, horse);
        game.physics.arcade.collide(ocean, apple);
        game.physics.arcade.collide(horse, ocean);
        //horse.body.accelerateToObject(horse, player, 600, 250, 250);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;

        horse.velocity = game.physics.arcade.accelerateToObject(horse, apple, 50, 50, 50);

        if ( apple.alive == true){
            if ( game.physics.arcade.overlap(apple, player) == true ){
                score = score + 1;
                apple.kill();
                console.log(score);
            }
            if ( game.physics.arcade.collide(apple, horse) == true ){
                score = score - 1;
                apple.kill();
                console.log(score);
            }
        }
        else{
            randX = Math.floor(Math.random()*(800-50+1)+50);
            randY = Math.floor(Math.random()*(550-170+1)+170);
            apple = game.add.sprite(randX, randY, 'apple');
            game.physics.arcade.enable(apple);
            game.physics.arcade.enableBody(apple);
            apple.body.collideWorldBounds = true;
            game.physics.arcade.collide(player, apple);
            game.physics.arcade.collide(ocean, apple);
        }

        if (cursors.left.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the left+up
                player.body.velocity.x = -100;
                player.body.velocity.y = -100;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the left+down
                player.body.velocity.x = -100;
                player.body.velocity.y = 100;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else
            {
                //  Move to the left
                player.body.velocity.x = -180;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }

        }

        else if (cursors.right.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the right+up
                player.body.velocity.x = 100;
                player.body.velocity.y = -100;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the right+down
                player.body.velocity.x = 100;
                player.body.velocity.y = 100;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else
            {
                //  Move to the right
                player.body.velocity.x = 180;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }

        }
        else if (cursors.up.isDown)
        {
            //  Move to the up
            player.body.velocity.y = -180;
            if ( foot == 0 ){
               player.frame = 2;
            }
            if ( foot == 1 ){
               player.frame = 3;
            }
        }
        else if (cursors.down.isDown)
        {
            //  Move to the down
            player.body.velocity.y = 180;
            if ( foot == 0 ){
               player.frame = 0;
            }
            if ( foot == 1 ){
               player.frame = 1;
            }

        }

        } //update

};
});<commit_msg>Speed Var<commit_after>$(function() {
    window.onload = function() {
    console.log("%c  ~~~  Bob v0.2 - Developed by d4rkd0s  ~~~  ", "color: #FFFFFF; font-size: 12px; background: #3F1338;");
    var game = new Phaser.Game(1156, 650, Phaser.AUTO, '', { preload: preload, create: create, update: update });
    function preload() {
        //setting up starting vars
        score = 0;
        console.log("%c   score: 0   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");
        lives = 3;
        console.log("%c   lives: 3   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");

        speed = 200;
        //game.load.image('bob', 'assets/images/bob.png');
        game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80);
        console.log("%c   loaded: spritesheet   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('apple', 'assets/images/apple_red.png');
        game.load.image('background', 'assets/images/background.png');
        console.log("%c   loaded: background   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.image('healthbar', 'assets/images/healthbar.png');
        //console.log("%c   loaded: healthbar   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('ocean', 'assets/images/ocean.png');
        console.log("%c   loaded: horse   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('horse', 'assets/images/horse.png');
        console.log("%c   set border: ocean   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        cursors = game.input.keyboard.createCursorKeys();
        console.log("%c   user input: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.audio('jumpsound', 'assets/sounds/jump.wav');

        //walking case switch
        function coroutine(f) {
           var o = f(); // instantiate the coroutine
           o.next(); // execute until the first yield
           return function(x) {
                o.next(x);
            }
        }
        var clock = coroutine(function*(_) {
            while (true) {
                yield _;
                foot = 0;
                yield _;
                foot = 1;
            }
        });

        //walk step speed in ms
        setInterval(clock, 100);
        //notify user (console)
        console.log("%c   walking: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
    }//preload

    function create() {

        //  A simple background for our game
        game.add.sprite(0, 0, 'background');
        console.log("%c   spawned: background   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //Game Objects
        player = game.add.sprite(775, game.world.height - 150, 'bob');
        console.log("%c   spawned: player   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        apple = game.add.sprite(game.world.width / 2, game.world.height / 2, 'apple');

        //var healthbar = game.add.sprite(0,0,'healthbar');
        //healthbar.cropEnabled = true;
        //healthbar.crop.width = (character.health / character.maxHealth) * healthbar.width

        //text = "Score: " . score;
        //style = { font: "32px Arial", fill: "#3D4185", align: "center" };
        //game.add.text(game.world.centerX-300, 0, text, style);
        //sound
        //jumpsound = game.add.audio('jumpsound');
        //jumpsound.allowMultiple = false;

        ocean = game.add.sprite(0, game.world.height - 484, 'ocean');
        console.log("%c   spawned: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");

        //add horse
        horse = game.add.sprite(450, game.world.height - 300, 'horse');

        //ocean
        game.physics.enable(ocean, Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        ocean.body.immovable = true;
        console.log("%c   locked: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #A40E38;");

        //start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(player);
        game.physics.arcade.enableBody(player);
        console.log("%c   physics: bounds(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(horse);
        game.physics.arcade.enableBody(horse);
        game.physics.arcade.enable(apple);
        game.physics.arcade.enableBody(apple);
        player.body.collideWorldBounds = true;
        horse.body.collideWorldBounds = true;
        apple.body.collideWorldBounds = true;
        console.log("%c   collideWorldBounds: enabled   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
    }//create()

    function update() {

        //ocean collision
        game.physics.arcade.collide(player, ocean);
        game.physics.arcade.collide(player, horse);
        game.physics.arcade.collide(ocean, apple);
        game.physics.arcade.collide(horse, ocean);
        //horse.body.accelerateToObject(horse, player, 600, 250, 250);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;

        horse.velocity = game.physics.arcade.accelerateToObject(horse, apple, 50, 50, 50);

        if ( apple.alive == true){
            if ( game.physics.arcade.overlap(apple, player) == true ){
                score = score + 1;
                apple.kill();
                console.log(score);
            }
            if ( game.physics.arcade.collide(apple, horse) == true ){
                score = score - 1;
                apple.kill();
                console.log(score);
            }
        }
        else{
            randX = Math.floor(Math.random()*(800-50+1)+50);
            randY = Math.floor(Math.random()*(550-170+1)+170);
            apple = game.add.sprite(randX, randY, 'apple');
            game.physics.arcade.enable(apple);
            game.physics.arcade.enableBody(apple);
            apple.body.collideWorldBounds = true;
            game.physics.arcade.collide(player, apple);
            game.physics.arcade.collide(ocean, apple);
        }

        if (cursors.left.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the left+up
                player.body.velocity.x = -speed;
                player.body.velocity.y = -speed;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the left+down
                player.body.velocity.x = -speed;
                player.body.velocity.y = speed;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else
            {
                //  Move to the left
                player.body.velocity.x = -speed*1.8;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }

        }

        else if (cursors.right.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the right+up
                player.body.velocity.x = speed;
                player.body.velocity.y = -speed;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the right+down
                player.body.velocity.x = speed;
                player.body.velocity.y = speed;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else
            {
                //  Move to the right
                player.body.velocity.x = speed*1.8;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }

        }
        else if (cursors.up.isDown)
        {
            //  Move to the up
            player.body.velocity.y = -speed;
            if ( foot == 0 ){
               player.frame = 2;
            }
            if ( foot == 1 ){
               player.frame = 3;
            }
        }
        else if (cursors.down.isDown)
        {
            //  Move to the down
            player.body.velocity.y = speed;
            if ( foot == 0 ){
               player.frame = 0;
            }
            if ( foot == 1 ){
               player.frame = 1;
            }

        }

        } //update

};
});<|endoftext|>