<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import classNames from '../../utilities/classNames'
import { noop } from '../../utilities/other'
import RouteWrapper from '../RouteWrapper'
import { standardSizeTypes, stateTypes } from '../../constants/propTypes'

export const propTypes = {
  accessibilityLabel: PropTypes.string,
  block: PropTypes.bool,
  className: PropTypes.string,
  disabled: PropTypes.bool,
  onBlur: PropTypes.func,
  onClick: PropTypes.func,
  onFocus: PropTypes.func,
  isActive: PropTypes.bool,
  outline: PropTypes.bool,
  plain: PropTypes.bool,
  primary: PropTypes.bool,
  size: standardSizeTypes,
  state: stateTypes,
  submit: PropTypes.bool,
  theme: PropTypes.string
}

const defaultProps = {
  accessibilityLabel: '',
  block: false,
  disabled: false,
  onBlur: noop,
  onClick: noop,
  onFocus: noop,
  outline: false,
  plain: false,
  primary: false,
  size: '',
  state: '',
  submit: false
}

const Button = props => {
  const {
    accessibilityLabel,
    block,
    buttonRef,
    children,
    className,
    disabled,
    isActive,
    onBlur,
    onClick,
    onFocus,
    outline,
    plain,
    primary,
    size,
    state,
    submit,
    theme,
    ...rest
  } = props

  const componentClassName = classNames(
    'c-Button',
    isActive && 'is-selected',
    block && 'c-Button--block',
    outline && 'c-Button--outline',
    plain && 'c-Button--link',
    primary && 'c-Button--primary',
    size && `c-Button--${size}`,
    state && `is-${state}`,
    theme && `c-Button--${theme}`,
    className
  )

  const type = submit ? 'submit' : 'button'

  return (
    <button
      aria-label={accessibilityLabel}
      ref={buttonRef}
      className={componentClassName}
      disabled={disabled}
      onBlur={onBlur}
      onClick={onClick}
      onFocus={onFocus}
      type={type}
      {...rest}
    >
      {children}
    </button>
  )
}

Button.propTypes = propTypes
Button.defaultProps = defaultProps

export default RouteWrapper(Button)
<commit_msg>Adjust defaultProps for Button<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import classNames from '../../utilities/classNames'
import { noop } from '../../utilities/other'
import RouteWrapper from '../RouteWrapper'
import { standardSizeTypes, stateTypes } from '../../constants/propTypes'

export const propTypes = {
  accessibilityLabel: PropTypes.string,
  block: PropTypes.bool,
  className: PropTypes.string,
  disabled: PropTypes.bool,
  onBlur: PropTypes.func,
  onClick: PropTypes.func,
  onFocus: PropTypes.func,
  isActive: PropTypes.bool,
  outline: PropTypes.bool,
  plain: PropTypes.bool,
  primary: PropTypes.bool,
  size: standardSizeTypes,
  state: stateTypes,
  submit: PropTypes.bool,
  theme: PropTypes.string
}

const defaultProps = {
  block: false,
  disabled: false,
  onBlur: noop,
  onClick: noop,
  onFocus: noop,
  outline: false,
  plain: false,
  primary: false,
  submit: false
}

const Button = props => {
  const {
    accessibilityLabel,
    block,
    buttonRef,
    children,
    className,
    disabled,
    isActive,
    onBlur,
    onClick,
    onFocus,
    outline,
    plain,
    primary,
    size,
    state,
    submit,
    theme,
    ...rest
  } = props

  const componentClassName = classNames(
    'c-Button',
    isActive && 'is-selected',
    block && 'c-Button--block',
    outline && 'c-Button--outline',
    plain && 'c-Button--link',
    primary && 'c-Button--primary',
    size && `c-Button--${size}`,
    state && `is-${state}`,
    theme && `c-Button--${theme}`,
    className
  )

  const type = submit ? 'submit' : 'button'

  return (
    <button
      aria-label={accessibilityLabel}
      ref={buttonRef}
      className={componentClassName}
      disabled={disabled}
      onBlur={onBlur}
      onClick={onClick}
      onFocus={onFocus}
      type={type}
      {...rest}
    >
      {children}
    </button>
  )
}

Button.propTypes = propTypes
Button.defaultProps = defaultProps

export default RouteWrapper(Button)
<|endoftext|>


<commit_before>
import mongoose from 'mongoose';
import autoIncrement from 'mongoose-auto-increment';

const connection = mongoose.connect('mongodb://localhost/instance1');
autoIncrement.initialize(connection);

let IncomeSchema = new mongoose.Schema({
	incomeNumber: {type:  Number},
	typeSend: {type: String},
	incomeStatus: {type: String},
	idSend: {type: Object}, //CLIENT, BUSINESS, INSURANCE, USER
	send: {type: Object},
	idUserAddress: {type: incomeStatusngoose.Schema.ObjectId, ref: "User"},
	dateIncome: {type: String, require: true},
	dateReception: {type: String, require: true},
	details: {type: String, require: true},
	observations: {type: String},
	dateCreate: {type: Date, require: true},
	userCreate: {type: String, require: true},
	dateUpdate: {type: Date, require: true},
	userUpdate: {type: String, require: true}
});

IncomeSchema.plugin(autoIncrement.plugin, { model: 'Income', field: 'incomeNumber', startAt: 1});

export default mongoose.model('Income', IncomeSchema)
<commit_msg>fixed name of mongose relation<commit_after>
import mongoose from 'mongoose';
import autoIncrement from 'mongoose-auto-increment';

const connection = mongoose.connect('mongodb://localhost/instance1');
autoIncrement.initialize(connection);

let IncomeSchema = new mongoose.Schema({
	incomeNumber: {type:  Number},
	typeSend: {type: String},
	incomeStatus: {type: String},
	idSend: {type: Object}, //CLIENT, BUSINESS, INSURANCE, USER
	send: {type: Object},
	idUserAddress: {type: mongoose.Schema.ObjectId, ref: "User"},
	dateIncome: {type: String, require: true},
	dateReception: {type: String, require: true},
	details: {type: String, require: true},
	observations: {type: String},
	dateCreate: {type: Date, require: true},
	userCreate: {type: String, require: true},
	dateUpdate: {type: Date, require: true},
	userUpdate: {type: String, require: true}
});

IncomeSchema.plugin(autoIncrement.plugin, { model: 'Income', field: 'incomeNumber', startAt: 1});

export default mongoose.model('Income', IncomeSchema)
<|endoftext|>


<commit_before>// dependencies
//
import React from 'react';
import uniqueId from 'lodash/uniqueId';
import classnames from 'classnames';

import Label from './Label';
import columns from '../helpers/columns';

/**
 * Clean a value of any non-numeric characters
 * @param  {String|Number} value The value to clean
 * @return {String}              The cleaned value
 */
const clean = (value) => `${value}`.replace(/[^0-9.-]/g, '');

/**
 * Convert a value to a fixed-decimal number
 * @param  {Number} value The number to convert
 * @param  {Number} count The number of decimal places
 * @return {String}       The formatted number
 */
const decimals = (value, count) => (value !== '' ? `${value.toFixed(count)}` : '');

/**
 * Convert a value to a currency string (2 decimal places, prefixed by "$")
 * @param  {Number} value The value to convert
 * @return {String}       The formatted value
 */
const currency = (value) => (value !== '' ? `$ ${decimals(value, 2)}` : '');

/**
 * The NumericInput component
 */
class NumericInput extends React.Component {
    constructor(props) {
        super(props);

        // generate a unique ID for the component
        //
        this.id = uniqueId('NumericInput-');

        // set the validation message from the properties or from a default
        //
        this.validationMessage = this.props.validationMessage
            || `${props.description} is required`;

        // initialize the component state
        //
        this.state = this.validate(props.value);

        // bind `this` to the event handlers
        //
        this.onBlur = this.onBlur.bind(this);
        this.onChange = this.onChange.bind(this);
        this.onFocus = this.onFocus.bind(this);
    }

    /**
     * Handle the initial mounting of the component
     */
    componentWillMount() {
        // do we have an onValidation handler? if so, call it with the current
        // validation state
        //
        if (this.props.onValidation) {
            this.props.onValidation(
                this.state.hasValidated,
                this.state.isValid,
                this.state.validationMessage
            );
        }
    }

    /**
     * Handle new props passed from the parent component
     * @param  {Object} newProps The new props
     */
    componentWillReceiveProps(newProps) {
        // validate the new value
        //
        const newState = this.validate(newProps.value);

        // ensure that we preserve the `hasValidated`, `isEditing`, and
        // `hasTrailingDecimal` state of the component
        //
        newState.hasValidated = this.state.hasValidated;
        newState.isEditing = this.state.isEditing;
        newState.hasTrailingDecimal = this.state.hasTrailingDecimal;

        // do we have a new value? if not, then don't bother changing anything
        //
        if (newState.value !== this.state.value) {
            // update the component state
            //
            this.setState(newState);

            // do we have an onValidation handler? if so, call it with the new
            // validation state
            //
            if (this.props.onValidation) {
                this.props.onValidation(
                    newState.hasValidated,
                    newState.isValid,
                    newState.validationMessage
                );
            }

            // do we have an onChange handler? if so, call it with the new value
            //
            if (this.props.onChange) {
                this.props.onChange(newState.value);
            }
        }
    }

    /**
     * Handle the blur event for the input element
     * @param  {Object} event The event object
     */
    onBlur(event) {
        // validate the new value WITH FORMATTING
        //
        const newState = this.validate(event.target.value);

        // set `hasValidated` to true
        //
        newState.hasValidated = true;

        // set `isEditing` to false (since the user has just tabbed away)
        //
        newState.isEditing = false;

        // set `hasTrailingDecimal` to false (since we're no longer editing)
        //
        newState.hasTrailingDecimal = false;

        // handle the updated state
        //
        this.onUpdatedState(newState);
    }

    /**
     * Handle the change event for the input element
     * @param  {Object} event The event object
     */
    onChange(event) {
        // validate the new value without formatting it
        //
        const newState = this.validate(event.target.value);

        // preserve the `hasValidated` state
        //
        newState.hasValidated = this.state.hasValidated;

        // set `isEditing` to true, since the user is currently editing
        //
        newState.isEditing = true;

        // set the `hasTrailingDecimal` based on whether the rightmost character
        // of the event value is a decimal
        //
        newState.hasTrailingDecimal = event.target.value[event.target.value.length - 1] === '.';

        // handle the updated state
        //
        this.onUpdatedState(newState);
    }

    /**
     * Handle the "update state" event
     * @param  {Object} newState The new state for the component
     */
    onUpdatedState(newState) {
        // set the new component state
        //
        this.setState(newState);

        // do we have an onValidation handler? has the component previously
        // validated? if so, call the onValidation handler with the new validation state
        //
        if (this.props.onValidation && newState.hasValidated) {
            this.props.onValidation(
                newState.hasValidated,
                newState.isValid,
                newState.validationMessage
            );
        }

        // do we have an onChange handler? do we have a new value? if so, call
        // the onChange handler with the new value
        //
        if (this.props.onChange && newState.value !== this.state.value) {
            this.props.onChange(newState.value);
        }
    }

    /**
     * Handle the focus event for the input element
     * @param  {Object} event The event object
     */
    onFocus(event) {
        // validate the new value
        //
        const newState = this.validate(event.target.value);

        // preserve the `hasValidated` state
        //
        newState.hasValidated = this.state.hasValidated;

        // set `isEditing` to true, since the user has just focused the input
        // element
        //
        newState.isEditing = true;

        // preserve the `hasTrailingDecimal` state
        //
        newState.hasTrailingDecimal = this.state.hasTrailingDecimal;

        // set the new state
        //
        this.setState(newState);
    }

    /**
     * Validate a value, optionally formatting it
     * @param  {String|Number} newValue The new value
     * @param  {Boolean} format         If true, then format the value according
     *                                  to the component props; otherwise, just
     *                                  clean it
     * @return {Object}                 The new state for the component,
     *                                  including value & validation state
     */
    validate(newValue) {
        // clean the value & convert it to a floating point number
        //
        let value = parseFloat(clean(newValue));

        // determine if the value is not a number (NaN)
        //
        const notANumber = Number.isNaN(value);

        // examine the value & ensure it's a number
        //
        if (notANumber) {
            // it's not a number - change to an empty string
            //
            value = '';
        }

        // check to see if the value is valid
        //
        const isValid = !this.props.required || (!!value || value === 0);

        // return the new component state
        //
        return {
            value,
            isValid,
            validationMessage:  isValid ? null : this.validationMessage,
            hasValidated:       false,
            isEditing:          false,
            hasTrailingDecimal: false,
        };
    }

    /**
     * Render the component
     * @return {React.Element} The React Element representing this component
     */
    render() {
        let value = `${this.state.value}`;

        // are we currently editing? if not, then format the value appropriately
        //
        if (!this.state.isEditing) {
            if (this.props.isCurrency) {
                value = currency(this.state.value);
            } else if (this.props.decimals || this.props.decimals === 0) {
                value = decimals(this.state.value, this.props.decimals);
            }
        }

        // generate the classes for the outermost div element
        //
        const divClasses = classnames('form-group', {
            'has-error': this.state.hasValidated && !this.state.isValid,
        });

        // instantiate the input element
        //
        const input = (
            <input
                type="text"
                id={this.id}
                className="form-control"
                placeholder={this.props.placeholder || ''}
                value={value}
                readOnly={this.props.readOnly}
                onBlur={this.onBlur}
                onChange={this.onChange}
                onFocus={this.onFocus}
            />
        );

        // instantiate the help block if there's a validation error
        //
        const helpBlock = this.state.hasValidated && !this.state.isValid
            ? {this.validationMessage}
            : '';

        // render the component & return it
        //
        return (

                {this.props.label
                    ?
                    : ''
                }

{input}{helpBlock}

        );
    }
}

// set the property types for the NumericInput component
//
NumericInput.propTypes = {
    label:             React.PropTypes.string,
    description:       React.PropTypes.string,
    required:          React.PropTypes.bool,
    readOnly:          React.PropTypes.bool,
    validationMessage: React.PropTypes.string,
    placeholder:       React.PropTypes.string,
    isCurrency:        React.PropTypes.bool,
    decimals:          React.PropTypes.number,
    labelColumns:      React.PropTypes.object,
    inputColumns:      React.PropTypes.object,
    value:             React.PropTypes.oneOfType([
        React.PropTypes.string,
        React.PropTypes.number,
    ]),
    onChange:          React.PropTypes.func,
    onValidation:      React.PropTypes.func,
};

// export the component
//
export default NumericInput;
<commit_msg>updated render method to add trailing decimal when flag is set<commit_after>// dependencies
//
import React from 'react';
import uniqueId from 'lodash/uniqueId';
import classnames from 'classnames';

import Label from './Label';
import columns from '../helpers/columns';

/**
 * Clean a value of any non-numeric characters
 * @param  {String|Number} value The value to clean
 * @return {String}              The cleaned value
 */
const clean = (value) => `${value}`.replace(/[^0-9.-]/g, '');

/**
 * Convert a value to a fixed-decimal number
 * @param  {Number} value The number to convert
 * @param  {Number} count The number of decimal places
 * @return {String}       The formatted number
 */
const decimals = (value, count) => (value !== '' ? `${value.toFixed(count)}` : '');

/**
 * Convert a value to a currency string (2 decimal places, prefixed by "$")
 * @param  {Number} value The value to convert
 * @return {String}       The formatted value
 */
const currency = (value) => (value !== '' ? `$ ${decimals(value, 2)}` : '');

/**
 * The NumericInput component
 */
class NumericInput extends React.Component {
    constructor(props) {
        super(props);

        // generate a unique ID for the component
        //
        this.id = uniqueId('NumericInput-');

        // set the validation message from the properties or from a default
        //
        this.validationMessage = this.props.validationMessage
            || `${props.description} is required`;

        // initialize the component state
        //
        this.state = this.validate(props.value);

        // bind `this` to the event handlers
        //
        this.onBlur = this.onBlur.bind(this);
        this.onChange = this.onChange.bind(this);
        this.onFocus = this.onFocus.bind(this);
    }

    /**
     * Handle the initial mounting of the component
     */
    componentWillMount() {
        // do we have an onValidation handler? if so, call it with the current
        // validation state
        //
        if (this.props.onValidation) {
            this.props.onValidation(
                this.state.hasValidated,
                this.state.isValid,
                this.state.validationMessage
            );
        }
    }

    /**
     * Handle new props passed from the parent component
     * @param  {Object} newProps The new props
     */
    componentWillReceiveProps(newProps) {
        // validate the new value
        //
        const newState = this.validate(newProps.value);

        // ensure that we preserve the `hasValidated`, `isEditing`, and
        // `hasTrailingDecimal` state of the component
        //
        newState.hasValidated = this.state.hasValidated;
        newState.isEditing = this.state.isEditing;
        newState.hasTrailingDecimal = this.state.hasTrailingDecimal;

        // do we have a new value? if not, then don't bother changing anything
        //
        if (newState.value !== this.state.value) {
            // update the component state
            //
            this.setState(newState);

            // do we have an onValidation handler? if so, call it with the new
            // validation state
            //
            if (this.props.onValidation) {
                this.props.onValidation(
                    newState.hasValidated,
                    newState.isValid,
                    newState.validationMessage
                );
            }

            // do we have an onChange handler? if so, call it with the new value
            //
            if (this.props.onChange) {
                this.props.onChange(newState.value);
            }
        }
    }

    /**
     * Handle the blur event for the input element
     * @param  {Object} event The event object
     */
    onBlur(event) {
        // validate the new value WITH FORMATTING
        //
        const newState = this.validate(event.target.value);

        // set `hasValidated` to true
        //
        newState.hasValidated = true;

        // set `isEditing` to false (since the user has just tabbed away)
        //
        newState.isEditing = false;

        // set `hasTrailingDecimal` to false (since we're no longer editing)
        //
        newState.hasTrailingDecimal = false;

        // handle the updated state
        //
        this.onUpdatedState(newState);
    }

    /**
     * Handle the change event for the input element
     * @param  {Object} event The event object
     */
    onChange(event) {
        // validate the new value without formatting it
        //
        const newState = this.validate(event.target.value);

        // preserve the `hasValidated` state
        //
        newState.hasValidated = this.state.hasValidated;

        // set `isEditing` to true, since the user is currently editing
        //
        newState.isEditing = true;

        // set the `hasTrailingDecimal` based on whether the rightmost character
        // of the event value is a decimal
        //
        newState.hasTrailingDecimal = event.target.value[event.target.value.length - 1] === '.';

        // handle the updated state
        //
        this.onUpdatedState(newState);
    }

    /**
     * Handle the "update state" event
     * @param  {Object} newState The new state for the component
     */
    onUpdatedState(newState) {
        // set the new component state
        //
        this.setState(newState);

        // do we have an onValidation handler? has the component previously
        // validated? if so, call the onValidation handler with the new validation state
        //
        if (this.props.onValidation && newState.hasValidated) {
            this.props.onValidation(
                newState.hasValidated,
                newState.isValid,
                newState.validationMessage
            );
        }

        // do we have an onChange handler? do we have a new value? if so, call
        // the onChange handler with the new value
        //
        if (this.props.onChange && newState.value !== this.state.value) {
            this.props.onChange(newState.value);
        }
    }

    /**
     * Handle the focus event for the input element
     * @param  {Object} event The event object
     */
    onFocus(event) {
        // validate the new value
        //
        const newState = this.validate(event.target.value);

        // preserve the `hasValidated` state
        //
        newState.hasValidated = this.state.hasValidated;

        // set `isEditing` to true, since the user has just focused the input
        // element
        //
        newState.isEditing = true;

        // preserve the `hasTrailingDecimal` state
        //
        newState.hasTrailingDecimal = this.state.hasTrailingDecimal;

        // set the new state
        //
        this.setState(newState);
    }

    /**
     * Validate a value, optionally formatting it
     * @param  {String|Number} newValue The new value
     * @param  {Boolean} format         If true, then format the value according
     *                                  to the component props; otherwise, just
     *                                  clean it
     * @return {Object}                 The new state for the component,
     *                                  including value & validation state
     */
    validate(newValue) {
        // clean the value & convert it to a floating point number
        //
        let value = parseFloat(clean(newValue));

        // determine if the value is not a number (NaN)
        //
        const notANumber = Number.isNaN(value);

        // examine the value & ensure it's a number
        //
        if (notANumber) {
            // it's not a number - change to an empty string
            //
            value = '';
        }

        // check to see if the value is valid
        //
        const isValid = !this.props.required || (!!value || value === 0);

        // return the new component state
        //
        return {
            value,
            isValid,
            validationMessage:  isValid ? null : this.validationMessage,
            hasValidated:       false,
            isEditing:          false,
            hasTrailingDecimal: false,
        };
    }

    /**
     * Render the component
     * @return {React.Element} The React Element representing this component
     */
    render() {
        let value = `${this.state.value}`;

        // are we currently editing? if not, then format the value appropriately
        //
        if (!this.state.isEditing) {
            if (this.props.isCurrency) {
                value = currency(this.state.value);
            } else if (this.props.decimals || this.props.decimals === 0) {
                value = decimals(this.state.value, this.props.decimals);
            }
        }

        // if the hasTrailingDecimal flag is set, then append a decimal
        // character
        //
        if (this.state.hasTrailingDecimal) {
            value += '.';
        }

        // generate the classes for the outermost div element
        //
        const divClasses = classnames('form-group', {
            'has-error': this.state.hasValidated && !this.state.isValid,
        });

        // instantiate the input element
        //
        const input = (
            <input
                type="text"
                id={this.id}
                className="form-control"
                placeholder={this.props.placeholder || ''}
                value={value}
                readOnly={this.props.readOnly}
                onBlur={this.onBlur}
                onChange={this.onChange}
                onFocus={this.onFocus}
            />
        );

        // instantiate the help block if there's a validation error
        //
        const helpBlock = this.state.hasValidated && !this.state.isValid
            ? {this.validationMessage}
            : '';

        // render the component & return it
        //
        return (

                {this.props.label
                    ?
                    : ''
                }

{input}{helpBlock}

        );
    }
}

// set the property types for the NumericInput component
//
NumericInput.propTypes = {
    label:             React.PropTypes.string,
    description:       React.PropTypes.string,
    required:          React.PropTypes.bool,
    readOnly:          React.PropTypes.bool,
    validationMessage: React.PropTypes.string,
    placeholder:       React.PropTypes.string,
    isCurrency:        React.PropTypes.bool,
    decimals:          React.PropTypes.number,
    labelColumns:      React.PropTypes.object,
    inputColumns:      React.PropTypes.object,
    value:             React.PropTypes.oneOfType([
        React.PropTypes.string,
        React.PropTypes.number,
    ]),
    onChange:          React.PropTypes.func,
    onValidation:      React.PropTypes.func,
};

// export the component
//
export default NumericInput;
<|endoftext|>


<commit_before>import React from 'react';
import './styles.css';

export default (props) => (

            Web-code

            Github

);<commit_msg>Fixing security flaw<commit_after>import React from 'react';
import './styles.css';

export default (props) => (

            Web-code

                Github

);<|endoftext|>


<commit_before>import React from 'react'
import ReactCountdownClock from 'react-countdown-clock'
import { checkNetWorkByID, checkTxMined, sendTXToContract } from '../../utils/blockchainHelpers'
import {
  findCurrentContractRecursively,
  getAccumulativeCrowdsaleData,
  getContractStoreProperty,
  getCrowdsaleData,
  getCrowdsaleTargetDates,
  getCurrentRate,
  getJoinedTiers
} from '../crowdsale/utils'
import { getQueryVariable, getURLParam, getWhiteListWithCapCrowdsaleAssets, toast } from '../../utils/utils'
import {
  invalidCrowdsaleAddrAlert,
  investmentDisabledAlertInTime,
  noMetaMaskAlert,
  successfulInvestmentAlert
} from '../../utils/alerts'
import { Loader } from '../Common/Loader'
import { ICOConfig } from '../Common/config'
import { CONTRACT_TYPES, INVESTMENT_OPTIONS, TOAST } from '../../utils/constants'
import { inject, observer } from 'mobx-react'
import QRPaymentProcess from './QRPaymentProcess'

@inject('contractStore', 'crowdsalePageStore', 'web3Store', 'tierStore', 'tokenStore', 'generalStore', 'investStore')
@observer
export class Invest extends React.Component {
  constructor(props) {
    super(props);
    window.scrollTo(0, 0);

    this.state = {
      seconds: 0,
      loading: true,
      pristineTokenInput: true,
      web3Available: false,
      investThrough: INVESTMENT_OPTIONS.QR,
      crowdsaleAddress: ICOConfig.crowdsaleContractURL || getURLParam("addr")
    }
  }

  componentDidMount () {
    const { web3Store, contractStore } = this.props
    const { web3 } = web3Store

    if (!web3) {
      this.setState({ loading: false })
      return
    }

    const networkID = ICOConfig.networkID ? ICOConfig.networkID : getQueryVariable('networkID')
    const contractType = CONTRACT_TYPES.whitelistwithcap
    checkNetWorkByID(web3, networkID)
    contractStore.setContractType(contractType)

    const timeInterval = setInterval(() => this.setState({ seconds: this.state.seconds - 1 }), 1000);
    this.setState({
      timeInterval,
      web3Available: true,
      investThrough: INVESTMENT_OPTIONS.METAMASK
    });

    getWhiteListWithCapCrowdsaleAssets()
      .then(_newState => {
        this.setState(_newState)
        this.extractContractsData(web3)
      })
  }

  extractContractsData(web3) {
    const { contractStore, crowdsalePageStore } = this.props

    const crowdsaleAddr = ICOConfig.crowdsaleContractURL ? ICOConfig.crowdsaleContractURL : getURLParam('addr')

    if (!web3.utils.isAddress(crowdsaleAddr)) {
      this.setState({ loading: false })
      return invalidCrowdsaleAddrAlert()
    }

    getJoinedTiers(web3, contractStore.crowdsale.abi, crowdsaleAddr, [], joinedCrowdsales => {
      console.log('joinedCrowdsales:', joinedCrowdsales)

      const crowdsaleAddrs = typeof joinedCrowdsales === 'string' ? [joinedCrowdsales] : joinedCrowdsales
      contractStore.setContractProperty('crowdsale', 'addr', crowdsaleAddrs)

      web3.eth.getAccounts().then((accounts) => {
        if (accounts.length === 0) {
          this.setState({ loading: false })
          return
        }

        this.setState({
          curAddr: accounts[0],
          web3
        })

        if (!contractStore.crowdsale.addr) {
          this.setState({ loading: false })
          return
        }

        findCurrentContractRecursively(0, this, web3, null, crowdsaleContract => {
          if (!crowdsaleContract) {
            this.setState({ loading: false })
            return
          }

          getCrowdsaleData(web3, crowdsaleContract)
            .then(() => getAccumulativeCrowdsaleData.call(this, web3, () => Promise.resolve()))
            .then(() => this.setState({ loading: false }))
            .catch(err => {
              this.setState({ loading: false })
              console.log(err)
            })

          getCrowdsaleTargetDates(web3, this, () => {
            if (crowdsalePageStore.endDate) {
              this.setState({
                seconds: (crowdsalePageStore.endDate - new Date().getTime()) / 1000
              })
            }
          })
        })
      })
    })
  }

  investToTokens = event => {
    const { investStore, crowdsalePageStore, web3Store } = this.props
    const { web3 } = web3Store

    event.preventDefault()

    if (!this.isValidToken(investStore.tokensToInvest)) {
      this.setState({ pristineTokenInput: false })
      return
    }

    this.setState({ loading: true })

    const startBlock = parseInt(crowdsalePageStore.startBlock, 10)
    const { startDate } = crowdsalePageStore

    if ((isNaN(startBlock) || startBlock === 0) && !startDate) {
      this.setState({ loading: false })
      return
    }

    if (web3.eth.accounts.length === 0) {
      this.setState({ loading: false })
      return noMetaMaskAlert()
    }

    this.investToTokensForWhitelistedCrowdsale(web3)
  }

  investToTokensForWhitelistedCrowdsale(web3) {
    const { crowdsalePageStore } = this.props

    if (crowdsalePageStore.startDate > (new Date()).getTime()) {
      this.setState({ loading: false })
      return investmentDisabledAlertInTime(crowdsalePageStore.startDate)
    }

    findCurrentContractRecursively(0, this, web3, null, (crowdsaleContract, tierNum) => {
      if (!crowdsaleContract) {
        this.setState({ loading: false })
        return
      }

      console.log(web3)

      getCurrentRate(web3, crowdsaleContract)
        .then(() => {
          console.log(web3)
          this.investToTokensForWhitelistedCrowdsaleInternal(crowdsaleContract, tierNum, web3, web3.eth.accounts)
        })
        .catch(console.log)
    })
  }

  investToTokensForWhitelistedCrowdsaleInternal(crowdsaleContract, tierNum, web3, accounts) {
    const { contractStore, tokenStore, crowdsalePageStore, investStore, generalStore } = this.props

    let nextTiers = []
    for (let i = tierNum + 1; i < contractStore.crowdsale.addr.length; i++) {
      nextTiers.push(contractStore.crowdsale.addr[i])
    }
    console.log('nextTiers:', nextTiers)
    console.log(nextTiers.length)

    const decimals = parseInt(tokenStore.decimals, 10)
    console.log('decimals:', decimals)

    const rate = parseInt(crowdsalePageStore.rate, 10) //it is from contract. It is already in wei. How much 1 token costs in wei.
    console.log('rate:', rate)

    const tokensToInvest = parseFloat(investStore.tokensToInvest)
    console.log('tokensToInvest:', tokensToInvest)

    const weiToSend = parseInt(tokensToInvest * rate, 10)
    console.log('weiToSend:', weiToSend)

    const opts = {
      from: accounts[0],
      value: weiToSend,
      gasPrice: generalStore.gasPrice
    }
    console.log(opts)

    sendTXToContract(web3, crowdsaleContract.methods.buy().send(opts))
      .then(() => successfulInvestmentAlert(investStore.tokensToInvest))
      .catch(err => toast.showToaster({ type: TOAST.TYPE.ERROR, message: TOAST.MESSAGE.TRANSACTION_FAILED }))
      .then(() => this.setState({ loading: false }))
  }

  txMinedCallback(web3, txHash, receipt) {
    const { investStore } = this.props

    console.log(web3)

    if (receipt) {
      if (receipt.blockNumber) {
        this.setState({ loading: false })
        successfulInvestmentAlert(investStore.tokensToInvest)
      }
    } else {
      console.log(web3)

      setTimeout(() => {
        checkTxMined(web3, txHash, receipt => this.txMinedCallback(web3, txHash, receipt))
      }, 500)
    }
  }

  tokensToInvestOnChange = event => {
    this.setState({ pristineTokenInput: false })
    this.props.investStore.setProperty('tokensToInvest', event.target.value)
  }

  isValidToken(token) {
    return +token > 0;
  }

  renderPieTracker () {
    return (

        <ReactCountdownClock
          seconds={this.state.seconds}
          color="#733EAB"
          alpha={0.9}
          size={270}
        />

    )
  }

  shouldStopCountDown () {
    if(this.state.seconds < 0) {
      this.setState({ seconds: 0 })
      clearInterval(this.state.timeInterval)
    }
  }

  getTimeStamps (seconds) {
    this.shouldStopCountDown()
    const days        = Math.floor(seconds / 24 / 60 / 60)
    const hoursLeft   = Math.floor(seconds - days * 86400)
    const hours       = Math.floor(hoursLeft / 3600)
    const minutesLeft = Math.floor(hoursLeft - hours * 3600)
    const minutes     = Math.floor(minutesLeft / 60)
    return { days, hours, minutes }
  }

  render () {
    const { crowdsalePageStore, tokenStore, contractStore, investStore } = this.props
    const { rate, tokenAmountOf, ethRaised, supply } = crowdsalePageStore
    const { crowdsale, contractType } = contractStore
    const { tokensToInvest } = investStore

    const { seconds, curAddr, pristineTokenInput, investThrough, crowdsaleAddress, web3Available } = this.state
    const { days, hours, minutes } = this.getTimeStamps(seconds)

    const { decimals, ticker, name } = tokenStore
    const isWhitelistWithCap = contractType === CONTRACT_TYPES.whitelistwithcap

    const tokenDecimals = !isNaN(decimals) ? decimals : 0
    const tokenTicker = ticker ? ticker.toString() : ''
    const tokenName = name ? name.toString() : ''
    const maxCapBeforeDecimals = crowdsalePageStore.maximumSellableTokens / 10 ** tokenDecimals
    const tokenAddress = getContractStoreProperty('token', 'addr')

    //balance: tiers, standard
    const investorBalanceTiers = tokenAmountOf ? (tokenAmountOf / 10 ** tokenDecimals).toString() : '0'
    const investorBalanceStandard = ethRaised ? (ethRaised / rate).toString() : '0'
    const investorBalance = isWhitelistWithCap ? investorBalanceTiers : investorBalanceStandard

    //total supply: tiers, standard
    const tierCap = !isNaN(maxCapBeforeDecimals) ? maxCapBeforeDecimals.toString() : '0'
    const standardCrowdsaleSupply = !isNaN(supply) ? supply.toString() : '0'
    const totalSupply = isWhitelistWithCap ? tierCap : standardCrowdsaleSupply

    let invalidTokenDescription = null
    if (!pristineTokenInput && !this.isValidToken(tokensToInvest)) {
      invalidTokenDescription =
Number of tokens to buy should be positive

    }

    const QRPaymentProcessElement = investThrough === INVESTMENT_OPTIONS.QR ?
      <QRPaymentProcess crowdsaleAddress={crowdsaleAddress} /> :
      null

    const ContributeButton = investThrough === INVESTMENT_OPTIONS.METAMASK ?
      Contribute :
      null

    return

{days}

Days

{hours}

Hours

{minutes}

Mins

            {this.renderPieTracker()}

{curAddr}

Current Account

{tokenAddress}

Token Address

{crowdsale && crowdsale.addr && crowdsale.addr[0]}

Crowdsale Contract Address

{tokenName}

Name

{tokenTicker}

Ticker

{totalSupply} {tokenTicker}

Total Supply

Invest page

            {"Here you can invest in the crowdsale campaign. At the moment, you need Metamask client to invest into the crowdsale. If you don't have Metamask, you can send ethers to the crowdsale address with a MethodID: 0xa6f2ae3a. Sample "}
            transaction.

{investorBalance} {tokenTicker}

Balance

              Your balance in tokens.

          <form className="invest-form" onSubmit={this.investToTokens}>
            Choose amount to invest

              <input type="text" className="invest-form-input" value={tokensToInvest} onChange={this.tokensToInvestOnChange} placeholder="0"/>

TOKENS

              {invalidTokenDescription}

              <select value={investThrough} className="invest-through" onChange={(e) => this.setState({ investThrough: e.target.value })}>
                <option disabled={!web3Available} value={INVESTMENT_OPTIONS.METAMASK}>Metamask {!web3Available ? ' (not available)' : null}</option>
                <option value={INVESTMENT_OPTIONS.QR}>QR</option>
              </select>
              { ContributeButton }

              Think twice before investment in ICOs. Tokens will be deposited on a wallet you used to buy tokens.

          </form>
          { QRPaymentProcessElement }

      <Loader show={this.state.loading}></Loader>

  }
}
<commit_msg>Fix estimate gas limit before buy<commit_after>import React from 'react'
import ReactCountdownClock from 'react-countdown-clock'
import { checkNetWorkByID, checkTxMined, sendTXToContract } from '../../utils/blockchainHelpers'
import {
  findCurrentContractRecursively,
  getAccumulativeCrowdsaleData,
  getContractStoreProperty,
  getCrowdsaleData,
  getCrowdsaleTargetDates,
  getCurrentRate,
  getJoinedTiers
} from '../crowdsale/utils'
import { getQueryVariable, getURLParam, getWhiteListWithCapCrowdsaleAssets, toast } from '../../utils/utils'
import {
  invalidCrowdsaleAddrAlert,
  investmentDisabledAlertInTime,
  noMetaMaskAlert,
  successfulInvestmentAlert
} from '../../utils/alerts'
import { Loader } from '../Common/Loader'
import { ICOConfig } from '../Common/config'
import { CONTRACT_TYPES, INVESTMENT_OPTIONS, TOAST } from '../../utils/constants'
import { inject, observer } from 'mobx-react'
import QRPaymentProcess from './QRPaymentProcess'

@inject('contractStore', 'crowdsalePageStore', 'web3Store', 'tierStore', 'tokenStore', 'generalStore', 'investStore')
@observer
export class Invest extends React.Component {
  constructor(props) {
    super(props);
    window.scrollTo(0, 0);

    this.state = {
      seconds: 0,
      loading: true,
      pristineTokenInput: true,
      web3Available: false,
      investThrough: INVESTMENT_OPTIONS.QR,
      crowdsaleAddress: ICOConfig.crowdsaleContractURL || getURLParam("addr")
    }
  }

  componentDidMount () {
    const { web3Store, contractStore } = this.props
    const { web3 } = web3Store

    if (!web3) {
      this.setState({ loading: false })
      return
    }

    const networkID = ICOConfig.networkID ? ICOConfig.networkID : getQueryVariable('networkID')
    const contractType = CONTRACT_TYPES.whitelistwithcap
    checkNetWorkByID(web3, networkID)
    contractStore.setContractType(contractType)

    const timeInterval = setInterval(() => this.setState({ seconds: this.state.seconds - 1 }), 1000);
    this.setState({
      timeInterval,
      web3Available: true,
      investThrough: INVESTMENT_OPTIONS.METAMASK
    });

    getWhiteListWithCapCrowdsaleAssets()
      .then(_newState => {
        this.setState(_newState)
        this.extractContractsData(web3)
      })
  }

  extractContractsData(web3) {
    const { contractStore, crowdsalePageStore } = this.props

    const crowdsaleAddr = ICOConfig.crowdsaleContractURL ? ICOConfig.crowdsaleContractURL : getURLParam('addr')

    if (!web3.utils.isAddress(crowdsaleAddr)) {
      this.setState({ loading: false })
      return invalidCrowdsaleAddrAlert()
    }

    getJoinedTiers(web3, contractStore.crowdsale.abi, crowdsaleAddr, [], joinedCrowdsales => {
      console.log('joinedCrowdsales:', joinedCrowdsales)

      const crowdsaleAddrs = typeof joinedCrowdsales === 'string' ? [joinedCrowdsales] : joinedCrowdsales
      contractStore.setContractProperty('crowdsale', 'addr', crowdsaleAddrs)

      web3.eth.getAccounts().then((accounts) => {
        if (accounts.length === 0) {
          this.setState({ loading: false })
          return
        }

        this.setState({
          curAddr: accounts[0],
          web3
        })

        if (!contractStore.crowdsale.addr) {
          this.setState({ loading: false })
          return
        }

        findCurrentContractRecursively(0, this, web3, null, crowdsaleContract => {
          if (!crowdsaleContract) {
            this.setState({ loading: false })
            return
          }

          getCrowdsaleData(web3, crowdsaleContract)
            .then(() => getAccumulativeCrowdsaleData.call(this, web3, () => Promise.resolve()))
            .then(() => this.setState({ loading: false }))
            .catch(err => {
              this.setState({ loading: false })
              console.log(err)
            })

          getCrowdsaleTargetDates(web3, this, () => {
            if (crowdsalePageStore.endDate) {
              this.setState({
                seconds: (crowdsalePageStore.endDate - new Date().getTime()) / 1000
              })
            }
          })
        })
      })
    })
  }

  investToTokens = event => {
    const { investStore, crowdsalePageStore, web3Store } = this.props
    const { web3 } = web3Store

    event.preventDefault()

    if (!this.isValidToken(investStore.tokensToInvest)) {
      this.setState({ pristineTokenInput: false })
      return
    }

    this.setState({ loading: true })

    const startBlock = parseInt(crowdsalePageStore.startBlock, 10)
    const { startDate } = crowdsalePageStore

    if ((isNaN(startBlock) || startBlock === 0) && !startDate) {
      this.setState({ loading: false })
      return
    }

    if (web3.eth.accounts.length === 0) {
      this.setState({ loading: false })
      return noMetaMaskAlert()
    }

    this.investToTokensForWhitelistedCrowdsale(web3)
  }

  investToTokensForWhitelistedCrowdsale(web3) {
    const { crowdsalePageStore } = this.props

    if (crowdsalePageStore.startDate > (new Date()).getTime()) {
      this.setState({ loading: false })
      return investmentDisabledAlertInTime(crowdsalePageStore.startDate)
    }

    findCurrentContractRecursively(0, this, web3, null, (crowdsaleContract, tierNum) => {
      if (!crowdsaleContract) {
        this.setState({ loading: false })
        return
      }

      console.log(web3)

      getCurrentRate(web3, crowdsaleContract)
        .then(() => {
          console.log(web3)
          this.investToTokensForWhitelistedCrowdsaleInternal(crowdsaleContract, tierNum, web3, web3.eth.accounts)
        })
        .catch(console.log)
    })
  }

  investToTokensForWhitelistedCrowdsaleInternal(crowdsaleContract, tierNum, web3, accounts) {
    const { contractStore, tokenStore, crowdsalePageStore, investStore, generalStore } = this.props

    let nextTiers = []
    for (let i = tierNum + 1; i < contractStore.crowdsale.addr.length; i++) {
      nextTiers.push(contractStore.crowdsale.addr[i])
    }
    console.log('nextTiers:', nextTiers)
    console.log(nextTiers.length)

    const decimals = parseInt(tokenStore.decimals, 10)
    console.log('decimals:', decimals)

    const rate = parseInt(crowdsalePageStore.rate, 10) //it is from contract. It is already in wei. How much 1 token costs in wei.
    console.log('rate:', rate)

    const tokensToInvest = parseFloat(investStore.tokensToInvest)
    console.log('tokensToInvest:', tokensToInvest)

    const weiToSend = parseInt(tokensToInvest * rate, 10)
    console.log('weiToSend:', weiToSend)

    const opts = {
      from: accounts[0],
      value: weiToSend,
      gasPrice: generalStore.gasPrice
    }
    console.log(opts)

    crowdsaleContract.methods.buy().estimateGas(opts)
      .then(estimatedGas => {
        const estimatedGasMax = 362897
        opts.gasLimit = !estimatedGas || estimatedGas > estimatedGasMax ? estimatedGasMax : estimatedGas + 100000

        return sendTXToContract(web3, crowdsaleContract.methods.buy().send(opts))
      })
      .then(() => successfulInvestmentAlert(investStore.tokensToInvest))
      .catch(err => toast.showToaster({ type: TOAST.TYPE.ERROR, message: TOAST.MESSAGE.TRANSACTION_FAILED }))
      .then(() => this.setState({ loading: false }))
  }

  txMinedCallback(web3, txHash, receipt) {
    const { investStore } = this.props

    console.log(web3)

    if (receipt) {
      if (receipt.blockNumber) {
        this.setState({ loading: false })
        successfulInvestmentAlert(investStore.tokensToInvest)
      }
    } else {
      console.log(web3)

      setTimeout(() => {
        checkTxMined(web3, txHash, receipt => this.txMinedCallback(web3, txHash, receipt))
      }, 500)
    }
  }

  tokensToInvestOnChange = event => {
    this.setState({ pristineTokenInput: false })
    this.props.investStore.setProperty('tokensToInvest', event.target.value)
  }

  isValidToken(token) {
    return +token > 0;
  }

  renderPieTracker () {
    return (

        <ReactCountdownClock
          seconds={this.state.seconds}
          color="#733EAB"
          alpha={0.9}
          size={270}
        />

    )
  }

  shouldStopCountDown () {
    if(this.state.seconds < 0) {
      this.setState({ seconds: 0 })
      clearInterval(this.state.timeInterval)
    }
  }

  getTimeStamps (seconds) {
    this.shouldStopCountDown()
    const days        = Math.floor(seconds / 24 / 60 / 60)
    const hoursLeft   = Math.floor(seconds - days * 86400)
    const hours       = Math.floor(hoursLeft / 3600)
    const minutesLeft = Math.floor(hoursLeft - hours * 3600)
    const minutes     = Math.floor(minutesLeft / 60)
    return { days, hours, minutes }
  }

  render () {
    const { crowdsalePageStore, tokenStore, contractStore, investStore } = this.props
    const { rate, tokenAmountOf, ethRaised, supply } = crowdsalePageStore
    const { crowdsale, contractType } = contractStore
    const { tokensToInvest } = investStore

    const { seconds, curAddr, pristineTokenInput, investThrough, crowdsaleAddress, web3Available } = this.state
    const { days, hours, minutes } = this.getTimeStamps(seconds)

    const { decimals, ticker, name } = tokenStore
    const isWhitelistWithCap = contractType === CONTRACT_TYPES.whitelistwithcap

    const tokenDecimals = !isNaN(decimals) ? decimals : 0
    const tokenTicker = ticker ? ticker.toString() : ''
    const tokenName = name ? name.toString() : ''
    const maxCapBeforeDecimals = crowdsalePageStore.maximumSellableTokens / 10 ** tokenDecimals
    const tokenAddress = getContractStoreProperty('token', 'addr')

    //balance: tiers, standard
    const investorBalanceTiers = tokenAmountOf ? (tokenAmountOf / 10 ** tokenDecimals).toString() : '0'
    const investorBalanceStandard = ethRaised ? (ethRaised / rate).toString() : '0'
    const investorBalance = isWhitelistWithCap ? investorBalanceTiers : investorBalanceStandard

    //total supply: tiers, standard
    const tierCap = !isNaN(maxCapBeforeDecimals) ? maxCapBeforeDecimals.toString() : '0'
    const standardCrowdsaleSupply = !isNaN(supply) ? supply.toString() : '0'
    const totalSupply = isWhitelistWithCap ? tierCap : standardCrowdsaleSupply

    let invalidTokenDescription = null
    if (!pristineTokenInput && !this.isValidToken(tokensToInvest)) {
      invalidTokenDescription =
Number of tokens to buy should be positive

    }

    const QRPaymentProcessElement = investThrough === INVESTMENT_OPTIONS.QR ?
      <QRPaymentProcess crowdsaleAddress={crowdsaleAddress} /> :
      null

    const ContributeButton = investThrough === INVESTMENT_OPTIONS.METAMASK ?
      Contribute :
      null

    return

{days}

Days

{hours}

Hours

{minutes}

Mins

            {this.renderPieTracker()}

{curAddr}

Current Account

{tokenAddress}

Token Address

{crowdsale && crowdsale.addr && crowdsale.addr[0]}

Crowdsale Contract Address

{tokenName}

Name

{tokenTicker}

Ticker

{totalSupply} {tokenTicker}

Total Supply

Invest page

            {"Here you can invest in the crowdsale campaign. At the moment, you need Metamask client to invest into the crowdsale. If you don't have Metamask, you can send ethers to the crowdsale address with a MethodID: 0xa6f2ae3a. Sample "}
            transaction.

{investorBalance} {tokenTicker}

Balance

              Your balance in tokens.

          <form className="invest-form" onSubmit={this.investToTokens}>
            Choose amount to invest

              <input type="text" className="invest-form-input" value={tokensToInvest} onChange={this.tokensToInvestOnChange} placeholder="0"/>

TOKENS

              {invalidTokenDescription}

              <select value={investThrough} className="invest-through" onChange={(e) => this.setState({ investThrough: e.target.value })}>
                <option disabled={!web3Available} value={INVESTMENT_OPTIONS.METAMASK}>Metamask {!web3Available ? ' (not available)' : null}</option>
                <option value={INVESTMENT_OPTIONS.QR}>QR</option>
              </select>
              { ContributeButton }

              Think twice before investment in ICOs. Tokens will be deposited on a wallet you used to buy tokens.

          </form>
          { QRPaymentProcessElement }

      <Loader show={this.state.loading}></Loader>

  }
}
<|endoftext|>


<commit_before>function sortTabs(prop){
  prop = prop || "url";
  chrome.tabs.query({currentWindow: true}, function(tabs){
    tabs.sort(function(a,b){
      return a[prop] == b[prop] ? 0 : (a[prop] < b[prop] ? -1 : 1);
    });
    tabs.forEach(function(tab){
      chrome.tabs.move(tab.id, {index: -1});
      // chrome.tabs.update(tab.id, {}, function(tab) {
      //   console.log("initial" + tab.favIconUrl);
      //   tab.favIconUrl = "http://www.google.com/favicon.ico";
      //   tab.title = "hello";
      //   console.log("final" + tab.favIconUrl);
      // });
      chrome.tabs.executeScript(tab.id,{code:"document.title = 'test'" });
      //changeFavicon("url");
      chrome.tabs.executeScript(tab.id,{code:"document.querySelectorAll(\"link[rel*='mask-icon']\")[0].href = 'http://www.google.com/favicon.ico'"});
      chrome.tabs.executeScript(tab.id,{code:"document.querySelectorAll(\"link[rel*='shortcut icon']\")[0].href = 'http://www.google.com/favicon.ico'"});
      chrome.tabs.executeScript(tab.id,{code:"document.querySelectorAll(\"link[rel*='icon']\")[0].href = 'http://www.google.com/favicon.ico'"});

    });
    //chrome.tabs.create({url:"http://www.google.com"});
  });
}

chrome.tabs.onCreated.addListener(function(tab){
  console.log("hello");
  sortTabs("url");

});

function changeFavicon(src) {
 var link = document.createElement('link'),
     oldLink = document.getElementById('dynamic-favicon');
 link.id = 'http://www.google.com/favicon.ico';
 link.rel = 'http://www.google.com/favicon.ico';
 link.href = src;
 if (oldLink) {
  document.head.removeChild(oldLink);
 }
 document.head.appendChild(link);
}
<commit_msg>working with favicons and title changes<commit_after>function sortTabs(prop){
  prop = prop || "url";
  chrome.tabs.query({currentWindow: true}, function(tabs){
    tabs.sort(function(a,b){
      return a[prop] == b[prop] ? 0 : (a[prop] < b[prop] ? -1 : 1);
    });
    tabs.forEach(function(tab){
      chrome.tabs.move(tab.id, {index: -1});
      chrome.tabs.executeScript(tab.id,{code:"document.title = 'test'" });
      chrome.tabs.executeScript(tab.id,{code:"document.querySelectorAll(\"link[rel*='mask-icon']\")[0].href = 'http://www.google.com/favicon.ico'"});
      chrome.tabs.executeScript(tab.id,{code:"document.querySelectorAll(\"link[rel*='shortcut icon']\")[0].href = 'http://www.google.com/favicon.ico'"});
      chrome.tabs.executeScript(tab.id,{code:"document.querySelectorAll(\"link[rel*='icon']\")[0].href = 'http://www.google.com/favicon.ico'"});

    });
  });
}

chrome.tabs.onCreated.addListener(function(tab){
  console.log("hello");
  sortTabs("url");

});
<|endoftext|>


<commit_before>import QNewLayout from './QNewLayout'
import QLayoutDrawer from './QLayoutDrawer'
import QLayoutFooter from './QLayoutFooter'
import QLayoutHeader from './QLayoutHeader'
import QPage from './QPage'
import QPageContainer from './QPageContainer'
import QPageSticky from './QPageSticky'

export {
  QNewLayout,
  QLayoutDrawer,
  QLayoutFooter,
  QLayoutHeader,
  QPage,
  QPageContainer,
  QPageSticky
}
<commit_msg>fix: Build error<commit_after>import QLayout from './QLayout'
import QLayoutDrawer from './QLayoutDrawer'
import QLayoutFooter from './QLayoutFooter'
import QLayoutHeader from './QLayoutHeader'
import QPage from './QPage'
import QPageContainer from './QPageContainer'
import QPageSticky from './QPageSticky'

export {
  QLayout,
  QLayoutDrawer,
  QLayoutFooter,
  QLayoutHeader,
  QPage,
  QPageContainer,
  QPageSticky
}
<|endoftext|>


<commit_before>angular.module('app',
    ['ngMessages',
      'ipCookie',
      'ngResource',
      'restangular',
      'ui.bootstrap',
      'ui.router',
      'ng-token-auth',
      'app.auth',
      'app.utils',
      'ui.gravatar',
      'angulartics',
      'angulartics.google.analytics'])

    .config(function ($stateProvider, $locationProvider, $urlRouterProvider, gravatarServiceProvider) {

      // NOTE: If you're going to use html5 pushstate, you'll need to configure your webserver(s) to route to index.html, except for static assets
      $locationProvider.html5Mode(true);
      $urlRouterProvider.otherwise('/home');

      function authRoute($auth, $state, $rootScope) {
        return $auth.validateUser()
          .catch(function(res) {
            //TODO: also open the login modal
            $state.go('home');
            $rootScope.$emit('navbar:openLoginModal');
          });
      }

      $stateProvider
          .state('home', {
            url: "/home",
            templateUrl: "home.html",
            controller: 'HomeCtrl'
          })

          .state('error', {
            url: "/error",
            templateUrl: "error.html",
            controller: 'HomeCtrl'
          })

          .state('password-reset', {
            url: "/password/reset",
            templateUrl: "auth/password-reset.html",
            controller: 'PasswordResetCtrl'
          })

          .state('password-change', {
            url: "/password/change",
            templateUrl: "auth/password-change.html",
            controller: 'PasswordChangeCtrl',
            resolve: {
              auth: authRoute
            }
          })

          .state('users', {
            url: "/users",
            templateUrl: "users/index.html",
            controller: function ($scope, users) {
              $scope.users = users;
            },
            resolve: {
              auth: authRoute,
              users: function(Users) {
                return Users.getList();
              }
            }
          })

          .state('users-profile', {
            url: '/users/{userId:int}',
            templateUrl: 'users/profile.html',
            controller: function ($scope, user) {
              $scope.user = user;
            },
            resolve: {
              auth: authRoute,
              user: function($stateParams, Users) {
                return Users.one($stateParams.userId).get();
              }
            }
          })

          .state('users-profile-edit', {
            url: '/users/{userId:int}/edit',
            templateUrl: 'users/edit.html',
            controller: function ($scope, $state, user) {
              $scope.validName = /^[a-zA-Z0-9\s]+$/;
              $scope.user = user;
              $scope.submit = function() {
                $scope.user.save().then(function(res) {
                  $state.go('users-profile', {userId: $scope.user.id});
                });
              };
            },
            resolve: {
              auth: authRoute,
              user: function($stateParams, Users) {
                return Users.one($stateParams.userId).get();
              }
            }
          })

          .state('sounds.detail', {
            url: "/sounds/{soundId:int}",
            templateUrl: "sounds/detail.html",
            controller: function($scope, Sounds) {

            },
            resolve: {
              auth: authRoute
            }
          })

          .state('sounds.detail.sound', {

          })

          .state('artists', {
            url: "/artists",
            abstract: true,
            template: '<ui-view/>',
            resolve: {
              auth: authRoute
            }
          })

          .state('artists.list', {
            url: "/list",
            templateUrl: "artists/index.html",
            resolve: {
              artists: function (Artists) { return Artists.getList(); }
            },
            controller: function ($scope, artists) {
              $scope.artists = artists;
            }
          })

          //TODO: change artist urls to reference their name
          .state('artists.detail', {
            url: '/{artistId:int}',
            templateUrl: "artists/detail.html",
            resolve: {
              artist: function ($stateParams, Artists) { return Artists.one($stateParams.artistId).get(); },
              audio: function (SpectrogramAudio) { return SpectrogramAudio; },
              mic: function (SpectrogramMic) { return SpectrogramMic; }
            },
            controller: 'SpectroCtrl'
          })

          .state('artists.detail.sound', {
            url: '/sounds/{soundId:int}',
            templateUrl: "artists/sound.html",
            resolve: {
              sound: function ($stateParams, Sounds) { return Sounds.one($stateParams.soundId).get(); }
            },
            controller: 'SpectroSoundsCtrl'
          });

      gravatarServiceProvider.defaults = {
        size: 100,
        default: 'retro'
      };
    })

    .constant('ENV', {
      //TODO: update so host is separate from url
      apiHost: '<%= api_protocol %>://<%= api_url %>',
      apiUrl: '<%= api_protocol %>://<%= api_url %>/api/v1'
    })

    .config(function(RestangularProvider, ENV) {
      RestangularProvider.setBaseUrl(ENV.apiUrl);
      RestangularProvider.setDefaultHeaders({
        'Content-Type': 'application/json;charset=UTF-8',
        'Accept': 'application/json,text/plain;version=1'
      })
    })

    .config(function($authProvider, ENV) {
      $authProvider.configure({
        apiUrl: ENV.apiHost,
        validateOnPageLoad: true,
        passwordResetSuccessUrl: '/password/change',
        authProviderPaths: {
          google_oauth2: '/auth/google_oauth2'
        }
      });
    })

    .constant('USER_ROLES', {
      all: '*',
      admin: 'admin',
      guest: 'guest'
    })

    .run(function ($rootScope, $location) {

    });

window.requestAnimationFrame = (function (){
  return window.requestAnimationFrame ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame ||
          window.oRequestAnimationFrame ||
          window.msRequestAnimationFrame ||
          function(cb, el) {
            window.setTimeout(cb, 1000 / 60)
          };
})();

window.AudioContext = window.AudioContext || window.webkitAudioContext;

navigator.getUserMedia =
    (navigator.webkitGetUserMedia ||
    navigator.mozGetUserMedia ||
    navigator.msGetUserMedia);
<commit_msg>prepend window.location.origin to password reset success url<commit_after>angular.module('app',
    ['ngMessages',
      'ipCookie',
      'ngResource',
      'restangular',
      'ui.bootstrap',
      'ui.router',
      'ng-token-auth',
      'app.auth',
      'app.utils',
      'ui.gravatar',
      'angulartics',
      'angulartics.google.analytics'])

    .config(function ($stateProvider, $locationProvider, $urlRouterProvider, gravatarServiceProvider) {

      // NOTE: If you're going to use html5 pushstate, you'll need to configure your webserver(s) to route to index.html, except for static assets
      $locationProvider.html5Mode(true);
      $urlRouterProvider.otherwise('/home');

      function authRoute($auth, $state, $rootScope) {
        return $auth.validateUser()
          .catch(function(res) {
            //TODO: also open the login modal
            $state.go('home');
            $rootScope.$emit('navbar:openLoginModal');
          });
      }

      $stateProvider
          .state('home', {
            url: "/home",
            templateUrl: "home.html",
            controller: 'HomeCtrl'
          })

          .state('error', {
            url: "/error",
            templateUrl: "error.html",
            controller: 'HomeCtrl'
          })

          .state('password-reset', {
            url: "/password/reset",
            templateUrl: "auth/password-reset.html",
            controller: 'PasswordResetCtrl'
          })

          .state('password-change', {
            url: "/password/change",
            templateUrl: "auth/password-change.html",
            controller: 'PasswordChangeCtrl',
            resolve: {
              auth: authRoute
            }
          })

          .state('users', {
            url: "/users",
            templateUrl: "users/index.html",
            controller: function ($scope, users) {
              $scope.users = users;
            },
            resolve: {
              auth: authRoute,
              users: function(Users) {
                return Users.getList();
              }
            }
          })

          .state('users-profile', {
            url: '/users/{userId:int}',
            templateUrl: 'users/profile.html',
            controller: function ($scope, user) {
              $scope.user = user;
            },
            resolve: {
              auth: authRoute,
              user: function($stateParams, Users) {
                return Users.one($stateParams.userId).get();
              }
            }
          })

          .state('users-profile-edit', {
            url: '/users/{userId:int}/edit',
            templateUrl: 'users/edit.html',
            controller: function ($scope, $state, user) {
              $scope.validName = /^[a-zA-Z0-9\s]+$/;
              $scope.user = user;
              $scope.submit = function() {
                $scope.user.save().then(function(res) {
                  $state.go('users-profile', {userId: $scope.user.id});
                });
              };
            },
            resolve: {
              auth: authRoute,
              user: function($stateParams, Users) {
                return Users.one($stateParams.userId).get();
              }
            }
          })

          .state('sounds.detail', {
            url: "/sounds/{soundId:int}",
            templateUrl: "sounds/detail.html",
            controller: function($scope, Sounds) {

            },
            resolve: {
              auth: authRoute
            }
          })

          .state('sounds.detail.sound', {

          })

          .state('artists', {
            url: "/artists",
            abstract: true,
            template: '<ui-view/>',
            resolve: {
              auth: authRoute
            }
          })

          .state('artists.list', {
            url: "/list",
            templateUrl: "artists/index.html",
            resolve: {
              artists: function (Artists) { return Artists.getList(); }
            },
            controller: function ($scope, artists) {
              $scope.artists = artists;
            }
          })

          //TODO: change artist urls to reference their name
          .state('artists.detail', {
            url: '/{artistId:int}',
            templateUrl: "artists/detail.html",
            resolve: {
              artist: function ($stateParams, Artists) { return Artists.one($stateParams.artistId).get(); },
              audio: function (SpectrogramAudio) { return SpectrogramAudio; },
              mic: function (SpectrogramMic) { return SpectrogramMic; }
            },
            controller: 'SpectroCtrl'
          })

          .state('artists.detail.sound', {
            url: '/sounds/{soundId:int}',
            templateUrl: "artists/sound.html",
            resolve: {
              sound: function ($stateParams, Sounds) { return Sounds.one($stateParams.soundId).get(); }
            },
            controller: 'SpectroSoundsCtrl'
          });

      gravatarServiceProvider.defaults = {
        size: 100,
        default: 'retro'
      };
    })

    .constant('ENV', {
      //TODO: update so host is separate from url
      apiHost: '<%= api_protocol %>://<%= api_url %>',
      apiUrl: '<%= api_protocol %>://<%= api_url %>/api/v1'
    })

    .config(function(RestangularProvider, ENV) {
      RestangularProvider.setBaseUrl(ENV.apiUrl);
      RestangularProvider.setDefaultHeaders({
        'Content-Type': 'application/json;charset=UTF-8',
        'Accept': 'application/json,text/plain;version=1'
      })
    })

    .config(function($authProvider, ENV) {
      $authProvider.configure({
        apiUrl: ENV.apiHost,
        validateOnPageLoad: true,
        passwordResetSuccessUrl: window.location.origin + '/password/change',
        authProviderPaths: {
          google_oauth2: '/auth/google_oauth2'
        }
      });
    })

    .constant('USER_ROLES', {
      all: '*',
      admin: 'admin',
      guest: 'guest'
    })

    .run(function ($rootScope, $location) {

    });

window.requestAnimationFrame = (function (){
  return window.requestAnimationFrame ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame ||
          window.oRequestAnimationFrame ||
          window.msRequestAnimationFrame ||
          function(cb, el) {
            window.setTimeout(cb, 1000 / 60)
          };
})();

window.AudioContext = window.AudioContext || window.webkitAudioContext;

navigator.getUserMedia =
    (navigator.webkitGetUserMedia ||
    navigator.mozGetUserMedia ||
    navigator.msGetUserMedia);
<|endoftext|>


<commit_before>'use strict';

/* Controllers */

angular.module('MarvelJSApp.controllers', [])
.controller('navigationCtrl',function($scope, Setup, $i18next, $window, $location) {
	$scope.appname = Setup.app;
	$scope.messageurl = "http://marvel.com";
	$scope.messagetxt = "Data provided by Marvel. © 2014 MARVEL";
	$(window).bind('resize', function() {
		if ($window.innerWidth < 768) {
			$scope.menuShow = false;
		} else {
			$scope.menuShow = true;
		}
		$scope.$apply();
	});
	$scope.menuShow = true;
	$scope.toggleMenu = function() {
		$scope.menuShow = !$scope.menuShow;
	};
	$scope.menuitems = [ {
		path: 'comics',
		faimg: 'fa-file-image-o',
		title: 'Comics'
	}, {
		path: 'characters',
		faimg: 'fa-female',
		title: 'Characters'
	}, {
		path: 'creators',
		faimg: 'fa-graduation-cap',
		title: 'Creators'
	}, {
		path: 'events',
		faimg: 'fa-eye',
		title: 'Events'
	}, {
		path: 'series',
		faimg: 'fa-trophy',
		title: 'Series'
	}, {
		path: 'stories',
		faimg: 'fa-video-camera',
		title: 'Stories'
	}, {
		path: 'config',
		faimg: 'fa-edit',
		title: 'Settings'
	}, {
		path: 'conclusion',
		faimg: 'fa-life-ring',
		title: 'Conclusion'
	} ];
	$scope.isActive = function (viewLocation) {
		var active = (viewLocation === $location.path());
		return active;
	};
})
.controller('characterCtrl',function($scope, $i18next, marvelAPIservice) {
	$scope.characterList = [];
	$scope.myPageItemsCount = 0;
	$scope.myItemsTotalCount = 0;
	marvelAPIservice.getCharacters().success(function(response) {
		$scope.myPageItemsCount = response.data.count;
		$scope.myItemsTotalCount = response.data.total;
		$scope.characterList = response.data.results;
	});
	$scope.onServerSideItemsRequested = function(currentPage, pageItems, filterBy, filterByFields, orderBy, orderByReverse) {
		marvelAPIservice.getCharacters(currentPage * pageItems, pageItems).success(function(response) {
			$scope.myPageItemsCount = response.data.count;
			$scope.myItemsTotalCount = response.data.total;
			$scope.characterList = response.data.results;
		});
	}
	$scope.mySelectedItems = [];
	$scope.$watch("mySelectedItems.length", function(newLength){
	  console.log($scope.mySelectedItems);
	});
})
.controller('creatorsCtrl',function($scope, $i18next, marvelAPIservice) {
	$scope.creatorList = [];
	$scope.myPageItemsCount = 0;
	$scope.myItemsTotalCount = 0;
	marvelAPIservice.getCreators().success(function(response) {
		$scope.myPageItemsCount = response.data.count;
		$scope.myItemsTotalCount = response.data.total;
		$scope.creatorList = response.data.results;
	});
	$scope.onServerSideItemsRequested = function(currentPage, pageItems, filterBy, filterByFields, orderBy, orderByReverse) {
		marvelAPIservice.getCreators(currentPage * pageItems, pageItems).success(function(response) {
			$scope.myPageItemsCount = response.data.count;
			$scope.myItemsTotalCount = response.data.total;
			$scope.creatorList = response.data.results;
		});
	}
	$scope.mySelectedItems = [];
	$scope.$watch("mySelectedItems.length", function(newLength){
	  console.log($scope.mySelectedItems);
	});
})
.controller('eventsCtrl',function($scope, $i18next, marvelAPIservice) {
	$scope.eventsList = [];
	$scope.myPageItemsCount = 0;
	$scope.myItemsTotalCount = 0;
	marvelAPIservice.getEvents().success(function(response) {
		$scope.myPageItemsCount = response.data.count;
		$scope.myItemsTotalCount = response.data.total;
		$scope.eventsList = response.data.results;
	});
	$scope.onServerSideItemsRequested = function(currentPage, pageItems, filterBy, filterByFields, orderBy, orderByReverse) {
		marvelAPIservice.getEvents(currentPage * pageItems, pageItems).success(function(response) {
			$scope.myPageItemsCount = response.data.count;
			$scope.myItemsTotalCount = response.data.total;
			$scope.eventsList = response.data.results;
		});
	}
	$scope.mySelectedItems = [];
	$scope.$watch("mySelectedItems.length", function(newLength){
	  console.log($scope.mySelectedItems);
	});
})
.controller('seriesCtrl',function($scope, $i18next, marvelAPIservice) {
	$scope.seriesList = [];
	$scope.myPageItemsCount = 0;
	$scope.myItemsTotalCount = 0;
	marvelAPIservice.getSeries().success(function(response) {
		$scope.myPageItemsCount = response.data.count;
		$scope.myItemsTotalCount = response.data.total;
		$scope.seriesList = response.data.results;
	});
	$scope.onServerSideItemsRequested = function(currentPage, pageItems, filterBy, filterByFields, orderBy, orderByReverse) {
		marvelAPIservice.getSeries(currentPage * pageItems, pageItems).success(function(response) {
			$scope.myPageItemsCount = response.data.count;
			$scope.myItemsTotalCount = response.data.total;
			$scope.seriesList = response.data.results;
		});
	}
	$scope.mySelectedItems = [];
	$scope.$watch("mySelectedItems.length", function(newLength){
	  console.log($scope.mySelectedItems);
	});
})
.controller('storiesCtrl',function($scope, $i18next, marvelAPIservice) {
	$scope.storiesList = [];
	$scope.myPageItemsCount = 0;
	$scope.myItemsTotalCount = 0;
	marvelAPIservice.getStories().success(function(response) {
		$scope.myPageItemsCount = response.data.count;
		$scope.myItemsTotalCount = response.data.total;
		$scope.storiesList = response.data.results;
	});
	$scope.onServerSideItemsRequested = function(currentPage, pageItems, filterBy, filterByFields, orderBy, orderByReverse) {
		marvelAPIservice.getStories(currentPage * pageItems, pageItems).success(function(response) {
			$scope.myPageItemsCount = response.data.count;
			$scope.myItemsTotalCount = response.data.total;
			$scope.storiesList = response.data.results;
		});
	}
	$scope.mySelectedItems = [];
	$scope.$watch("mySelectedItems.length", function(newLength){
	  console.log($scope.mySelectedItems);
	});
})
.controller('conclusionCtrl',function($scope, $i18next) {
	$scope.evaledList = [
	  {
		name: 'Tablesaw',
		url: 'http://filamentgroup.com/lab/tablesaw.html'
	  },
	  {
		name: 'angularjs_datatables',
		url: 'http://l-lin.github.io/angular-datatables/#/welcome'
	  },
	  {
		name: 'SmartTables',
		url: 'https://github.com/lorenzofox3/Smart-Table'
	  },
	  {
		name: 'trNgGrid',
		url: 'http://moonstorm.github.io/trNgGrid/release/'
	  },
	  {
		name: 'adapt_strap',
		url: 'http://adaptv.github.io/adapt-strap/',
	  }
	];
	$scope.conclusionList = {
		ajsnative: {
			Tablesaw: 0.2,
			angularjs_datatables: 0.5,
			SmartTables: 1,
			trNgGrid: 1,
			adapt_strap: 1
		},
		nojquery: {
			Tablesaw: 0,
			angularjs_datatables: 0,
			SmartTables: 1,
			trNgGrid: 1,
			adapt_strap: 1
		},
		responsive: {
			Tablesaw: 1,
			angularjs_datatables: 0,
			SmartTables: 0.8,
			trNgGrid: 0,
			adapt_strap: 0
		},
		inlineedit: {
			Tablesaw: 0,
			angularjs_datatables: 1,
			SmartTables: 0,
			trNgGrid: 0,
			adapt_strap: 0
		},
		customcell: {
			Tablesaw: 1,
			angularjs_datatables: 1,
			SmartTables: 1,
			trNgGrid: 1,
			adapt_strap: 0
		},
		paging: {
			Tablesaw: 1,
			angularjs_datatables: 1,
			SmartTables: 1,
			trNgGrid: 1,
			adapt_strap: 1
		},
		rest: {
			Tablesaw: 1,
			angularjs_datatables: 1,
			SmartTables: 1,
			trNgGrid: 1,
			adapt_strap: 1
		},
		search: {
			Tablesaw: 0,
			angularjs_datatables: 1,
			SmartTables: 1,
			trNgGrid: 1,
			adapt_strap: 1
		},
		easy: {
			Tablesaw: 0.4,
			angularjs_datatables: 0.2,
			SmartTables: 0.5,
			trNgGrid: 1,
			adapt_strap: 0.5
		},
		features: {
			Tablesaw: 0.4,
			angularjs_datatables: 1,
			SmartTables: 0.8,
			trNgGrid: 0.8,
			adapt_strap: 0.6
		},
		maturity: {
			Tablesaw: 0.6,
			angularjs_datatables: 0.9,
			SmartTables: 0.9,
			trNgGrid: 0.8,
			adapt_strap: 0.4
		}
	  };
	var ob  = {};
	for(var rdos in $scope.evaledList){
		var ename =$scope.evaledList[rdos].name;
		var sum = 0;
		for (var vals in $scope.conclusionList) {
			sum = sum + $scope.conclusionList[vals][ename];
		}
		ob[ename] = Math.round(sum*10)/10;
	}
	$scope.resultSum = ob;
})
.controller('configCtrl',function($scope, $i18next, $filter, marvelAPIservice, marvelAPIInvalidKeys) {
	$scope.langs = [ {
		name : i18n.t('English'),
		code : 'en'
	}, {
		name : i18n.t('Spanish'),
		code : 'es'
	}];
	var found = $filter('getById')($scope.langs, $i18next.options.lng, 'code');
	if (found!=null) {
		$scope.currentLang = found;
	} else {
		$scope.currentLang = $scope.langs[0];
	}
	$scope.mvpublickey = marvelAPIservice.getPublicKey();
	$scope.mvprivatekey = marvelAPIservice.getPrivateKey();
	$scope.$watch("mvpublickey", function(newval, oldval){
		marvelAPIservice.setPublicKey(newval);
		marvelAPIservice.setConfigured();
	});
	$scope.$watch("mvprivatekey", function(newval, oldval){
		marvelAPIservice.setPrivateKey(newval);
		marvelAPIservice.setConfigured();
	});
	$scope.MarvelAPIConfigured = marvelAPIservice.isConfigured();
	$scope.MarvelAPIKeys = marvelAPIInvalidKeys.hasInvalidKeys();
})
.controller('comicsCtrl',function($scope, marvelAPIservice, $i18next) {
	$scope.comicsList = [];
	$scope.myPageItemsCount = 0;
	$scope.myItemsTotalCount = 0;
	marvelAPIservice.getComics().success(function(response) {
		$scope.myPageItemsCount = response.data.count;
		$scope.myItemsTotalCount = response.data.total;
		$scope.comicsList = response.data.results;
	});
	$scope.onServerSideItemsRequested = function(currentPage, pageItems, filterBy, filterByFields, orderBy, orderByReverse) {
		marvelAPIservice.getComics(currentPage * pageItems, pageItems).success(function(response) {
			$scope.myPageItemsCount = response.data.count;
			$scope.myItemsTotalCount = response.data.total;
			$scope.comicsList = response.data.results;
		});
	}
	$scope.mySelectedItems = [];
	$scope.$watch("mySelectedItems.length", function(newLength){
	  console.log($scope.mySelectedItems);
	});
})
.controller('comicCtrl', function($scope, marvelAPIservice) {
	$scope.id = $routeParams.id;
	$scope.events = [];
	$scope.creators = [];
	$scope.comic = null;

	marvelAPIservice.getComicDetails($scope.id).success(function (response) {
		$scope.comic = response.data.results[0];
		$scope.creators = $scope.comic.creators.items;
	});
	//marvelAPIservice.getComicCreators($scope.id).success(function (response) {
	//	$scope.creators = response.MRData.RaceTable.Races;
	//});
	//marvelAPIservice.getComicEvents($scope.id).success(function (response) {
	//	$scope.events = response.MRData.RaceTable.Races;
	//});
});
<commit_msg>recover changelanguage function eliminated by mistake in previous cleanup<commit_after>'use strict';

/* Controllers */

angular.module('MarvelJSApp.controllers', [])
.controller('navigationCtrl',function($scope, Setup, $i18next, $window, $location) {
	$scope.appname = Setup.app;
	$scope.messageurl = "http://marvel.com";
	$scope.messagetxt = "Data provided by Marvel. © 2014 MARVEL";
	$(window).bind('resize', function() {
		if ($window.innerWidth < 768) {
			$scope.menuShow = false;
		} else {
			$scope.menuShow = true;
		}
		$scope.$apply();
	});
	$scope.menuShow = true;
	$scope.toggleMenu = function() {
		$scope.menuShow = !$scope.menuShow;
	};
	$scope.menuitems = [ {
		path: 'comics',
		faimg: 'fa-file-image-o',
		title: 'Comics'
	}, {
		path: 'characters',
		faimg: 'fa-female',
		title: 'Characters'
	}, {
		path: 'creators',
		faimg: 'fa-graduation-cap',
		title: 'Creators'
	}, {
		path: 'events',
		faimg: 'fa-eye',
		title: 'Events'
	}, {
		path: 'series',
		faimg: 'fa-trophy',
		title: 'Series'
	}, {
		path: 'stories',
		faimg: 'fa-video-camera',
		title: 'Stories'
	}, {
		path: 'config',
		faimg: 'fa-edit',
		title: 'Settings'
	}, {
		path: 'conclusion',
		faimg: 'fa-life-ring',
		title: 'Conclusion'
	} ];
	$scope.isActive = function (viewLocation) {
		var active = (viewLocation === $location.path());
		return active;
	};
})
.controller('characterCtrl',function($scope, $i18next, marvelAPIservice) {
	$scope.characterList = [];
	$scope.myPageItemsCount = 0;
	$scope.myItemsTotalCount = 0;
	marvelAPIservice.getCharacters().success(function(response) {
		$scope.myPageItemsCount = response.data.count;
		$scope.myItemsTotalCount = response.data.total;
		$scope.characterList = response.data.results;
	});
	$scope.onServerSideItemsRequested = function(currentPage, pageItems, filterBy, filterByFields, orderBy, orderByReverse) {
		marvelAPIservice.getCharacters(currentPage * pageItems, pageItems).success(function(response) {
			$scope.myPageItemsCount = response.data.count;
			$scope.myItemsTotalCount = response.data.total;
			$scope.characterList = response.data.results;
		});
	}
	$scope.mySelectedItems = [];
	$scope.$watch("mySelectedItems.length", function(newLength){
	  console.log($scope.mySelectedItems);
	});
})
.controller('creatorsCtrl',function($scope, $i18next, marvelAPIservice) {
	$scope.creatorList = [];
	$scope.myPageItemsCount = 0;
	$scope.myItemsTotalCount = 0;
	marvelAPIservice.getCreators().success(function(response) {
		$scope.myPageItemsCount = response.data.count;
		$scope.myItemsTotalCount = response.data.total;
		$scope.creatorList = response.data.results;
	});
	$scope.onServerSideItemsRequested = function(currentPage, pageItems, filterBy, filterByFields, orderBy, orderByReverse) {
		marvelAPIservice.getCreators(currentPage * pageItems, pageItems).success(function(response) {
			$scope.myPageItemsCount = response.data.count;
			$scope.myItemsTotalCount = response.data.total;
			$scope.creatorList = response.data.results;
		});
	}
	$scope.mySelectedItems = [];
	$scope.$watch("mySelectedItems.length", function(newLength){
	  console.log($scope.mySelectedItems);
	});
})
.controller('eventsCtrl',function($scope, $i18next, marvelAPIservice) {
	$scope.eventsList = [];
	$scope.myPageItemsCount = 0;
	$scope.myItemsTotalCount = 0;
	marvelAPIservice.getEvents().success(function(response) {
		$scope.myPageItemsCount = response.data.count;
		$scope.myItemsTotalCount = response.data.total;
		$scope.eventsList = response.data.results;
	});
	$scope.onServerSideItemsRequested = function(currentPage, pageItems, filterBy, filterByFields, orderBy, orderByReverse) {
		marvelAPIservice.getEvents(currentPage * pageItems, pageItems).success(function(response) {
			$scope.myPageItemsCount = response.data.count;
			$scope.myItemsTotalCount = response.data.total;
			$scope.eventsList = response.data.results;
		});
	}
	$scope.mySelectedItems = [];
	$scope.$watch("mySelectedItems.length", function(newLength){
	  console.log($scope.mySelectedItems);
	});
})
.controller('seriesCtrl',function($scope, $i18next, marvelAPIservice) {
	$scope.seriesList = [];
	$scope.myPageItemsCount = 0;
	$scope.myItemsTotalCount = 0;
	marvelAPIservice.getSeries().success(function(response) {
		$scope.myPageItemsCount = response.data.count;
		$scope.myItemsTotalCount = response.data.total;
		$scope.seriesList = response.data.results;
	});
	$scope.onServerSideItemsRequested = function(currentPage, pageItems, filterBy, filterByFields, orderBy, orderByReverse) {
		marvelAPIservice.getSeries(currentPage * pageItems, pageItems).success(function(response) {
			$scope.myPageItemsCount = response.data.count;
			$scope.myItemsTotalCount = response.data.total;
			$scope.seriesList = response.data.results;
		});
	}
	$scope.mySelectedItems = [];
	$scope.$watch("mySelectedItems.length", function(newLength){
	  console.log($scope.mySelectedItems);
	});
})
.controller('storiesCtrl',function($scope, $i18next, marvelAPIservice) {
	$scope.storiesList = [];
	$scope.myPageItemsCount = 0;
	$scope.myItemsTotalCount = 0;
	marvelAPIservice.getStories().success(function(response) {
		$scope.myPageItemsCount = response.data.count;
		$scope.myItemsTotalCount = response.data.total;
		$scope.storiesList = response.data.results;
	});
	$scope.onServerSideItemsRequested = function(currentPage, pageItems, filterBy, filterByFields, orderBy, orderByReverse) {
		marvelAPIservice.getStories(currentPage * pageItems, pageItems).success(function(response) {
			$scope.myPageItemsCount = response.data.count;
			$scope.myItemsTotalCount = response.data.total;
			$scope.storiesList = response.data.results;
		});
	}
	$scope.mySelectedItems = [];
	$scope.$watch("mySelectedItems.length", function(newLength){
	  console.log($scope.mySelectedItems);
	});
})
.controller('conclusionCtrl',function($scope, $i18next) {
	$scope.evaledList = [
	  {
		name: 'Tablesaw',
		url: 'http://filamentgroup.com/lab/tablesaw.html'
	  },
	  {
		name: 'angularjs_datatables',
		url: 'http://l-lin.github.io/angular-datatables/#/welcome'
	  },
	  {
		name: 'SmartTables',
		url: 'https://github.com/lorenzofox3/Smart-Table'
	  },
	  {
		name: 'trNgGrid',
		url: 'http://moonstorm.github.io/trNgGrid/release/'
	  },
	  {
		name: 'adapt_strap',
		url: 'http://adaptv.github.io/adapt-strap/',
	  }
	];
	$scope.conclusionList = {
		ajsnative: {
			Tablesaw: 0.2,
			angularjs_datatables: 0.5,
			SmartTables: 1,
			trNgGrid: 1,
			adapt_strap: 1
		},
		nojquery: {
			Tablesaw: 0,
			angularjs_datatables: 0,
			SmartTables: 1,
			trNgGrid: 1,
			adapt_strap: 1
		},
		responsive: {
			Tablesaw: 1,
			angularjs_datatables: 0,
			SmartTables: 0.8,
			trNgGrid: 0,
			adapt_strap: 0
		},
		inlineedit: {
			Tablesaw: 0,
			angularjs_datatables: 1,
			SmartTables: 0,
			trNgGrid: 0,
			adapt_strap: 0
		},
		customcell: {
			Tablesaw: 1,
			angularjs_datatables: 1,
			SmartTables: 1,
			trNgGrid: 1,
			adapt_strap: 0
		},
		paging: {
			Tablesaw: 1,
			angularjs_datatables: 1,
			SmartTables: 1,
			trNgGrid: 1,
			adapt_strap: 1
		},
		rest: {
			Tablesaw: 1,
			angularjs_datatables: 1,
			SmartTables: 1,
			trNgGrid: 1,
			adapt_strap: 1
		},
		search: {
			Tablesaw: 0,
			angularjs_datatables: 1,
			SmartTables: 1,
			trNgGrid: 1,
			adapt_strap: 1
		},
		easy: {
			Tablesaw: 0.4,
			angularjs_datatables: 0.2,
			SmartTables: 0.5,
			trNgGrid: 1,
			adapt_strap: 0.5
		},
		features: {
			Tablesaw: 0.4,
			angularjs_datatables: 1,
			SmartTables: 0.8,
			trNgGrid: 0.8,
			adapt_strap: 0.6
		},
		maturity: {
			Tablesaw: 0.6,
			angularjs_datatables: 0.9,
			SmartTables: 0.9,
			trNgGrid: 0.8,
			adapt_strap: 0.4
		}
	  };
	var ob  = {};
	for(var rdos in $scope.evaledList){
		var ename =$scope.evaledList[rdos].name;
		var sum = 0;
		for (var vals in $scope.conclusionList) {
			sum = sum + $scope.conclusionList[vals][ename];
		}
		ob[ename] = Math.round(sum*10)/10;
	}
	$scope.resultSum = ob;
})
.controller('configCtrl',function($scope, $i18next, $filter, marvelAPIservice, marvelAPIInvalidKeys) {
	$scope.langs = [ {
		name : i18n.t('English'),
		code : 'en'
	}, {
		name : i18n.t('Spanish'),
		code : 'es'
	}];
	$scope.changeLanguage = function (lng) {
		$i18next.options.lng=lng.code;
	}
	var found = $filter('getById')($scope.langs, $i18next.options.lng, 'code');
	if (found!=null) {
		$scope.currentLang = found;
	} else {
		$scope.currentLang = $scope.langs[0];
	}
	$scope.mvpublickey = marvelAPIservice.getPublicKey();
	$scope.mvprivatekey = marvelAPIservice.getPrivateKey();
	$scope.$watch("mvpublickey", function(newval, oldval){
		marvelAPIservice.setPublicKey(newval);
		marvelAPIservice.setConfigured();
	});
	$scope.$watch("mvprivatekey", function(newval, oldval){
		marvelAPIservice.setPrivateKey(newval);
		marvelAPIservice.setConfigured();
	});
	$scope.MarvelAPIConfigured = marvelAPIservice.isConfigured();
	$scope.MarvelAPIKeys = marvelAPIInvalidKeys.hasInvalidKeys();
})
.controller('comicsCtrl',function($scope, marvelAPIservice, $i18next) {
	$scope.comicsList = [];
	$scope.myPageItemsCount = 0;
	$scope.myItemsTotalCount = 0;
	marvelAPIservice.getComics().success(function(response) {
		$scope.myPageItemsCount = response.data.count;
		$scope.myItemsTotalCount = response.data.total;
		$scope.comicsList = response.data.results;
	});
	$scope.onServerSideItemsRequested = function(currentPage, pageItems, filterBy, filterByFields, orderBy, orderByReverse) {
		marvelAPIservice.getComics(currentPage * pageItems, pageItems).success(function(response) {
			$scope.myPageItemsCount = response.data.count;
			$scope.myItemsTotalCount = response.data.total;
			$scope.comicsList = response.data.results;
		});
	}
	$scope.mySelectedItems = [];
	$scope.$watch("mySelectedItems.length", function(newLength){
	  console.log($scope.mySelectedItems);
	});
})
.controller('comicCtrl', function($scope, marvelAPIservice) {
	$scope.id = $routeParams.id;
	$scope.events = [];
	$scope.creators = [];
	$scope.comic = null;

	marvelAPIservice.getComicDetails($scope.id).success(function (response) {
		$scope.comic = response.data.results[0];
		$scope.creators = $scope.comic.creators.items;
	});
	//marvelAPIservice.getComicCreators($scope.id).success(function (response) {
	//	$scope.creators = response.MRData.RaceTable.Races;
	//});
	//marvelAPIservice.getComicEvents($scope.id).success(function (response) {
	//	$scope.events = response.MRData.RaceTable.Races;
	//});
});
<|endoftext|>


<commit_before>"use strict";

function TaskListController($scope) {
    var self = this,
        tasks = $scope.tasks = [];

    $scope.addTask = function(newTask) {
        var title, duration;

        if (!newTask) { return; }

        title = self.getTitle(self.matchPattern, newTask.toString());
        duration = self.getDuration(self.matchPattern, newTask.toString());

        tasks.push({
            title: title,
            duration: duration,
            class: "",
            done: false
        });

        $scope.newTask = null;
    };

    $scope.editTask = function(task) {
        var title, duration;

        if (!task.title) {
            $scope.removeTask(task);
            return;
        }

        title = self.getTitle(self.matchPattern, task.title);
        duration = self.getDuration(self.matchPattern, task.title);

        task.title = title;
        task.duration = duration;
    };

    $scope.removeTask = function(task) {
        tasks.splice(tasks.indexOf(task), 1);
    };

    $scope.toggleTaskStatus = function(task) {
        task.done = !task.done;
        task.class =  (task.done) ? "task-done" : "";
    };

    // Prototype functions

    TaskListController.prototype.matchPattern = function (str) {
        return str.match(/(\s*[0-9]+h)?(\s*[0-9]+m)?$/);
    };

    TaskListController.prototype.getTitle = function(matcher, str) {
        var matchedInput, title;

        matchedInput = matcher(str);

        title = (matchedInput[0])
            ? matchedInput.input.replace(matchedInput[0], "")
            : matchedInput.input;

        return title;
    };

    TaskListController.prototype.getDuration = function(matcher, str) {
        var matchedInput, duration;

        matchedInput = matcher(str);

        duration = 0;

        if (matchedInput[1]) {
            var h = parseInt(matchedInput[1].replace(/\s|h/, ""));
            duration = h * 60;
        }

        if (matchedInput[2]) {
            var m = parseInt(matchedInput[2].replace(/\s|m/, ""));
            duration += m;
        }

        return duration;
    };

}
<commit_msg>Task edit bugfix<commit_after>"use strict";

function TaskListController($scope) {
    var self = this,
        tasks = $scope.tasks = [];

    $scope.addTask = function(newTask) {
        var title, duration;

        if (!newTask) { return; }

        title = self.getTitle(self.matchPattern, newTask.toString());
        duration = self.getDuration(self.matchPattern, newTask.toString());

        tasks.push({
            title: title,
            duration: duration,
            class: "",
            done: false
        });

        $scope.newTask = null;
    };

    $scope.editTask = function(task) {
        var title, duration;

        // delete task with empty title
        if (!task.title) {
            $scope.removeTask(task);
            return;
        }

        // return if duration hasn't changed
        if (!self.matchPattern(task.title)[0]) {
            return;
        }

        title = self.getTitle(self.matchPattern, task.title);
        duration = self.getDuration(self.matchPattern, task.title);

        task.title = title;
        task.duration = duration;
    };

    $scope.removeTask = function(task) {
        tasks.splice(tasks.indexOf(task), 1);
    };

    $scope.toggleTaskStatus = function(task) {
        task.done = !task.done;
        task.class =  (task.done) ? "task-done" : "";
    };

    // Prototype functions

    TaskListController.prototype.matchPattern = function (str) {
        return str.match(/(\s*[0-9]+h)?(\s*[0-9]+m)?$/);
    };

    TaskListController.prototype.getTitle = function(matcher, str) {
        var matchedInput, title;

        matchedInput = matcher(str);

        title = (matchedInput[0])
            ? matchedInput.input.replace(matchedInput[0], "")
            : matchedInput.input;

        return title;
    };

    TaskListController.prototype.getDuration = function(matcher, str) {
        var matchedInput, duration;

        matchedInput = matcher(str);

        duration = 0;

        if (matchedInput[1]) {
            var h = parseInt(matchedInput[1].replace(/\s|h/, ""));
            duration = h * 60;
        }

        if (matchedInput[2]) {
            var m = parseInt(matchedInput[2].replace(/\s|m/, ""));
            duration += m;
        }

        return duration;
    };

}
<|endoftext|>


<commit_before>// @flow

import React, { PropTypes, Component } from "react";
import type { Children } from "react";
import classnames from "classnames";
import Transition from "react-transition-group/Transition";
import "./Modal.css";

type ModalProps = {
  status: string,
  children?: Children,
  handleClose: () => any
};

export class Modal extends Component {
  props: ModalProps;

  constructor(props: ModalProps) {
    super(props);
    const self: any = this;
    self.onClick = this.onClick.bind(this);
  }

  onClick(e: SyntheticEvent) {
    e.stopPropagation();
  }

  render() {
    const { status } = this.props;

    return (

          {this.props.children}

    );
  }
}

Modal.displayName = "Modal";
Modal.contextTypes = {
  shortcuts: PropTypes.object
};

type SlideProps = {
  in: boolean,
  children?: Children,
  handleClose: () => any
};

export default function Slide({
  in: inProp,
  children,
  handleClose
}: SlideProps) {
  return (
    <Transition in={inProp} timeout={175} appear>
      {status => <Modal status={status} handleClose={handleClose}>{children}</Modal>}
    </Transition>
  );
}
<commit_msg>tweaks<commit_after>// @flow

import React, { PropTypes, Component } from "react";
import type { Children } from "react";
import classnames from "classnames";
import Transition from "react-transition-group/Transition";
import "./Modal.css";

type ModalProps = {
  status: string,
  children?: Children,
  handleClose: () => any
};

export class Modal extends Component {
  props: ModalProps;

  constructor(props: ModalProps) {
    super(props);
    const self: any = this;
    self.onClick = this.onClick.bind(this);
  }

  onClick(e: SyntheticEvent) {
    e.stopPropagation();
  }

  render() {
    const { status } = this.props;

    return (

          {this.props.children}

    );
  }
}

Modal.displayName = "Modal";
Modal.contextTypes = {
  shortcuts: PropTypes.object
};

type SlideProps = {
  in: boolean,
  children?: Children,
  handleClose: () => any
};

export default function Slide({
  in: inProp,
  children,
  handleClose
}: SlideProps) {
  return (
    <Transition in={inProp} timeout={175} appear>
      {status =>
        <Modal status={status} handleClose={handleClose}>
          {children}
        </Modal>}
    </Transition>
  );
}

Slide.displayName = "Slide";
<|endoftext|>