<commit_before>/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017, 2018, 2019 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React from 'react';
import PropTypes from 'prop-types';
import { _t } from '../../../languageHandler';
import sdk from '../../../index';
import Modal from "../../../Modal";
import SdkConfig from "../../../SdkConfig";

import PasswordReset from "../../../PasswordReset";

// Phases
// Show controls to configure server details
const PHASE_SERVER_DETAILS = 0;
// Show the forgot password inputs
const PHASE_FORGOT = 1;
// Email is in the process of being sent
const PHASE_SENDING_EMAIL = 2;
// Email has been sent
const PHASE_EMAIL_SENT = 3;
// User has clicked the link in email and completed reset
const PHASE_DONE = 4;

module.exports = React.createClass({
    displayName: 'ForgotPassword',

    propTypes: {
        // The default server name to use when the user hasn't specified
        // one. If set, `defaultHsUrl` and `defaultHsUrl` were derived for this
        // via `.well-known` discovery. The server name is used instead of the
        // HS URL when talking about "your account".
        defaultServerName: PropTypes.string,
        // An error passed along from higher up explaining that something
        // went wrong when finding the defaultHsUrl.
        defaultServerDiscoveryError: PropTypes.string,

        defaultHsUrl: PropTypes.string,
        defaultIsUrl: PropTypes.string,
        customHsUrl: PropTypes.string,
        customIsUrl: PropTypes.string,

        onLoginClick: PropTypes.func,
        onComplete: PropTypes.func.isRequired,
    },

    getInitialState: function() {
        return {
            enteredHsUrl: this.props.customHsUrl || this.props.defaultHsUrl,
            enteredIsUrl: this.props.customIsUrl || this.props.defaultIsUrl,
            phase: PHASE_FORGOT,
            email: "",
            password: "",
            password2: "",
            errorText: null,
        };
    },

    submitPasswordReset: function(hsUrl, identityUrl, email, password) {
        this.setState({
            phase: PHASE_SENDING_EMAIL,
        });
        this.reset = new PasswordReset(hsUrl, identityUrl);
        this.reset.resetPassword(email, password).done(() => {
            this.setState({
                phase: PHASE_EMAIL_SENT,
            });
        }, (err) => {
            this.showErrorDialog(_t('Failed to send email') + ": " + err.message);
            this.setState({
                phase: PHASE_FORGOT,
            });
        });
    },

    onVerify: function(ev) {
        ev.preventDefault();
        if (!this.reset) {
            console.error("onVerify called before submitPasswordReset!");
            return;
        }
        this.reset.checkEmailLinkClicked().done((res) => {
            this.setState({ phase: PHASE_DONE });
        }, (err) => {
            this.showErrorDialog(err.message);
        });
    },

    onSubmitForm: function(ev) {
        ev.preventDefault();

        // Don't allow the user to register if there's a discovery error
        // Without this, the user could end up registering on the wrong homeserver.
        if (this.props.defaultServerDiscoveryError) {
            this.setState({errorText: this.props.defaultServerDiscoveryError});
            return;
        }

        if (!this.state.email) {
            this.showErrorDialog(_t('The email address linked to your account must be entered.'));
        } else if (!this.state.password || !this.state.password2) {
            this.showErrorDialog(_t('A new password must be entered.'));
        } else if (this.state.password !== this.state.password2) {
            this.showErrorDialog(_t('New passwords must match each other.'));
        } else {
            const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog");
            Modal.createTrackedDialog('Forgot Password Warning', '', QuestionDialog, {
                title: _t('Warning!'),
                description:

                        { _t(
                            "Changing your password will reset any end-to-end encryption keys " +
                            "on all of your devices, making encrypted chat history unreadable. Set up " +
                            "Key Backup or export your room keys from another device before resetting your " +
                            "password.",
                        ) }

,
                button: _t('Continue'),
                onFinished: (confirmed) => {
                    if (confirmed) {
                        this.submitPasswordReset(
                            this.state.enteredHsUrl, this.state.enteredIsUrl,
                            this.state.email, this.state.password,
                        );
                    }
                },
            });
        }
    },

    onInputChanged: function(stateKey, ev) {
        this.setState({
            [stateKey]: ev.target.value,
        });
    },

    onServerConfigChange: function(config) {
        const newState = {};
        if (config.hsUrl !== undefined) {
            newState.enteredHsUrl = config.hsUrl;
        }
        if (config.isUrl !== undefined) {
            newState.enteredIsUrl = config.isUrl;
        }
        this.setState(newState);
    },

    onServerDetailsNextPhaseClick(ev) {
        ev.stopPropagation();
        this.setState({
            phase: PHASE_FORGOT,
        });
    },

    onEditServerDetailsClick(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        this.setState({
            phase: PHASE_SERVER_DETAILS,
        });
    },

    onLoginClick: function(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        this.props.onLoginClick();
    },

    showErrorDialog: function(body, title) {
        const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
        Modal.createTrackedDialog('Forgot Password Error', '', ErrorDialog, {
            title: title,
            description: body,
        });
    },

    renderServerDetails() {
        const ServerConfig = sdk.getComponent("auth.ServerConfig");
        const AccessibleButton = sdk.getComponent("elements.AccessibleButton");

        if (SdkConfig.get()['disable_custom_urls']) {
            return null;
        }

        return

            <ServerConfig
                defaultHsUrl={this.props.defaultHsUrl}
                defaultIsUrl={this.props.defaultIsUrl}
                customHsUrl={this.state.enteredHsUrl}
                customIsUrl={this.state.enteredIsUrl}
                onServerConfigChange={this.onServerConfigChange}
                delayTimeMs={0} />
            <AccessibleButton className="mx_Login_submit"
                onClick={this.onServerDetailsNextPhaseClick}
            >
                {_t("Next")}
            </AccessibleButton>

;
    },

    renderForgot() {
        const Field = sdk.getComponent('elements.Field');

        let errorText = null;
        const err = this.state.errorText || this.props.defaultServerDiscoveryError;
        if (err) {
            errorText =
{ err }
;
        }

        let yourMatrixAccountText = _t('Your Matrix account');
        if (this.state.enteredHsUrl === this.props.defaultHsUrl) {
            yourMatrixAccountText = _t('Your Matrix account on %(serverName)s', {
                serverName: this.props.defaultServerName,
            });
        } else {
            try {
                const parsedHsUrl = new URL(this.state.enteredHsUrl);
                yourMatrixAccountText = _t('Your Matrix account on %(serverName)s', {
                    serverName: parsedHsUrl.hostname,
                });
            } catch (e) {
                errorText =
{_t(
                    "The homeserver URL %(hsUrl)s doesn't seem to be valid URL. Please " +
                    "enter a valid URL including the protocol prefix.",
                {
                    hsUrl: this.state.enteredHsUrl,
                })}
;
            }
        }

        // If custom URLs are allowed, wire up the server details edit link.
        let editLink = null;
        if (!SdkConfig.get()['disable_custom_urls']) {
            editLink =
                {_t('Change')}
            ;
        }

        return

                {yourMatrixAccountText}
                {editLink}

            {errorText}
            <form onSubmit={this.onSubmitForm}>

                    <Field
                        id="mx_ForgotPassword_email"
                        name="reset_email" // define a name so browser's password autofill gets less confused
                        type="text"
                        label={_t('Email')}
                        value={this.state.email}
                        onChange={this.onInputChanged.bind(this, "email")}
                        autoFocus
                    />

                    <Field
                        id="mx_ForgotPassword_password"
                        name="reset_password"
                        type="password"
                        label={_t('Password')}
                        value={this.state.password}
                        onChange={this.onInputChanged.bind(this, "password")}
                    />
                    <Field
                        id="mx_ForgotPassword_passwordConfirm"
                        name="reset_password_confirm"
                        type="password"
                        label={_t('Confirm')}
                        value={this.state.password2}
                        onChange={this.onInputChanged.bind(this, "password2")}
                    />

                {_t(
                    'A verification email will be sent to your inbox to confirm ' +
                    'setting your new password.',
                )}
                <input className="mx_Login_submit" type="submit" value={_t('Send Reset Email')} />
            </form>

                {_t('Sign in instead')}

;
    },

    renderSendingEmail() {
        const Spinner = sdk.getComponent("elements.Spinner");
        return <Spinner />;
    },

    renderEmailSent() {
        return

            {_t("An email has been sent to %(emailAddress)s. Once you've followed the " +
                "link it contains, click below.", { emailAddress: this.state.email })}

            <input className="mx_Login_submit" type="button" onClick={this.onVerify}
                value={_t('I have verified my email address')} />

;
    },

    renderDone() {
        return

{_t("Your password has been reset.")}

{_t(
                "You have been logged out of all devices and will no longer receive " +
                "push notifications. To re-enable notifications, sign in again on each " +
                "device.",
            )}

            <input className="mx_Login_submit" type="button" onClick={this.props.onComplete}
                value={_t('Return to login screen')} />

;
    },

    render: function() {
        const AuthPage = sdk.getComponent("auth.AuthPage");
        const AuthHeader = sdk.getComponent("auth.AuthHeader");
        const AuthBody = sdk.getComponent("auth.AuthBody");

        let resetPasswordJsx;
        switch (this.state.phase) {
            case PHASE_SERVER_DETAILS:
                resetPasswordJsx = this.renderServerDetails();
                break;
            case PHASE_FORGOT:
                resetPasswordJsx = this.renderForgot();
                break;
            case PHASE_SENDING_EMAIL:
                resetPasswordJsx = this.renderSendingEmail();
                break;
            case PHASE_EMAIL_SENT:
                resetPasswordJsx = this.renderEmailSent();
                break;
            case PHASE_DONE:
                resetPasswordJsx = this.renderDone();
                break;
        }

        return (
            <AuthPage>
                <AuthHeader />
                <AuthBody>

 { _t('Set a new password') }

                    {resetPasswordJsx}
                </AuthBody>
            </AuthPage>
        );
    },
});
<commit_msg>Test `defaultServerName` before showing it on forgot password<commit_after>/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017, 2018, 2019 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React from 'react';
import PropTypes from 'prop-types';
import { _t } from '../../../languageHandler';
import sdk from '../../../index';
import Modal from "../../../Modal";
import SdkConfig from "../../../SdkConfig";

import PasswordReset from "../../../PasswordReset";

// Phases
// Show controls to configure server details
const PHASE_SERVER_DETAILS = 0;
// Show the forgot password inputs
const PHASE_FORGOT = 1;
// Email is in the process of being sent
const PHASE_SENDING_EMAIL = 2;
// Email has been sent
const PHASE_EMAIL_SENT = 3;
// User has clicked the link in email and completed reset
const PHASE_DONE = 4;

module.exports = React.createClass({
    displayName: 'ForgotPassword',

    propTypes: {
        // The default server name to use when the user hasn't specified
        // one. If set, `defaultHsUrl` and `defaultHsUrl` were derived for this
        // via `.well-known` discovery. The server name is used instead of the
        // HS URL when talking about "your account".
        defaultServerName: PropTypes.string,
        // An error passed along from higher up explaining that something
        // went wrong when finding the defaultHsUrl.
        defaultServerDiscoveryError: PropTypes.string,

        defaultHsUrl: PropTypes.string,
        defaultIsUrl: PropTypes.string,
        customHsUrl: PropTypes.string,
        customIsUrl: PropTypes.string,

        onLoginClick: PropTypes.func,
        onComplete: PropTypes.func.isRequired,
    },

    getInitialState: function() {
        return {
            enteredHsUrl: this.props.customHsUrl || this.props.defaultHsUrl,
            enteredIsUrl: this.props.customIsUrl || this.props.defaultIsUrl,
            phase: PHASE_FORGOT,
            email: "",
            password: "",
            password2: "",
            errorText: null,
        };
    },

    submitPasswordReset: function(hsUrl, identityUrl, email, password) {
        this.setState({
            phase: PHASE_SENDING_EMAIL,
        });
        this.reset = new PasswordReset(hsUrl, identityUrl);
        this.reset.resetPassword(email, password).done(() => {
            this.setState({
                phase: PHASE_EMAIL_SENT,
            });
        }, (err) => {
            this.showErrorDialog(_t('Failed to send email') + ": " + err.message);
            this.setState({
                phase: PHASE_FORGOT,
            });
        });
    },

    onVerify: function(ev) {
        ev.preventDefault();
        if (!this.reset) {
            console.error("onVerify called before submitPasswordReset!");
            return;
        }
        this.reset.checkEmailLinkClicked().done((res) => {
            this.setState({ phase: PHASE_DONE });
        }, (err) => {
            this.showErrorDialog(err.message);
        });
    },

    onSubmitForm: function(ev) {
        ev.preventDefault();

        // Don't allow the user to register if there's a discovery error
        // Without this, the user could end up registering on the wrong homeserver.
        if (this.props.defaultServerDiscoveryError) {
            this.setState({errorText: this.props.defaultServerDiscoveryError});
            return;
        }

        if (!this.state.email) {
            this.showErrorDialog(_t('The email address linked to your account must be entered.'));
        } else if (!this.state.password || !this.state.password2) {
            this.showErrorDialog(_t('A new password must be entered.'));
        } else if (this.state.password !== this.state.password2) {
            this.showErrorDialog(_t('New passwords must match each other.'));
        } else {
            const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog");
            Modal.createTrackedDialog('Forgot Password Warning', '', QuestionDialog, {
                title: _t('Warning!'),
                description:

                        { _t(
                            "Changing your password will reset any end-to-end encryption keys " +
                            "on all of your devices, making encrypted chat history unreadable. Set up " +
                            "Key Backup or export your room keys from another device before resetting your " +
                            "password.",
                        ) }

,
                button: _t('Continue'),
                onFinished: (confirmed) => {
                    if (confirmed) {
                        this.submitPasswordReset(
                            this.state.enteredHsUrl, this.state.enteredIsUrl,
                            this.state.email, this.state.password,
                        );
                    }
                },
            });
        }
    },

    onInputChanged: function(stateKey, ev) {
        this.setState({
            [stateKey]: ev.target.value,
        });
    },

    onServerConfigChange: function(config) {
        const newState = {};
        if (config.hsUrl !== undefined) {
            newState.enteredHsUrl = config.hsUrl;
        }
        if (config.isUrl !== undefined) {
            newState.enteredIsUrl = config.isUrl;
        }
        this.setState(newState);
    },

    onServerDetailsNextPhaseClick(ev) {
        ev.stopPropagation();
        this.setState({
            phase: PHASE_FORGOT,
        });
    },

    onEditServerDetailsClick(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        this.setState({
            phase: PHASE_SERVER_DETAILS,
        });
    },

    onLoginClick: function(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        this.props.onLoginClick();
    },

    showErrorDialog: function(body, title) {
        const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
        Modal.createTrackedDialog('Forgot Password Error', '', ErrorDialog, {
            title: title,
            description: body,
        });
    },

    renderServerDetails() {
        const ServerConfig = sdk.getComponent("auth.ServerConfig");
        const AccessibleButton = sdk.getComponent("elements.AccessibleButton");

        if (SdkConfig.get()['disable_custom_urls']) {
            return null;
        }

        return

            <ServerConfig
                defaultHsUrl={this.props.defaultHsUrl}
                defaultIsUrl={this.props.defaultIsUrl}
                customHsUrl={this.state.enteredHsUrl}
                customIsUrl={this.state.enteredIsUrl}
                onServerConfigChange={this.onServerConfigChange}
                delayTimeMs={0} />
            <AccessibleButton className="mx_Login_submit"
                onClick={this.onServerDetailsNextPhaseClick}
            >
                {_t("Next")}
            </AccessibleButton>

;
    },

    renderForgot() {
        const Field = sdk.getComponent('elements.Field');

        let errorText = null;
        const err = this.state.errorText || this.props.defaultServerDiscoveryError;
        if (err) {
            errorText =
{ err }
;
        }

        let yourMatrixAccountText = _t('Your Matrix account');
        if (this.state.enteredHsUrl === this.props.defaultHsUrl && this.props.defaultServerName) {
            yourMatrixAccountText = _t('Your Matrix account on %(serverName)s', {
                serverName: this.props.defaultServerName,
            });
        } else {
            try {
                const parsedHsUrl = new URL(this.state.enteredHsUrl);
                yourMatrixAccountText = _t('Your Matrix account on %(serverName)s', {
                    serverName: parsedHsUrl.hostname,
                });
            } catch (e) {
                errorText =
{_t(
                    "The homeserver URL %(hsUrl)s doesn't seem to be valid URL. Please " +
                    "enter a valid URL including the protocol prefix.",
                {
                    hsUrl: this.state.enteredHsUrl,
                })}
;
            }
        }

        // If custom URLs are allowed, wire up the server details edit link.
        let editLink = null;
        if (!SdkConfig.get()['disable_custom_urls']) {
            editLink =
                {_t('Change')}
            ;
        }

        return

                {yourMatrixAccountText}
                {editLink}

            {errorText}
            <form onSubmit={this.onSubmitForm}>

                    <Field
                        id="mx_ForgotPassword_email"
                        name="reset_email" // define a name so browser's password autofill gets less confused
                        type="text"
                        label={_t('Email')}
                        value={this.state.email}
                        onChange={this.onInputChanged.bind(this, "email")}
                        autoFocus
                    />

                    <Field
                        id="mx_ForgotPassword_password"
                        name="reset_password"
                        type="password"
                        label={_t('Password')}
                        value={this.state.password}
                        onChange={this.onInputChanged.bind(this, "password")}
                    />
                    <Field
                        id="mx_ForgotPassword_passwordConfirm"
                        name="reset_password_confirm"
                        type="password"
                        label={_t('Confirm')}
                        value={this.state.password2}
                        onChange={this.onInputChanged.bind(this, "password2")}
                    />

                {_t(
                    'A verification email will be sent to your inbox to confirm ' +
                    'setting your new password.',
                )}
                <input className="mx_Login_submit" type="submit" value={_t('Send Reset Email')} />
            </form>

                {_t('Sign in instead')}

;
    },

    renderSendingEmail() {
        const Spinner = sdk.getComponent("elements.Spinner");
        return <Spinner />;
    },

    renderEmailSent() {
        return

            {_t("An email has been sent to %(emailAddress)s. Once you've followed the " +
                "link it contains, click below.", { emailAddress: this.state.email })}

            <input className="mx_Login_submit" type="button" onClick={this.onVerify}
                value={_t('I have verified my email address')} />

;
    },

    renderDone() {
        return

{_t("Your password has been reset.")}

{_t(
                "You have been logged out of all devices and will no longer receive " +
                "push notifications. To re-enable notifications, sign in again on each " +
                "device.",
            )}

            <input className="mx_Login_submit" type="button" onClick={this.props.onComplete}
                value={_t('Return to login screen')} />

;
    },

    render: function() {
        const AuthPage = sdk.getComponent("auth.AuthPage");
        const AuthHeader = sdk.getComponent("auth.AuthHeader");
        const AuthBody = sdk.getComponent("auth.AuthBody");

        let resetPasswordJsx;
        switch (this.state.phase) {
            case PHASE_SERVER_DETAILS:
                resetPasswordJsx = this.renderServerDetails();
                break;
            case PHASE_FORGOT:
                resetPasswordJsx = this.renderForgot();
                break;
            case PHASE_SENDING_EMAIL:
                resetPasswordJsx = this.renderSendingEmail();
                break;
            case PHASE_EMAIL_SENT:
                resetPasswordJsx = this.renderEmailSent();
                break;
            case PHASE_DONE:
                resetPasswordJsx = this.renderDone();
                break;
        }

        return (
            <AuthPage>
                <AuthHeader />
                <AuthBody>

 { _t('Set a new password') }

                    {resetPasswordJsx}
                </AuthBody>
            </AuthPage>
        );
    },
});
<|endoftext|>


<commit_before>import build from "./scripts/build"
import start from "./scripts/start"

var script = process.argv[2]
var args = process.argv.slice(3)

switch (script)
{
  case "build":
    build(args)
    break

  case "start":
    start(args)
    break

  case null:
  case undefined:
    console.log("No script name given!")
    break

  default:
    console.log(`Unknown script "${script}"!`)
    break
}
<commit_msg>Add bootstrap command<commit_after>/* eslint no-console: off */
import build from "./scripts/build"
import start from "./scripts/start"
import bootstrap from "./scripts/bootstrap"

const ARGSPOS_SCRIPT = 2
const ARGSPOS_ARGUMENTS = 3

var script = process.argv[ARGSPOS_SCRIPT]
var args = process.argv.slice(ARGSPOS_ARGUMENTS)

switch (script)
{
  case "build":
    build(args)
    break

  case "start":
    start(args)
    break

  case "bootstrap":
    bootstrap(args)
    break

  case null:
  case undefined:
    console.log("No script name given!")
    break

  default:
    console.log(`Unknown script "${script}"!`)
    break
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import moment from 'moment';

export default class Todo extends Component {
  static propTypes = {
    id: PropTypes.number.isRequired,
    createdAt: PropTypes.number.isRequired,
    updatedAt: PropTypes.number.isRequired,
    deleted: PropTypes.bool.isRequired,
    completed: PropTypes.bool.isRequired,
    edit: PropTypes.bool.isRequired,
    text: PropTypes.string.isRequired,
    toggleComplete: PropTypes.func.isRequired,
    editTodo: PropTypes.func.isRequired,
    updateTodo: PropTypes.func.isRequired,
    deleteTodo: PropTypes.func.isRequired,
  };

  constructor(props) {
    super(props);
    this.props = props;
  }

  state = {
    text: this.props.text,
  }

  updateText = e => this.setState({ text: e.target.value })

  render() {
    const { id, text, createdAt, updatedAt, deleted, completed, edit,
      toggleComplete, editTodo, updateTodo, deleteTodo } = this.props;

    const iconClasses = classNames({
      fa: true,
      'fa-square-o': !completed,
      'fa-check-square-o': completed,
    });

    return (
      deleted ?
        null :

            created {moment(createdAt).fromNow()}

          {edit ?
            null :
             toggleComplete(id)}>

          }
          {edit ?

                <textarea
                  className="textarea"
                  value={this.state.text}
                  onChange={this.updateText} />

            :
            {text}
          }

            {updatedAt ?

                edited {moment(updatedAt).fromNow()}
               : null
            }
            {edit ?
               updateTodo(id, this.state.text)}>

              :
               editTodo(id)}>

            }
             deleteTodo(id)}>

    );
  }
}
<commit_msg>Edit and create messages update automatically<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import moment from 'moment';

export default class Todo extends Component {
  static propTypes = {
    id: PropTypes.number.isRequired,
    createdAt: PropTypes.number.isRequired,
    updatedAt: PropTypes.number,
    deleted: PropTypes.bool.isRequired,
    completed: PropTypes.bool.isRequired,
    edit: PropTypes.bool.isRequired,
    text: PropTypes.string.isRequired,
    toggleComplete: PropTypes.func.isRequired,
    editTodo: PropTypes.func.isRequired,
    updateTodo: PropTypes.func.isRequired,
    deleteTodo: PropTypes.func.isRequired,
  };

  static defaultProps = {
    updatedAt: 0,
  }

  constructor(props) {
    super(props);
    this.props = props;
  }

  state = {
    text: this.props.text,
    updateMessage: '',
    createMessage: '',
  }

  componentDidMount() {
    this.updateMessages();
    this.interval = window.setInterval(this.updateMessages, 1000);
  }

  componentWillReceiveProps(props) {
    this.setState({ updatedMessage: moment(props.updatedAt).fromNow() });
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  updateMessages = () => {
    this.setState({
      updatedMessage: this.props.updatedAt ? moment(this.props.updatedAt).fromNow() : '',
      createdMessage: moment(this.props.createdAt).fromNow(),
    });
  }

  updateText = e => this.setState({ text: e.target.value })

  render() {
    const { id, text, updatedAt, deleted, completed, edit,
      toggleComplete, editTodo, updateTodo, deleteTodo } = this.props;

    const iconClasses = classNames({
      fa: true,
      'fa-square-o': !completed,
      'fa-check-square-o': completed,
    });

    return (
      deleted ?
        null :

            created {this.state.createdMessage}

          {edit ?
            null :
             toggleComplete(id)}>

          }
          {edit ?

                <textarea
                  className="textarea"
                  value={this.state.text}
                  onChange={this.updateText} />

            :
            {text}
          }

            {updatedAt ?

                edited {this.state.updatedMessage}
               : null
            }
            {edit ?
               updateTodo(id, this.state.text)}>

              :
               editTodo(id)}>

            }
             deleteTodo(id)}>

    );
  }
}
<|endoftext|>


<commit_before>var LightSliderNetworkInit = function() {

    this.slider = null;
    this.map = null;
    this.markers = [];
    this.currentLine = null;
    this.animationInterval = null;

    //
    // Init
    //
    this.init();

};

LightSliderNetworkInit.prototype.init = function() {

    var that = this;

    //
    // Slider init
    //
    /*that.slider = $('[data-slider-network]').lightSlider({
        item: 4,
        slideMargin: 10,
        pager: false,
        controls: false,
        loop: false,
        adaptiveHeight: true,
        onSliderLoad: function(elem) {
            elem.parents('.slider-network').find('.lSPrev').click(function(e) {
                elem.goToPrevSlide();
            });
            elem.parents('.slider-network').find('.lSNext').click(function(e) {
                elem.goToNextSlide();
            });
        },
        onBeforeSlide: function(elem) {
            if (that.currentLine) {
                that.currentLine.setMap(null);
            }
        }
    });*/

    //
    // Init map
    //
    if($('#network-map').length > 0) {

        that.map = new google.maps.Map(document.getElementById('network-map'), {
            zoom: 5,
            center: {lat: 48.85982, lng: 2.351402},
            //styles: [ { "featureType": "all", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "administrative", "elementType": "labels.text", "stylers": [ { "visibility": "off" } ] }, { "featureType": "landscape", "elementType": "all", "stylers": [ { "color": "#6c8080" }, { "visibility": "simplified" } ] }, { "featureType": "landscape.man_made", "elementType": "geometry.fill", "stylers": [ { "lightness": "0" }, { "color": "#000f24" } ] }, { "featureType": "landscape.natural", "elementType": "geometry.fill", "stylers": [ { "lightness": "0" }, { "color": "#000f24" } ] }, { "featureType": "landscape.natural.landcover", "elementType": "geometry.fill", "stylers": [ { "saturation": "0" }, { "lightness": "0" }, { "color": "#000f24" } ] }, { "featureType": "landscape.natural.terrain", "elementType": "geometry.fill", "stylers": [ { "color": "#000f24" } ] }, { "featureType": "landscape.natural.terrain", "elementType": "geometry.stroke", "stylers": [ { "saturation": "0" }, { "lightness": "0" } ] }, { "featureType": "poi", "elementType": "all", "stylers": [ { "visibility": "off" } ] }, { "featureType": "road", "elementType": "all", "stylers": [ { "visibility": "simplified" } ] }, { "featureType": "road", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] }, { "featureType": "road.highway", "elementType": "all", "stylers": [ { "color": "#d98080" }, { "hue": "#eeff00" }, { "lightness": 100 }, { "weight": 1.5 } ] }, { "featureType": "road.highway", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "transit", "elementType": "labels", "stylers": [ { "visibility": "off" } ] } ]
            styles: [{"featureType":"all","elementType":"geometry","stylers":[{"color":"#ffffff"}]},{"featureType":"all","elementType":"labels.text.fill","stylers":[{"gamma":0.01},{"lightness":20}]},{"featureType":"all","elementType":"labels.text.stroke","stylers":[{"saturation":-31},{"lightness":-33},{"weight":2},{"gamma":0.8}]},{"featureType":"all","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"administrative.locality","elementType":"labels.text.fill","stylers":[{"color":"#050505"}]},{"featureType":"administrative.locality","elementType":"labels.text.stroke","stylers":[{"color":"#fef3f3"},{"weight":"3.01"}]},{"featureType":"administrative.neighborhood","elementType":"labels.text.fill","stylers":[{"color":"#0a0a0a"},{"visibility":"off"}]},{"featureType":"administrative.neighborhood","elementType":"labels.text.stroke","stylers":[{"color":"#fffbfb"},{"weight":"3.01"},{"visibility":"off"}]},{"featureType":"landscape","elementType":"geometry","stylers":[{"lightness":30},{"saturation":30}]},{"featureType":"poi","elementType":"geometry","stylers":[{"saturation":20}]},{"featureType":"poi.attraction","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"lightness":20},{"saturation":-20}]},{"featureType":"road","elementType":"geometry","stylers":[{"lightness":10},{"saturation":-30}]},{"featureType":"road","elementType":"geometry.stroke","stylers":[{"saturation":25},{"lightness":25}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#a1a1a1"}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#292929"}]},{"featureType":"road.highway","elementType":"labels.text.fill","stylers":[{"visibility":"on"},{"color":"#202020"}]},{"featureType":"road.highway","elementType":"labels.text.stroke","stylers":[{"visibility":"on"},{"color":"#ffffff"}]},{"featureType":"road.highway","elementType":"labels.icon","stylers":[{"visibility":"simplified"},{"hue":"#0006ff"},{"saturation":"-100"},{"lightness":"13"},{"gamma":"0.00"}]},{"featureType":"road.arterial","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#686868"}]},{"featureType":"road.arterial","elementType":"geometry.stroke","stylers":[{"visibility":"off"},{"color":"#8d8d8d"}]},{"featureType":"road.arterial","elementType":"labels.text.fill","stylers":[{"visibility":"on"},{"color":"#353535"},{"lightness":"6"}]},{"featureType":"road.arterial","elementType":"labels.text.stroke","stylers":[{"visibility":"on"},{"color":"#ffffff"},{"weight":"3.45"}]},{"featureType":"road.local","elementType":"geometry.fill","stylers":[{"color":"#d0d0d0"}]},{"featureType":"road.local","elementType":"geometry.stroke","stylers":[{"lightness":"2"},{"visibility":"on"},{"color":"#999898"}]},{"featureType":"road.local","elementType":"labels.text.fill","stylers":[{"color":"#383838"}]},{"featureType":"road.local","elementType":"labels.text.stroke","stylers":[{"color":"#faf8f8"}]},{"featureType":"water","elementType":"all","stylers":[{"lightness":-20}]}]
        });

        google.maps.event.addListenerOnce(that.map, 'projection_changed', function() {
            that.initMarkers();
        });

        google.maps.event.addListener(that.map, 'zoom_changed', function() {
            if (that.map.getZoom() < 3) that.map.setZoom(3);
        });

    }

};

LightSliderNetworkInit.prototype.initMarkers = function() {

    var that = this;

    $('[data-marker-idx]').each(function(idx) {

        var obj = {
            'lat': parseFloat($(this).attr('data-marker-lat').replace(',', '.')),
            'lng': parseFloat($(this).attr('data-marker-lng').replace(',', '.')),
            'elem': $(this),
            'marker': new google.maps.Marker({
                position: {lat: parseFloat($(this).attr('data-marker-lat').replace(',', '.')), lng: parseFloat($(this).attr('data-marker-lng').replace(',', '.'))},
                map: that.map,
                icon: "/static/img/map-marker-" + $(this).attr('data-marker-color') + ".png"
            })
        };

        var info = new google.maps.InfoWindow({
            content: '

' + $(this).find('[data-marker-title]').text() + '

' + $(this).find('[data-marker-subtitle]').text() + '

' + $(this).find('[data-marker-description]').text() + '

'
        });

        obj.info = info;

        obj.marker.addListener('click', function() {
            that.markers.forEach(function(m, i) {
                m.info.close();
            });
            info.open(that.map, obj.marker);
        });

        that.markers.push(obj);

    });

};

module.exports = LightSliderNetworkInit;
<commit_msg>Fix zoom<commit_after>var LightSliderNetworkInit = function() {

    this.slider = null;
    this.map = null;
    this.markers = [];
    this.currentLine = null;
    this.animationInterval = null;

    //
    // Init
    //
    this.init();

};

LightSliderNetworkInit.prototype.init = function() {

    var that = this;

    //
    // Slider init
    //
    /*that.slider = $('[data-slider-network]').lightSlider({
        item: 4,
        slideMargin: 10,
        pager: false,
        controls: false,
        loop: false,
        adaptiveHeight: true,
        onSliderLoad: function(elem) {
            elem.parents('.slider-network').find('.lSPrev').click(function(e) {
                elem.goToPrevSlide();
            });
            elem.parents('.slider-network').find('.lSNext').click(function(e) {
                elem.goToNextSlide();
            });
        },
        onBeforeSlide: function(elem) {
            if (that.currentLine) {
                that.currentLine.setMap(null);
            }
        }
    });*/

    //
    // Init map
    //
    if($('#network-map').length > 0) {

        that.map = new google.maps.Map(document.getElementById('network-map'), {
            zoom: 3,
            center: {lat: 48.85982, lng: 2.351402},
            //styles: [ { "featureType": "all", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "administrative", "elementType": "labels.text", "stylers": [ { "visibility": "off" } ] }, { "featureType": "landscape", "elementType": "all", "stylers": [ { "color": "#6c8080" }, { "visibility": "simplified" } ] }, { "featureType": "landscape.man_made", "elementType": "geometry.fill", "stylers": [ { "lightness": "0" }, { "color": "#000f24" } ] }, { "featureType": "landscape.natural", "elementType": "geometry.fill", "stylers": [ { "lightness": "0" }, { "color": "#000f24" } ] }, { "featureType": "landscape.natural.landcover", "elementType": "geometry.fill", "stylers": [ { "saturation": "0" }, { "lightness": "0" }, { "color": "#000f24" } ] }, { "featureType": "landscape.natural.terrain", "elementType": "geometry.fill", "stylers": [ { "color": "#000f24" } ] }, { "featureType": "landscape.natural.terrain", "elementType": "geometry.stroke", "stylers": [ { "saturation": "0" }, { "lightness": "0" } ] }, { "featureType": "poi", "elementType": "all", "stylers": [ { "visibility": "off" } ] }, { "featureType": "road", "elementType": "all", "stylers": [ { "visibility": "simplified" } ] }, { "featureType": "road", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] }, { "featureType": "road.highway", "elementType": "all", "stylers": [ { "color": "#d98080" }, { "hue": "#eeff00" }, { "lightness": 100 }, { "weight": 1.5 } ] }, { "featureType": "road.highway", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "transit", "elementType": "labels", "stylers": [ { "visibility": "off" } ] } ]
            styles: [{"featureType":"all","elementType":"geometry","stylers":[{"color":"#ffffff"}]},{"featureType":"all","elementType":"labels.text.fill","stylers":[{"gamma":0.01},{"lightness":20}]},{"featureType":"all","elementType":"labels.text.stroke","stylers":[{"saturation":-31},{"lightness":-33},{"weight":2},{"gamma":0.8}]},{"featureType":"all","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"administrative.locality","elementType":"labels.text.fill","stylers":[{"color":"#050505"}]},{"featureType":"administrative.locality","elementType":"labels.text.stroke","stylers":[{"color":"#fef3f3"},{"weight":"3.01"}]},{"featureType":"administrative.neighborhood","elementType":"labels.text.fill","stylers":[{"color":"#0a0a0a"},{"visibility":"off"}]},{"featureType":"administrative.neighborhood","elementType":"labels.text.stroke","stylers":[{"color":"#fffbfb"},{"weight":"3.01"},{"visibility":"off"}]},{"featureType":"landscape","elementType":"geometry","stylers":[{"lightness":30},{"saturation":30}]},{"featureType":"poi","elementType":"geometry","stylers":[{"saturation":20}]},{"featureType":"poi.attraction","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"lightness":20},{"saturation":-20}]},{"featureType":"road","elementType":"geometry","stylers":[{"lightness":10},{"saturation":-30}]},{"featureType":"road","elementType":"geometry.stroke","stylers":[{"saturation":25},{"lightness":25}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#a1a1a1"}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#292929"}]},{"featureType":"road.highway","elementType":"labels.text.fill","stylers":[{"visibility":"on"},{"color":"#202020"}]},{"featureType":"road.highway","elementType":"labels.text.stroke","stylers":[{"visibility":"on"},{"color":"#ffffff"}]},{"featureType":"road.highway","elementType":"labels.icon","stylers":[{"visibility":"simplified"},{"hue":"#0006ff"},{"saturation":"-100"},{"lightness":"13"},{"gamma":"0.00"}]},{"featureType":"road.arterial","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#686868"}]},{"featureType":"road.arterial","elementType":"geometry.stroke","stylers":[{"visibility":"off"},{"color":"#8d8d8d"}]},{"featureType":"road.arterial","elementType":"labels.text.fill","stylers":[{"visibility":"on"},{"color":"#353535"},{"lightness":"6"}]},{"featureType":"road.arterial","elementType":"labels.text.stroke","stylers":[{"visibility":"on"},{"color":"#ffffff"},{"weight":"3.45"}]},{"featureType":"road.local","elementType":"geometry.fill","stylers":[{"color":"#d0d0d0"}]},{"featureType":"road.local","elementType":"geometry.stroke","stylers":[{"lightness":"2"},{"visibility":"on"},{"color":"#999898"}]},{"featureType":"road.local","elementType":"labels.text.fill","stylers":[{"color":"#383838"}]},{"featureType":"road.local","elementType":"labels.text.stroke","stylers":[{"color":"#faf8f8"}]},{"featureType":"water","elementType":"all","stylers":[{"lightness":-20}]}]
        });

        google.maps.event.addListenerOnce(that.map, 'projection_changed', function() {
            that.initMarkers();
        });

        google.maps.event.addListener(that.map, 'zoom_changed', function() {
            if (that.map.getZoom() < 3) that.map.setZoom(3);
        });

    }

};

LightSliderNetworkInit.prototype.initMarkers = function() {

    var that = this;

    $('[data-marker-idx]').each(function(idx) {

        var obj = {
            'lat': parseFloat($(this).attr('data-marker-lat').replace(',', '.')),
            'lng': parseFloat($(this).attr('data-marker-lng').replace(',', '.')),
            'elem': $(this),
            'marker': new google.maps.Marker({
                position: {lat: parseFloat($(this).attr('data-marker-lat').replace(',', '.')), lng: parseFloat($(this).attr('data-marker-lng').replace(',', '.'))},
                map: that.map,
                icon: "/static/img/map-marker-" + $(this).attr('data-marker-color') + ".png"
            })
        };

        var info = new google.maps.InfoWindow({
            content: '

' + $(this).find('[data-marker-title]').text() + '

' + $(this).find('[data-marker-subtitle]').text() + '

' + $(this).find('[data-marker-description]').text() + '

'
        });

        obj.info = info;

        obj.marker.addListener('click', function() {
            that.markers.forEach(function(m, i) {
                m.info.close();
            });
            info.open(that.map, obj.marker);
        });

        that.markers.push(obj);

    });

};

module.exports = LightSliderNetworkInit;
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var utility;
utility = function () {
    // var log = new Log("modules/utility.js");
    var JavaClass = Packages.java.lang.Class;
    var PrivilegedCarbonContext = Packages.org.wso2.carbon.context.PrivilegedCarbonContext;

    var getOsgiService = function (className) {
        return PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(JavaClass.forName(className));
    };

    var publicMethods = {};

    publicMethods.startTenantFlow = function (userInfo) {
        var context, carbon = require('carbon');
        PrivilegedCarbonContext.startTenantFlow();
        context = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        context.setTenantDomain(carbon.server.tenantDomain({
            tenantId: userInfo.tenantId
        }));
        context.setTenantId(userInfo.tenantId);
        context.setUsername(userInfo.username || null);
    };

    publicMethods.endTenantFlow = function () {
        PrivilegedCarbonContext.endTenantFlow();
    };

    publicMethods.getDeviceManagementService = function () {
        return getOsgiService('org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService');
    };

    publicMethods.getUserManagementService = function () {
        return getOsgiService("org.wso2.carbon.device.mgt.user.core.UserManager");
    };

    publicMethods.getPolicyManagementService = function () {
        return getOsgiService("org.wso2.carbon.policy.mgt.core.PolicyManagerService");
    };

    publicMethods.insertAppPermissions = function (userModule, type) {
        userModule.addPermissions([{key: "device-mgt", name: "Device Management"}], "", type);
        // Below are the 2 types of users:- Normal users and Admins
        userModule.addPermissions([{key: "emm-admin", name: "Device Management Admin"}], "device-mgt", type);
        userModule.addPermissions([{key: "user", name: "Device Management User"}], "device-mgt", type);

        // adding permission definitions for device-mgt/admin
        userModule.addPermissions([{key: "dashboard", name: "Dashboard"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "dashboard/view", name: "View Dashboard"}], "device-mgt/emm-admin", type);

        userModule.addPermissions([{key: "devices", name: "Devices"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "devices/list", name: "List All Devices"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "devices/operation", name: "Perform Operation on Any Device"}],
                                         "device-mgt/emm-admin", type);

        userModule.addPermissions([{key: "users", name: "Users"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "users/add", name: "Add New Users"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "users/invite", name: "Invite Users"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "users/list", name: "List Users"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "users/remove", name: "Remove Users"}], "device-mgt/emm-admin", type);

        userModule.addPermissions([{key: "roles", name: "Roles"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "roles/add", name: "Add New Roles"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "roles/invite", name: "Invite Roles"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "roles/list", name: "List Roles"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "roles/remove", name: "Remove Roles"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "roles/permission", name: "Update Role Permission"}], "device-mgt/emm-admin", type);

        userModule.addPermissions([{key: "policies", name: "Policy"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "policies/add", name: "Add Policy"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "policies/list", name: "List Policy"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "policies/edit", name: "Edit Policy"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "policies/remove", name: "Remove Policy"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "policies/priority", name: "Policy Priority"}], "device-mgt/emm-admin", type);

        // adding permission definitions for device-mgt/user
        userModule.addPermissions([{key: "devices", name: "Devices"}], "device-mgt/user", type);
        userModule.addPermissions([{key: "devices/list", name: "List Individual Devices"}], "device-mgt/user", type);
        userModule.addPermissions([{key: "devices/operation", name: "Perform Operation on an Individual Device"}],
                                         "device-mgt/user", type);

        userModule.addPermissions([{key: "platform-configs", name: "Platform Configurations"}], "device-mgt/admin", type);
        userModule.addPermissions([{key: "platform-configs/view", name: "View Configurations"}], "device-mgt/emm-admin", type);
    };

    return publicMethods;
}();

<commit_msg>Fixed EMM-960<commit_after>/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var utility;
utility = function () {
    // var log = new Log("modules/utility.js");
    var JavaClass = Packages.java.lang.Class;
    var PrivilegedCarbonContext = Packages.org.wso2.carbon.context.PrivilegedCarbonContext;

    var getOsgiService = function (className) {
        return PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(JavaClass.forName(className));
    };

    var publicMethods = {};

    publicMethods.startTenantFlow = function (userInfo) {
        var context, carbon = require('carbon');
        PrivilegedCarbonContext.startTenantFlow();
        context = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        context.setTenantDomain(carbon.server.tenantDomain({
            tenantId: userInfo.tenantId
        }));
        context.setTenantId(userInfo.tenantId);
        context.setUsername(userInfo.username || null);
    };

    publicMethods.endTenantFlow = function () {
        PrivilegedCarbonContext.endTenantFlow();
    };

    publicMethods.getDeviceManagementService = function () {
        return getOsgiService('org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService');
    };

    publicMethods.getUserManagementService = function () {
        return getOsgiService("org.wso2.carbon.device.mgt.user.core.UserManager");
    };

    publicMethods.getPolicyManagementService = function () {
        return getOsgiService("org.wso2.carbon.policy.mgt.core.PolicyManagerService");
    };

    publicMethods.insertAppPermissions = function (userModule, type) {
        // Below are the 2 types of users:- Normal users and Admins
        userModule.addPermissions([{key: "emm-admin", name: "Device Management Admin"}], "device-mgt", type);
        userModule.addPermissions([{key: "user", name: "Device Management User"}], "device-mgt", type);

        // adding permission definitions for device-mgt/admin
        userModule.addPermissions([{key: "dashboard", name: "Dashboard"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "dashboard/view", name: "View Dashboard"}], "device-mgt/emm-admin", type);

        userModule.addPermissions([{key: "devices", name: "Devices"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "devices/list", name: "List All Devices"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "devices/operation", name: "Perform Operation on Any Device"}],
                                         "device-mgt/emm-admin", type);

        userModule.addPermissions([{key: "users", name: "Users"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "users/add", name: "Add New Users"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "users/invite", name: "Invite Users"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "users/list", name: "List Users"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "users/remove", name: "Remove Users"}], "device-mgt/emm-admin", type);

        userModule.addPermissions([{key: "roles", name: "Roles"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "roles/add", name: "Add New Roles"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "roles/invite", name: "Invite Roles"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "roles/list", name: "List Roles"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "roles/remove", name: "Remove Roles"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "roles/permission", name: "Update Role Permission"}], "device-mgt/emm-admin", type);

        userModule.addPermissions([{key: "policies", name: "Policy"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "policies/add", name: "Add Policy"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "policies/list", name: "List Policy"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "policies/edit", name: "Edit Policy"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "policies/remove", name: "Remove Policy"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "policies/priority", name: "Policy Priority"}], "device-mgt/emm-admin", type);

        // adding permission definitions for device-mgt/user
        userModule.addPermissions([{key: "devices", name: "Devices"}], "device-mgt/user", type);
        userModule.addPermissions([{key: "devices/list", name: "List Individual Devices"}], "device-mgt/user", type);
        userModule.addPermissions([{key: "devices/operation", name: "Perform Operation on an Individual Device"}],
                                         "device-mgt/user", type);

        userModule.addPermissions([{key: "platform-configs", name: "Platform Configurations"}], "device-mgt/emm-admin", type);
        userModule.addPermissions([{key: "platform-configs/view", name: "View Configurations"}], "device-mgt/emm-admin", type);
    };

    return publicMethods;
}();

<|endoftext|>


<commit_before>define([
    "./../gameobject/gameobject",
    "./../gameobject/controls",
    "./../world/tile"
], function plugin(GameObject, Controls, Tile) {
    var DebugLayer = cop.create("DebugLayer")
        .refineClass(GameObject, {
            draw: function(renderer) {
                cop.proceed(renderer);
                renderer.drawLine(this.position, this.position.add(this.velocity), "red", 1, 3);
            }
        })
        .refineClass(Controls.CPU, {
            getTargetTiles: function() {
                var tiles = cop.proceed();

                tiles.each(function(tile) {
                    tile.marked = tile.canFlyThrough() ? this.color : "red";
                }, this);

                return tiles;
            }
        })
        .refineClass(Tile, {
            draw: function(renderer, x, y, size) {
                cop.proceed(renderer, x, y, size);
                if(this.marked) {
                    var min = new Vector2(x, y).mulVector(size);
                    renderer.drawRectangle(
                        min.add(size.mulFloat(0.5)),
                        25,
                        this.marked,
                        1
                    );
                }
                this.marked = false;
            }
        });

    return DebugLayer;
});
<commit_msg>no opacity set in primitive operations<commit_after>define([
    "./../gameobject/gameobject",
    "./../gameobject/controls",
    "./../world/tile"
], function plugin(GameObject, Controls, Tile) {
    var DebugLayer = cop.create("DebugLayer")
        .refineClass(GameObject, {
            draw: function(renderer) {
                cop.proceed(renderer);
                renderer.drawLine(this.position, this.position.add(this.velocity), "red", 1, 3);
            }
        })
        .refineClass(Controls.CPU, {
            getTargetTiles: function() {
                var tiles = cop.proceed();

                tiles.each(function(tile) {
                    tile.marked = tile.canFlyThrough() ? this.color : "red";
                }, this);

                return tiles;
            }
        })
        .refineClass(Tile, {
            draw: function(renderer, x, y, size) {
                cop.proceed(renderer, x, y, size);
                if(this.marked) {
                    var min = new Vector2(x, y).mulVector(size);
                    renderer.drawRectangle(
                        min.add(size.mulFloat(0.5)),
                        25,
                        this.marked
                    );
                }
                this.marked = false;
            }
        });

    return DebugLayer;
});
<|endoftext|>


<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var exec = require('cordova/exec');

exports.getInfo = function(callback) {
  exec(callback, callback, 'ChromeSystemCPU', 'getInfo', []);
};<commit_msg>Fixed newline at end of file<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var exec = require('cordova/exec');

exports.getInfo = function(callback) {
  exec(callback, callback, 'ChromeSystemCPU', 'getInfo', []);
};
<|endoftext|>


<commit_before>// jshint ignore: start

/*

a = canvases
b = body
s = canvas size

T = tick

X, Y, Z, and _ are temporary

*/

document.documentElement.style.cssText = 'width:100%;height:100%;font-weight:100;display:table;background:#333;font-family:"Helvetica Neue",sans-serif';
b.style.cssText = 'display:table-cell;vertical-align:middle;text-align:center';

a = 'second minute hour day week month year'.split(' ').map(function(unit, index) {

  _ = document.createElement('canvas');
  s = _.width = _.height = innerWidth / 7;

  _.m = [1000, 60000, 3600000, 86400000, 604800000, 2629800000, 31557600000][index];

  _.e = function() {
    Z = new Date;
    switch (unit) {
      case 'year':
        Z.setMonth(0);
      case 'month':
        Z.setDate(1);
      case 'week':
      case 'day':
        Z.setHours(0);
      case 'hour':
        Z.setMinutes(0);
      case 'minute':
        Z.setSeconds(0);
      case 'second':
        Z.setMilliseconds(0);
    }
    if (unit === 'week') {
      Z.setDate(Z.getDate() - Z.getDay());
    }
    Z.setTime(Z.getTime() + this.m - 1);
    return Z;
  };

  _.c = _.getContext('2d');
  _.c.lineWidth = s * 0.01;

  (Y = document.createElement('div')).innerHTML = unit;
  (X = document.createElement('div')).appendChild(_);
  X.style.cssText = 'display:inline-block;color:' + (_.c.fillStyle = _.c.strokeStyle = '#fa8072 #faad72 #fada72 #acda72 #87ceeb #87aceb #a4b7eb'.split(' ')[index]) + ';font-size:' + (s / 8) + 'px';
  (b.appendChild(X)).appendChild(Y);

  return _;

});

(function T() {

  a.forEach(function(canvas) {

    canvas.c.clearRect(0, 0, s, s);

    canvas.c.beginPath();
    canvas.c.moveTo(s / 2, s / 2);
    canvas.c.arc(s / 2, s / 2, s * 0.45, 0, 2 * Math.PI * ((canvas.e() - new Date) / canvas.m));
    canvas.c.fill();

    canvas.c.beginPath();
    canvas.c.moveTo(s / 2, s / 2);
    canvas.c.arc(s / 2, s / 2, s * 0.45, 0, 2 * Math.PI);
    canvas.c.stroke();

  });

  requestAnimationFrame(T);

})();
<commit_msg>add copious comments<commit_after>// jshint ignore: start

/*

a = canvases
b = body
s = canvas size

T = tick

X, Y, Z, and _ are temporary

*/

// Style <html> and <body>.

document.documentElement.style.cssText = 'width:100%;height:100%;font-weight:100;display:table;background:#333;font-family:"Helvetica Neue",sans-serif';
b.style.cssText = 'display:table-cell;vertical-align:middle;text-align:center';

// Take an array of intervals ('second', 'minute', etc) and turn them into an array of <canvas>es.

a = 'second minute hour day week month year'.split(' ').map(function(unit, index) {

  // Create the canvas and set some properties.
  _ = document.createElement('canvas');
  s = _.width = _.height = innerWidth / 7;  // Also sneak in a definition of the canvas size.

  // .m represents the number of milliseconds for each interval.
  _.m = [1000, 60000, 3600000, 86400000, 604800000, 2629800000, 31557600000][index];

  // .e() returns "end of {{interval}}". For example, if it's June 6 and the interval is 'month',
  // .e() will return July 1. This logic is stolen from Moment.js.
  _.e = function() {
    Z = new Date;
    switch (unit) {
      case 'year':
        Z.setMonth(0);
      case 'month':
        Z.setDate(1);
      case 'week':
      case 'day':
        Z.setHours(0);
      case 'hour':
        Z.setMinutes(0);
      case 'minute':
        Z.setSeconds(0);
      case 'second':
        Z.setMilliseconds(0);
    }
    if (unit === 'week') {
      Z.setDate(Z.getDate() - Z.getDay());
    }
    Z.setTime(Z.getTime() + this.m - 1);
    return Z;
  };

  // .c represents the context.
  _.c = _.getContext('2d');
  _.c.lineWidth = s * 0.01;

  // Create a container <div> and a <div> for the times. There's some trickery here
  // to ensure shorter declarations.
  (Y = document.createElement('div')).innerHTML = unit;
  (X = document.createElement('div')).appendChild(_);
  X.style.cssText = 'display:inline-block;color:' + (_.c.fillStyle = _.c.strokeStyle = '#fa8072 #faad72 #fada72 #acda72 #87ceeb #87aceb #a4b7eb'.split(' ')[index]) + ';font-size:' + (s / 8) + 'px';

  // Add the container to the body and the text to the container. There's some more
  // trickery here; appendChild returns the inserted element, which we then use.
  (b.appendChild(X)).appendChild(Y);

  // When done, return the canvas to the mapper.
  return _;

});

// T() is called once per frame.

(function T() {

  // For each <canvas>...

  a.forEach(function(canvas) {

    // Clear the canvas.
    canvas.c.clearRect(0, 0, s, s);

    // Draw the pie chart.
    // The bulk of the work is in the calculation of the angle (see the call to .arc()). In
    // pseudocode, the calculation for the hour interval might be:
    // ( (end_of_hour - now) / 3600000 ) * 2π
    canvas.c.beginPath();
    canvas.c.moveTo(s / 2, s / 2);
    canvas.c.arc(s / 2, s / 2, s * 0.45, 0, 2 * Math.PI * ((canvas.e() - new Date) / canvas.m));
    canvas.c.fill();

    // Draw the border of the pie chart.
    canvas.c.beginPath();
    canvas.c.moveTo(s / 2, s / 2);
    canvas.c.arc(s / 2, s / 2, s * 0.45, 0, 2 * Math.PI);
    canvas.c.stroke();

  });

  // Tick again!
  requestAnimationFrame(T);

})();
<|endoftext|>


<commit_before>"use strict";

var assert = require('assert');

var smush2 = function(a,b) {
  if (b.indexOf(a) === 0) {
    return b;
  }

  return a[0] + smush2(a.substr(1), b);
};

var smush = function() {
  if (arguments.length === 2) {
    var resultA = smush2(arguments[0], arguments[1]);
    var resultB = smush2(arguments[1], arguments[0]);

    return resultA.length > resultB.length ? resultB : resultA;
  }
};

describe('word smush', function() {
  describe('smush two works', function() {
    it('should concatenate words with no overlaps', function() {
      assert.equal("catdog", smush2("cat", "dog"));
    });

    it('should skip adjacent characters', function() {
      assert.equal('find', smush2('fin', 'ind'));
    });
  });

  describe('minimal solution', function() {
    it('should find the minimal solution for two words', function() {
      assert.equal('boing', smush('ing', 'boi'));
    });
  });
});<commit_msg>refactor our a method<commit_after>"use strict";

var assert = require('assert');

var smush2 = function(a,b) {
  if (b.indexOf(a) === 0) {
    return b;
  }

  return a[0] + smush2(a.substr(1), b);
};

var best = function(x,y) {
  return x.length > y.length ? y : x;
};

var smush = function() {
  if (arguments.length === 2) {
    var resultA = smush2(arguments[0], arguments[1]);
    var resultB = smush2(arguments[1], arguments[0]);

    return best(resultA, resultB);
  }
};

describe('word smush', function() {
  describe('smush two works', function() {
    it('should concatenate words with no overlaps', function() {
      assert.equal("catdog", smush2("cat", "dog"));
    });

    it('should skip adjacent characters', function() {
      assert.equal('find', smush2('fin', 'ind'));
    });
  });

  describe('minimal solution', function() {
    it('should find the minimal solution for two words', function() {
      assert.equal('boing', smush('ing', 'boi'));
    });
  });
});<|endoftext|>


<commit_before>import React, {PropTypes} from 'react';
import _ from 'lodash';
import {Link} from 'react-router';

const AlertsTable = React.createClass({
  propTypes: {
    alerts: PropTypes.arrayOf(PropTypes.shape({
      name: PropTypes.string,
      time: PropTypes.string,
      value: PropTypes.string,
      host: PropTypes.string,
      level: PropTypes.string,
    })),
    source: PropTypes.shape({
      id: PropTypes.string.isRequired,
      name: PropTypes.string.isRequired,
    }).isRequired,
  },

  getInitialState() {
    return {
      searchTerm: '',
      filteredAlerts: this.props.alerts,
      sortDirection: null,
      sortKey: null,
    };
  },

  componentWillReceiveProps(newProps) {
    this.filterAlerts(newProps.alerts, this.state.searchTerm);
  },

  filterAlerts(allAlerts, searchTerm) {
    const alerts = allAlerts.filter((h) => {
      return h.name.toLowerCase().search(searchTerm.toLowerCase()) !== -1 ||
              h.host.toLowerCase().search(searchTerm.toLowerCase()) !== -1 ||
              h.level.toLowerCase().search(searchTerm.toLowerCase()) !== -1;
    });
    this.setState({searchTerm, filteredAlerts: alerts});
  },

  changeSort(key) {
    // if we're using the key, reverse order; otherwise, set it with ascending
    if (this.state.sortKey === key) {
      const reverseDirection = (this.state.sortDirection === 'asc' ? 'desc' : 'asc');
      this.setState({sortDirection: reverseDirection});
    } else {
      this.setState({sortKey: key, sortDirection: 'asc'});
    }
  },

  sort(alerts, key, direction) {
    switch (direction) {
      case 'asc':
        return _.sortBy(alerts, (e) => e[key]);
      case 'desc':
        return _.sortBy(alerts, (e) => e[key]).reverse();
      default:
        return alerts;
    }
  },

  render() {
    const {id} = this.props.source;
    const alerts = this.sort(this.state.filteredAlerts, this.state.sortKey, this.state.sortDirection);
    return (

{this.props.alerts.length} Alerts

          <SearchBar onSearch={_.wrap(this.props.alerts, this.filterAlerts)} />

                 this.changeSort('name')} className="sortable-header">Name
                 this.changeSort('level')} className="sortable-header">Level
                 this.changeSort('time')} className="sortable-header">Time
                 this.changeSort('host')} className="sortable-header">Host
                 this.changeSort('value')} className="sortable-header">Value

              {
                alerts.map(({name, time, value, host, level}) => {
                  return (
                    <tr key={`${name}-${time}-${host}-${value}`}>
                      {name}
                      <td className={`monotype alert-level-${level.toLowerCase()}`}>{level}
                      {(new Date(Number(time)).toISOString())}

                        <Link to={`/sources/${id}/hosts/${host}`}>
                          {host}
                        </Link>

                      {value}

                  );
                })
              }

    );
  },
});

const SearchBar = React.createClass({
  propTypes: {
    onSearch: PropTypes.func.isRequired,
  },

  handleChange() {
    this.props.onSearch(this.refs.searchInput.value);
  },

  render() {
    return (

        <input
          type="text"
          className="form-control"
          placeholder="Filter Alerts by Name..."
          ref="searchInput"
          onChange={this.handleChange}
        />

    );
  },
});

export default AlertsTable;
<commit_msg>Fix filtering in alerts table<commit_after>import React, {PropTypes} from 'react';
import _ from 'lodash';
import {Link} from 'react-router';

const AlertsTable = React.createClass({
  propTypes: {
    alerts: PropTypes.arrayOf(PropTypes.shape({
      name: PropTypes.string,
      time: PropTypes.string,
      value: PropTypes.string,
      host: PropTypes.string,
      level: PropTypes.string,
    })),
    source: PropTypes.shape({
      id: PropTypes.string.isRequired,
      name: PropTypes.string.isRequired,
    }).isRequired,
  },

  getInitialState() {
    return {
      searchTerm: '',
      filteredAlerts: this.props.alerts,
      sortDirection: null,
      sortKey: null,
    };
  },

  componentWillReceiveProps(newProps) {
    this.filterAlerts(newProps.alerts, this.state.searchTerm);
  },

  filterAlerts(searchTerm) {
    const filteredAlerts = this.props.alerts.filter((h) => {
      if (h.host === null || h.name === null || h.level === null) {
        return false;
      }

      return h.name.toLowerCase().search((searchTerm).toLowerCase()) !== -1 ||
              h.host.toLowerCase().search((searchTerm).toLowerCase()) !== -1 ||
              h.level.toLowerCase().search((searchTerm).toLowerCase()) !== -1;
    });
    this.setState({searchTerm, filteredAlerts});
  },

  changeSort(key) {
    // if we're using the key, reverse order; otherwise, set it with ascending
    if (this.state.sortKey === key) {
      const reverseDirection = (this.state.sortDirection === 'asc' ? 'desc' : 'asc');
      this.setState({sortDirection: reverseDirection});
    } else {
      this.setState({sortKey: key, sortDirection: 'asc'});
    }
  },

  sort(alerts, key, direction) {
    switch (direction) {
      case 'asc':
        return _.sortBy(alerts, (e) => e[key]);
      case 'desc':
        return _.sortBy(alerts, (e) => e[key]).reverse();
      default:
        return alerts;
    }
  },

  render() {
    const {id} = this.props.source;
    const alerts = this.sort(this.state.filteredAlerts, this.state.sortKey, this.state.sortDirection);
    return (

{this.props.alerts.length} Alerts

          <SearchBar onSearch={this.filterAlerts} />

                 this.changeSort('name')} className="sortable-header">Name
                 this.changeSort('level')} className="sortable-header">Level
                 this.changeSort('time')} className="sortable-header">Time
                 this.changeSort('host')} className="sortable-header">Host
                 this.changeSort('value')} className="sortable-header">Value

              {
                alerts.map(({name, time, value, host, level}) => {
                  return (
                    <tr key={`${name}-${time}-${host}-${value}`}>
                      {name}
                      <td className={`monotype alert-level-${level.toLowerCase()}`}>{level}
                      {(new Date(Number(time)).toISOString())}

                        <Link to={`/sources/${id}/hosts/${host}`}>
                          {host}
                        </Link>

                      {value}

                  );
                })
              }

    );
  },
});

const SearchBar = React.createClass({
  propTypes: {
    onSearch: PropTypes.func.isRequired,
  },

  handleChange(e) {
    this.props.onSearch(e.target.value);
  },

  render() {
    return (

        <input
          type="text"
          className="form-control"
          placeholder="Filter Alerts by Name..."
          onChange={this.handleChange}
        />

    );
  },
});

export default AlertsTable;
<|endoftext|>


<commit_before>window.onload = function() {
	var canvas = document.getElementById('canvas');
	var ctx = canvas.getContext('2d');
	var canvasWidth = canvas.width;
	var canvasHeight = canvas.height;
	var game_loop;
	var cellSize = 40; //determines cell size. cell is always a square.
	var boardSize = 8; //determines board size. at the moment the board is always square.
	//var board = [];
	var board = [
	[1, 2, 0, 1, 2, 2, 2, 0],
	[2, 0, 0, 2, 1, 2, 2, 0],
	[1, 0, 1, 0, 2, 2, 1, 2],
	[1, 2, 1, 1, 0, 0, 2, 1],
	[1, 2, 2, 1, 2, 2, 0, 0],
	[0, 0, 1, 2, 2, 2, 1, 0],
	[1, 2, 0, 0, 2, 2, 2, 0],
	[0, 1, 0, 0, 1, 1, 2, 2]
	];
	var selectedCells = [];
	var score;

	function generateJewel() {
		return Math.floor(Math.random() * 3);
	}

	/* Start Game */
	function init() {
		//initialize board with randomly generated jewels
		/*for(var y = 0; y < boardSize; ++y) {
			var temp = [];
			for(var x = 0; x < boardSize; ++x) {
				temp.push(generateJewel());
			}
			board.push(temp);
		}*/

		console.log(board);
		score = 0;
		if(typeof game_loop !== 'undefined') clearInterval(game_loop);
		game_loop = setInterval(draw, 60);
	}

	init();

	function clearMatchesXAxis(startX, startY, length, boardClearMarked) {
		//console.log(startX, startY, length);
		for(var i = startX; i < startX + length; ++i) {
			boardClearMarked[startY][i] = 1;
		}
		return boardClearMarked;
	}

	function clearMatchesYAxis(startX, startY, length, boardClearMarked) {
		//console.log(startX, startY, length);
		for(var i = startY; i < startY + length; ++i) {
			boardClearMarked[i][startX] = 1;
		}
		return boardClearMarked;
	}

	function match() {
		var count = 1;
		var prevVal = -1;
		var matchFound = 0;

		//initialize boardClearMarked which tells game which tiles should be deleted
		var boardClearMarked = [];
		for(var y = 0; y < boardSize; ++y) {
			var temp = [];
			for(var x = 0; x < boardSize; ++x) {
				temp.push(0);
			}
			boardClearMarked.push(temp);
		}

		//check matches in each row on x-axis
		for(var y = 0; y < boardSize; ++y) {
			for(var x = 0; x < boardSize; ++x) {
				var currVal = board[y][x];
				if((currVal === prevVal) && (currVal != 3)) {
					++count;
				} else {
					if(count >= 3) {
						//console.log('x:' + x + ', ' + 'y:' + x + ', ' + 'count:' + count);
						matchFound = 1;
						boardClearMarked = clearMatchesXAxis(x - count, y, count, boardClearMarked);
					}
					count = 1;
				}
				prevVal = currVal;
			}
			if(count >= 3) {
				//console.log('x:' + i + ', ' + 'y:' + x + ', ' + 'count:' + count);
				matchFound = 1;
				boardClearMarked = clearMatchesXAxis(boardSize - count, y, count, boardClearMarked);
			}
			count = 1;
			prevVal = -1;
		}

		//check matches in each row on y-axis
		for(var x = 0; x < boardSize; ++x) {
			for(var y = 0; y < boardSize; ++y) {
				var currVal = board[y][x];
				if((currVal === prevVal) && (currVal != 3)) {
					++count;
				} else {
					if(count >= 3) {
						matchFound = 1;
						boardClearMarked = clearMatchesYAxis(x, y - count, count, boardClearMarked);
					}
					count = 1;
				}
				prevVal = currVal;
			}
			if(count >= 3) {
				matchFound = 1;
				boardClearMarked = clearMatchesYAxis(x, boardSize - count, count, boardClearMarked);
			}
			count = 1;
			prevVal = -1;
		}

		//delete matched tilesets from board
		for(var y = 0; y < boardSize; ++y) {
			for(var x = 0; x < boardSize; ++x) {
				if(boardClearMarked[y][x] === 1) {
					board[y][x] = 3;
				}
			}
		}

		return matchFound;
	}

	function jewelSlideDown() {
		for(var x = 0; x < boardSize; ++x) {
			var emptyCells = [];
			for(var y = boardSize - 1; y >= 0; --y) {
				if(board[y][x] === 3) {
					emptyCells.unshift({'x': x, 'y': y});
				} else if(emptyCells.length) {
					var deepestEmptyCell = emptyCells.pop();
					board[deepestEmptyCell.y][deepestEmptyCell.x] = board[y][x];
					board[y][x] = 3;
					emptyCells.unshift({'x': x, 'y': y});
				}
			}
			emptyCells = [];
		}
	}

	function drawJewel(x, y, val) {
		if(val === 0) {
			ctx.fillStyle = '#ff0000';
		} else if(val === 1) {
			ctx.fillStyle = '#00ff00';
		} else if(val === 2){
			ctx.fillStyle = '#0000ff';
		} else if(val === 4) {
			ctx.fillStyle = '#fff';
		} else {
			ctx.fillStyle = '#000';
		}
		ctx.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);
		ctx.strokeStyle = '#000';
		ctx.strokeRect(x * cellSize, y * cellSize, cellSize, cellSize);
	}

	function fillGaps() {
		for(var y = 0; y < board.length; ++y) {
			for(var x = 0; x < board.length; ++x) {
				if(board[y][x] === 3) {
					board[y][x] = generateJewel();
				}
			}
		}
	}

	function draw() {
		//draw the background to clear previous frame
		ctx.fillStyle = '#fff';
		ctx.fillRect(0, 0, canvasWidth, canvasHeight);

		for(var y = 0; y < boardSize; ++y) {
			for(var x = 0; x < boardSize; ++x) {
				drawJewel(x, y, board[y][x]);
			}
		}

		var score_text = 'Score: ' + score;
		ctx.fillStyle = '#000';
		ctx.fillText(score_text, canvasWidth - 155, 15);
	}

	var matchFound = -1;
	while(matchFound = match()){
		jewelSlideDown();
		fillGaps();
	}

	/* Input */
	window.onmousedown = function(evt) {
		var key = evt.which;
		//console.log(key);
		if(key === 1) {
			var x = evt.pageX - canvas.offsetLeft;
			var y = evt.pageY - canvas.offsetTop;
			var mouseCoord = { 'x': x, 'y': y };

			if((mouseCoord.x >= 0) && (mouseCoord.x <= 320) && (mouseCoord.y >= 0) && (mouseCoord.y <= 320)) {
				var clickedCell = {};

				//console.log(mouseCoord);
				if((mouseCoord.x / 40) <= 1) {
					clickedCell.x = 0;
				} else if((mouseCoord.x / 40) <= 2) {
					clickedCell.x = 1;
				} else if((mouseCoord.x / 40) <= 3) {
					clickedCell.x = 2;
				} else if((mouseCoord.x / 40) <= 4) {
					clickedCell.x = 3;
				} else if((mouseCoord.x / 40) <= 5) {
					clickedCell.x = 4;
				} else if((mouseCoord.x / 40) <= 6) {
					clickedCell.x = 5;
				} else if((mouseCoord.x / 40) <= 7) {
					clickedCell.x = 6;
				} else if((mouseCoord.x / 40) <= 8) {
					clickedCell.x = 7;
				}

				if((mouseCoord.y / 40) <= 1) {
					clickedCell.y = 0;
				} else if((mouseCoord.y / 40) <= 2) {
					clickedCell.y = 1;
				} else if((mouseCoord.y / 40) <= 3) {
					clickedCell.y = 2;
				} else if((mouseCoord.y / 40) <= 4) {
					clickedCell.y = 3;
				} else if((mouseCoord.y / 40) <= 5) {
					clickedCell.y = 4;
				} else if((mouseCoord.y / 40) <= 6) {
					clickedCell.y = 5;
				} else if((mouseCoord.y / 40) <= 7) {
					clickedCell.y = 6;
				} else if((mouseCoord.y / 40) <= 8) {
					clickedCell.y = 7;
				}

				if(selectedCells.length === 0) {
					selectedCells.push(clickedCell);
				} else if(selectedCells.length === 1) {
					selectedCells.push(clickedCell);
					if(((selectedCells[1].x >= (selectedCells[0].x - 1)) && (selectedCells[1].x <= (selectedCells[0].x + 1))) && ((selectedCells[1].y >= (selectedCells[0].y - 1)) && (selectedCells[1].y <= (selectedCells[0].y + 1)))) {
						var temp = board[selectedCells[0].y][selectedCells[0].x];
						board[selectedCells[0].y][selectedCells[0].x] = board[selectedCells[1].y][selectedCells[1].x];
						board[selectedCells[1].y][selectedCells[1].x] = temp;
					}
					selectedCells = [];
				}
			}
		}
	}
};<commit_msg>Got click highlighting working<commit_after>window.onload = function() {
	var canvas = document.getElementById('canvas');
	var ctx = canvas.getContext('2d');
	var canvasWidth = canvas.width;
	var canvasHeight = canvas.height;
	var game_loop;
	var cellSize = 40; //determines cell size. cell is always a square.
	var boardSize = 8; //determines board size. at the moment the board is always square.
	//var board = [];
	var board = [
	[1, 2, 0, 1, 2, 2, 2, 0],
	[2, 0, 0, 2, 1, 2, 2, 0],
	[1, 0, 1, 0, 2, 2, 1, 2],
	[1, 2, 1, 1, 0, 0, 2, 1],
	[1, 2, 2, 1, 2, 2, 0, 0],
	[0, 0, 1, 2, 2, 2, 1, 0],
	[1, 2, 0, 0, 2, 2, 2, 0],
	[0, 1, 0, 0, 1, 1, 2, 2]
	];
	var selectedCells = [];
	var score;

	function generateJewel() {
		return Math.floor(Math.random() * 3);
	}

	/* Start Game */
	function init() {
		//initialize board with randomly generated jewels
		/*for(var y = 0; y < boardSize; ++y) {
			var temp = [];
			for(var x = 0; x < boardSize; ++x) {
				temp.push(generateJewel());
			}
			board.push(temp);
		}*/

		console.log(board);
		score = 0;
		if(typeof game_loop !== 'undefined') clearInterval(game_loop);
		game_loop = setInterval(draw, 60);
	}

	init();

	function clearMatchesXAxis(startX, startY, length, boardClearMarked) {
		//console.log(startX, startY, length);
		for(var i = startX; i < startX + length; ++i) {
			boardClearMarked[startY][i] = 1;
		}
		return boardClearMarked;
	}

	function clearMatchesYAxis(startX, startY, length, boardClearMarked) {
		//console.log(startX, startY, length);
		for(var i = startY; i < startY + length; ++i) {
			boardClearMarked[i][startX] = 1;
		}
		return boardClearMarked;
	}

	function match() {
		var count = 1;
		var prevVal = -1;
		var matchFound = 0;

		//initialize boardClearMarked which tells game which tiles should be deleted
		var boardClearMarked = [];
		for(var y = 0; y < boardSize; ++y) {
			var temp = [];
			for(var x = 0; x < boardSize; ++x) {
				temp.push(0);
			}
			boardClearMarked.push(temp);
		}

		//check matches in each row on x-axis
		for(var y = 0; y < boardSize; ++y) {
			for(var x = 0; x < boardSize; ++x) {
				var currVal = board[y][x];
				if((currVal === prevVal) && (currVal != 3)) {
					++count;
				} else {
					if(count >= 3) {
						//console.log('x:' + x + ', ' + 'y:' + x + ', ' + 'count:' + count);
						matchFound = 1;
						boardClearMarked = clearMatchesXAxis(x - count, y, count, boardClearMarked);
					}
					count = 1;
				}
				prevVal = currVal;
			}
			if(count >= 3) {
				//console.log('x:' + i + ', ' + 'y:' + x + ', ' + 'count:' + count);
				matchFound = 1;
				boardClearMarked = clearMatchesXAxis(boardSize - count, y, count, boardClearMarked);
			}
			count = 1;
			prevVal = -1;
		}

		//check matches in each row on y-axis
		for(var x = 0; x < boardSize; ++x) {
			for(var y = 0; y < boardSize; ++y) {
				var currVal = board[y][x];
				if((currVal === prevVal) && (currVal != 3)) {
					++count;
				} else {
					if(count >= 3) {
						matchFound = 1;
						boardClearMarked = clearMatchesYAxis(x, y - count, count, boardClearMarked);
					}
					count = 1;
				}
				prevVal = currVal;
			}
			if(count >= 3) {
				matchFound = 1;
				boardClearMarked = clearMatchesYAxis(x, boardSize - count, count, boardClearMarked);
			}
			count = 1;
			prevVal = -1;
		}

		//delete matched tilesets from board
		for(var y = 0; y < boardSize; ++y) {
			for(var x = 0; x < boardSize; ++x) {
				if(boardClearMarked[y][x] === 1) {
					board[y][x] = 3;
				}
			}
		}

		return matchFound;
	}

	function jewelSlideDown() {
		for(var x = 0; x < boardSize; ++x) {
			var emptyCells = [];
			for(var y = boardSize - 1; y >= 0; --y) {
				if(board[y][x] === 3) {
					emptyCells.unshift({'x': x, 'y': y});
				} else if(emptyCells.length) {
					var deepestEmptyCell = emptyCells.pop();
					board[deepestEmptyCell.y][deepestEmptyCell.x] = board[y][x];
					board[y][x] = 3;
					emptyCells.unshift({'x': x, 'y': y});
				}
			}
			emptyCells = [];
		}
	}

	function drawJewel(x, y, val, highlight) {
		if(val === 0) {
			ctx.fillStyle = '#ff0000';
		} else if(val === 1) {
			ctx.fillStyle = '#00ff00';
		} else if(val === 2){
			ctx.fillStyle = '#0000ff';
		} else if(val === 4) {
			ctx.fillStyle = '#fff';
		} else {
			ctx.fillStyle = '#000';
		}
		ctx.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);
		if(highlight) {
			ctx.strokeStyle = '#ff69b4';
		} else {
			ctx.strokeStyle = '#000';
		}
		ctx.strokeRect(x * cellSize, y * cellSize, cellSize, cellSize);
	}

	function fillGaps() {
		for(var y = 0; y < board.length; ++y) {
			for(var x = 0; x < board.length; ++x) {
				if(board[y][x] === 3) {
					board[y][x] = generateJewel();
				}
			}
		}
	}

	function draw() {
		//draw the background to clear previous frame
		ctx.fillStyle = '#fff';
		ctx.fillRect(0, 0, canvasWidth, canvasHeight);

		for(var y = 0; y < boardSize; ++y) {
			for(var x = 0; x < boardSize; ++x) {
				drawJewel(x, y, board[y][x], false);
			}
		}

		if(selectedCells.length != 0) {
			drawJewel(selectedCells[0].x, selectedCells[0].y, board[selectedCells[0].y][selectedCells[0].x], true);
		}

		var score_text = 'Score: ' + score;
		ctx.fillStyle = '#000';
		ctx.fillText(score_text, canvasWidth - 155, 15);
	}

	var matchFound = -1;
	/*while(matchFound = match()){
		jewelSlideDown();
		fillGaps();
	}*/

	/* Input */
	window.onmousedown = function(evt) {
		var key = evt.which;
		//console.log(key);
		if(key === 1) {
			var x = evt.pageX - canvas.offsetLeft;
			var y = evt.pageY - canvas.offsetTop;
			var mouseCoord = { 'x': x, 'y': y };

			if((mouseCoord.x >= 0) && (mouseCoord.x <= 320) && (mouseCoord.y >= 0) && (mouseCoord.y <= 320)) {
				var clickedCell = {};

				//console.log(mouseCoord);
				if((mouseCoord.x / 40) <= 1) {
					clickedCell.x = 0;
				} else if((mouseCoord.x / 40) <= 2) {
					clickedCell.x = 1;
				} else if((mouseCoord.x / 40) <= 3) {
					clickedCell.x = 2;
				} else if((mouseCoord.x / 40) <= 4) {
					clickedCell.x = 3;
				} else if((mouseCoord.x / 40) <= 5) {
					clickedCell.x = 4;
				} else if((mouseCoord.x / 40) <= 6) {
					clickedCell.x = 5;
				} else if((mouseCoord.x / 40) <= 7) {
					clickedCell.x = 6;
				} else if((mouseCoord.x / 40) <= 8) {
					clickedCell.x = 7;
				}

				if((mouseCoord.y / 40) <= 1) {
					clickedCell.y = 0;
				} else if((mouseCoord.y / 40) <= 2) {
					clickedCell.y = 1;
				} else if((mouseCoord.y / 40) <= 3) {
					clickedCell.y = 2;
				} else if((mouseCoord.y / 40) <= 4) {
					clickedCell.y = 3;
				} else if((mouseCoord.y / 40) <= 5) {
					clickedCell.y = 4;
				} else if((mouseCoord.y / 40) <= 6) {
					clickedCell.y = 5;
				} else if((mouseCoord.y / 40) <= 7) {
					clickedCell.y = 6;
				} else if((mouseCoord.y / 40) <= 8) {
					clickedCell.y = 7;
				}

				if(selectedCells.length === 0) {
					selectedCells.push(clickedCell);
				} else if(selectedCells.length === 1) {
					selectedCells.push(clickedCell);
					drawJewel(selectedCells[1].x, selectedCells[1].y, board[selectedCells[1].y][selectedCells[1].x], true);
					/*var firstCell = selectedCells[0];
					var secondCell = selectedCells[1];
					if(secondCell.y === firstCell.y) {
						if(secondCell.x === firstCell.x) {

						}
					}

					if(((selectedCells[1].x >= (selectedCells[0].x - 1)) && (selectedCells[1].x <= (selectedCells[0].x + 1))) && ((selectedCells[1].y >= (selectedCells[0].y - 1)) && (selectedCells[1].y <= (selectedCells[0].y + 1)))) {
						if(selectedCells[1].x >= 1) {
							var temp = board[selectedCells[0].y][selectedCells[0].x];
							board[selectedCells[0].y][selectedCells[0].x] = board[selectedCells[1].y][selectedCells[1].x];
							board[selectedCells[1].y][selectedCells[1].x] = temp;
						}
					}*/
					selectedCells = [];
				}
			}
		}
	}
};<|endoftext|>


<commit_before>var info      = require('../package.json');
var path      = require('path');

var clientAppPath = path.join(__dirname, '../');

var devRelativeOutput     = '/assets/';
var prodRelativeOutput    = '/assets/';

var devOutput     = path.join(__dirname, '../../app/assets/javascripts');
var prodOutput    = path.join(__dirname, '../../app/assets/javascripts');

var hotPort = 8081;
var devAssetsUrl = null; //'https://cs_assets.ngrok.com' // Set to null to use localhost

module.exports = {
  title: info.title,
  author: info.author,
  version: info.versions,
  build: Date.now(),

  devRelativeOutput: devRelativeOutput,
  prodRelativeOutput: prodRelativeOutput,

  devOutput: devOutput,
  prodOutput: prodOutput,

  // Used by pageSpeed. This should be the url of your production server
  applicationUrl: 'http://www.example.com',

  // Dev urls
  devAssetsUrl: devAssetsUrl || 'http://localhost:' + hotPort,

  ports: {
    hotPort: hotPort
  },
  assets: {
    paths: {
      all: clientAppPath + 'assets/**/*',
      output: {
        dev: devOutput,
        prod: prodOutput
      }
    }
  },
  fonts: {
    paths: {
      all: [
        clientAppPath + 'fonts/**'
        // './node_modules/bootstrap-sass/assets/fonts/**',
        // './node_modules/font-awesome/fonts/**'
      ],
      output: {
        dev: devOutput,
        prod: prodOutput
      }
    }
  },
  scripts: {
    paths: {
      all: clientAppPath + 'js/**/*.js',
      entries: {
        app: clientAppPath + 'js/app.jsx',
        app_admin: clientAppPath + 'js/app_admin.jsx',
        styles: clientAppPath + 'styles/styles.js'
      },
      output: {
        dev: devOutput,
        prod: prodOutput
      },
      relativeOutput: {
        dev: devRelativeOutput,
        prod: prodRelativeOutput
      }
    }
  },
  styles: {
    autoPrefix: ['last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'],
    paths: {
      all: clientAppPath + 'styles/**/*.scss',

      output: {
        dev: devOutput,
        prod: prodOutput
      }
    },
    sourcemaps: false
  },
  html: {
    paths: {
      all: clientAppPath + 'html/**/*.html',
      ignore: clientAppPath + '!html/**/_*.html',
      output: {
        dev: devOutput,
        prod: prodOutput
      }
    }
  },
  images: {
    paths: {
      all: [clientAppPath + 'images/*', clientAppPath + 'images/**/*.jpg', clientAppPath + 'images/**/*.jpeg', clientAppPath + 'images/**/*.gif'],
      output: {
        dev: devOutput,
        prod: prodOutput
      }
    },
    compression: 3
  }
};
<commit_msg>Use localhost for assets by default.<commit_after>var info      = require('../package.json');
var path      = require('path');

var clientAppPath = path.join(__dirname, '../');

var devRelativeOutput     = '/assets/';
var prodRelativeOutput    = '/assets/';

var devOutput     = path.join(__dirname, '../../app/assets/javascripts');
var prodOutput    = path.join(__dirname, '../../app/assets/javascripts');

var hotPort = 8080;
var devAssetsUrl = null; //'https://cs_assets.ngrok.com' // Set to null to use localhost

module.exports = {
  title: info.title,
  author: info.author,
  version: info.versions,
  build: Date.now(),

  devRelativeOutput: devRelativeOutput,
  prodRelativeOutput: prodRelativeOutput,

  devOutput: devOutput,
  prodOutput: prodOutput,

  // Used by pageSpeed. This should be the url of your production server
  applicationUrl: 'http://www.example.com',

  // Dev urls
  devAssetsUrl: devAssetsUrl || 'http://localhost:' + hotPort,

  ports: {
    hotPort: hotPort
  },
  assets: {
    paths: {
      all: clientAppPath + 'assets/**/*',
      output: {
        dev: devOutput,
        prod: prodOutput
      }
    }
  },
  fonts: {
    paths: {
      all: [
        clientAppPath + 'fonts/**'
        // './node_modules/bootstrap-sass/assets/fonts/**',
        // './node_modules/font-awesome/fonts/**'
      ],
      output: {
        dev: devOutput,
        prod: prodOutput
      }
    }
  },
  scripts: {
    paths: {
      all: clientAppPath + 'js/**/*.js',
      entries: {
        app: clientAppPath + 'js/app.jsx',
        app_admin: clientAppPath + 'js/app_admin.jsx',
        styles: clientAppPath + 'styles/styles.js'
      },
      output: {
        dev: devOutput,
        prod: prodOutput
      },
      relativeOutput: {
        dev: devRelativeOutput,
        prod: prodRelativeOutput
      }
    }
  },
  styles: {
    autoPrefix: ['last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'],
    paths: {
      all: clientAppPath + 'styles/**/*.scss',

      output: {
        dev: devOutput,
        prod: prodOutput
      }
    },
    sourcemaps: false
  },
  html: {
    paths: {
      all: clientAppPath + 'html/**/*.html',
      ignore: clientAppPath + '!html/**/_*.html',
      output: {
        dev: devOutput,
        prod: prodOutput
      }
    }
  },
  images: {
    paths: {
      all: [clientAppPath + 'images/*', clientAppPath + 'images/**/*.jpg', clientAppPath + 'images/**/*.jpeg', clientAppPath + 'images/**/*.gif'],
      output: {
        dev: devOutput,
        prod: prodOutput
      }
    },
    compression: 3
  }
};
<|endoftext|>


<commit_before>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/*  bootstrap component system  */
ComponentJS.symbol("cs")
cs.bootstrap()
cs.ns("app.lib")
cs.ns("app.ui.comp")
cs.ns("app.ui.widget")
cs.debug(0)
if (cs.plugin("debugger")) {
    if (cs.debug_instrumented()) {
        cs.debug(9)
        cs.debug_window({
            enable:    true,
            natural:   true,
            autoclose: false,
            name:      "ComponentJS Tracing Proxy",
            width:     800,
            height:    800
        })
    }
}

/*  once the DOM is ready...  */
$(document).ready(function () {
    /*  we really need Google Chrome's feature set  */
    if (window.chrome === undefined) {
        /* global alert: true */
        alert("You can only view this application using Google Chrome.");
        return;
    }

    /*  load stylesheets  */
    /* global less: true */
    less.env = "production"
    less.async = true
    less.dumpLineNumbers = "mediaQuery"
    $("head > link[rel='stylesheet/less']").each(function () {
        less.sheets.push(this)
    })
    less.refresh(true)

    /*  load markup templates  */
    $.markup.load(function () {
        /*  fire up application components  */
        cs.create("/sv", app.sv)
        cs("/sv").state("prepared", function () {
            cs.create("/ui/panel", {}, app.ui.comp.panel)
            cs("/ui/panel").state(typeof document !== "undefined" ? "visible" : "prepared")
        })
    })
})
<commit_msg>Added jshint annotation for app<commit_after>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/*  bootstrap component system  */
ComponentJS.symbol("cs")
cs.bootstrap()
cs.ns("app.lib")
cs.ns("app.ui.comp")
cs.ns("app.ui.widget")
cs.debug(0)
if (cs.plugin("debugger")) {
    if (cs.debug_instrumented()) {
        cs.debug(9)
        cs.debug_window({
            enable:    true,
            natural:   true,
            autoclose: false,
            name:      "ComponentJS Tracing Proxy",
            width:     800,
            height:    800
        })
    }
}

/*  once the DOM is ready...  */
$(document).ready(function () {
    /*  we really need Google Chrome's feature set  */
    if (window.chrome === undefined) {
        /* global alert: true */
        alert("You can only view this application using Google Chrome.");
        return;
    }

    /*  load stylesheets  */
    /* global less: true */
    less.env = "production"
    less.async = true
    less.dumpLineNumbers = "mediaQuery"
    $("head > link[rel='stylesheet/less']").each(function () {
        less.sheets.push(this)
    })
    less.refresh(true)

    /*  load markup templates  */
    $.markup.load(function () {
        /*  fire up application components  */
        /* global app: true */
        cs.create("/sv", app.sv)
        cs("/sv").state("prepared", function () {
            cs.create("/ui/panel", {}, app.ui.comp.panel)
            cs("/ui/panel").state(typeof document !== "undefined" ? "visible" : "prepared")
        })
    })
})
<|endoftext|>