<commit_before>import React from 'react';

import { withStyles } from '@material-ui/core/styles';
//import { MdContactPhone } from 'react-icons/md';

import Avatar from '@material-ui/core/Avatar';
import Grid from '@material-ui/core/Grid';
import IconButton from '@material-ui/core/IconButton';
import LinearProgress from '@material-ui/core/LinearProgress';
import Paper from '@material-ui/core/Paper';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import TextField from '@material-ui/core/TextField';
import Typography from '@material-ui/core/Typography';

import AddIcon from '@material-ui/icons/Add';
import AddToPhotosIcon from '@material-ui/icons/AddToPhotos';
import BuildIcon from '@material-ui/icons/Build';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import DeleteForeverIcon from '@material-ui/icons/DeleteForever';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import HelpIcon from '@material-ui/icons/Help';
import PublishIcon from '@material-ui/icons/Publish';
import RefreshIcon from '@material-ui/icons/Refresh';

import { FaGithub as GithubIcon } from 'react-icons/fa';

import { blue } from '@material-ui/core/colors';
import { green } from '@material-ui/core/colors';

const styles = theme => ({
    root:{
        marginBottom: theme.spacing(2)
    },
    smallAvatar: {
        width: theme.spacing(3),
        height: theme.spacing(3)
    },
    table: {
        tableLayout: 'fixed',
        minWidth: 960,
        '& td': {
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            textOverflow: 'ellipsis'
        }
    },
    hidden: {
        visibility: 'hidden'
    },
    name: {
        flexWrap: 'nowrap',
        width: 300
    },
    description: {
        width: 600
    },
    keywords: {

    },
    installed: {
        width: 120
    },
    available: {
        width: 100
    },
    license: {
        width: 150
    },
    install:{
        width: 220
    },
    green: {
        color: green[500]
    },
    blue: {
        color: blue[700]
    },
    category: {
        backgroundColor: theme.palette.background.default,
    },
    grow: {
        flexGrow: 1
    }
});

class Adapters extends React.Component {

    constructor(props) {

        super(props);

        this.state = {
            lastUpdate: 0,
            repository: {},
            installed: {},
            instances: {},
            categories: [],
            hostData: {},
            hostOs: '',
            nodeJsVersion: '',
            init: false
        };

        this.t = props.t;
    }

    componentDidMount() {
        if(this.props.ready) {
            this.getAdaptersInfo(this.props.currentHost, true);
        }
    }

    componentDidUpdate() {
        if(!this.state.init && this.props.ready) {
            this.getAdaptersInfo(this.props.currentHost, true);
        }
    }

    async getAdaptersInfo(update, updateRepo = false) {
        if (!this.props.currentHost) {
            return;
        }

        if (update) {
            // Do not update too often
            if (new Date().getTime() - this.state.lastUpdate > 1000) {

                const currentHost = this.props.currentHost;

                try {
                    const hostData = await this.props.socket.getHostInfo(currentHost);
                    const nodeJsVersion = hostData['Node.js'].replace('v', '');
                    const hostOs = hostData.os;

                    const repository = await this.props.socket.getRepository(currentHost, {repo: this.props.systemConfig.common.activeRepo, update: updateRepo});
                    const installed = await this.props.socket.getInstalled(currentHost);
                    const instances = await this.props.socket.getAdapterInstances();
                    const categories = {};
                    const categoriesSorted = [];

                    Object.keys(installed).forEach(value => {

                        const adapter = installed[value];

                        if (!adapter.controller && value !== 'hosts') {
                            if (!repository[value]) {
                                repository[value] = adapter;
                            }
                        }
                    });

                    Object.keys(repository).forEach(value => {

                        const adapter = repository[value];

                        if (!adapter.controller) {

                            const type = adapter.type;
                            const installedInGroup = installed[value];

                            if (!categories[type]) {
                                categories[type] = {
                                    name: type,
                                    translation: this.t(type + '_group'),
                                    expanded: false,
                                    count: 1,
                                    installed: installedInGroup ? 1 : 0
                                };
                            } else {
                                categories[type].count++;
                                if (installedInGroup) {
                                    categories[type].installed++;
                                }
                            }
                        }
                    });

                    Object.keys(instances).forEach(value => {

                        const instance = instances[value];
                        const name = instance.common.name;
                        const enabled = instance.common.enabled;

                        if (installed[name]) {
                            if (installed[name].count) {
                                installed[name].count++;
                            } else {
                                installed[name].count = 1;
                            }

                            if (enabled) {
                                if (installed[name].enabled) {
                                    installed[name].enabled++;
                                } else {
                                    installed[name].enabled = 1;
                                }
                            }
                        }
                    });

                    Object.keys(categories).forEach(value => {
                        categoriesSorted.push(categories[value]);
                    });

                    categoriesSorted.sort((a, b) => {

                        const result = b.installed - a.installed;

                        return result !== 0 ? result : a.translation  b.translation ? 1 : 0;
                    });

                    this.setState({
                        lastUpdate: Date.now(),
                        hostData,
                        hostOs,
                        nodeJsVersion,
                        repository,
                        installed,
                        instances,
                        categories: categoriesSorted,
                        init: true
                    });
                } catch(error) {
                    console.error(error);
                }
            }
        }
    }

    addInstance(adapter) {
        if (this.props.expertMode) {
            /* TODO: Add Dialog */
        } else {
            this.props.executeCommand(`add ${adapter} --host ${this.props.currentHostName}`);
        }
    }

    upload(adapter) {
        this.props.executeCommand('upload ' + adapter);
    }

    rebuild(adapter) {
        this.props.executeCommand('rebuild ' + adapter)
    }

    toggleCategory(category) {

        const categories = this.state.categories;
        categories[category].expanded = !categories[category].expanded;

        this.setState({
            categories
        });
    }

    getRows() {
        const rows = [];
        const { classes } = this.props;

        Object.keys(this.state.categories).forEach(value => {

            const category = this.state.categories[value];
            const categoryName = category.name;

            rows.push(
                <TableRow
                    key={ categoryName }
                    className={ classes.category }
                >
                    <TableCell>
                        <Grid container spacing={ 1 } alignItems="center" className={ classes.name }>
                            <Grid item>
                                <IconButton
                                    size="small"
                                    onClick={ () => this.toggleCategory(value) }
                                >
                                    { category.expanded ? <ExpandMoreIcon /> : <ChevronRightIcon />}
                                </IconButton>
                            </Grid>
                            <Grid item>
                                { category.translation }
                            </Grid>
                        </Grid>
                    </TableCell>
                    <TableCell>
                        <Typography component="span" variant="body2" className={ classes.green }>
                            { category.installed }
                        </Typography>
                        { ` ${this.t('of')} ` }
                        <Typography component="span" variant="body2" className={ classes.blue }>
                            { category.count }
                        </Typography>
                        { ` ${this.t('Adapters from this Group installed')}` }
                    </TableCell>
                    <TableCell />
                    <TableCell />
                    <TableCell />
                    <TableCell />
                    <TableCell />
                </TableRow>
            );

            if (category.expanded) {

                Object.keys(this.state.repository).forEach(value => {

                    const adapter = this.state.repository[value];

                    if (!adapter.controller && adapter.type === categoryName) {

                        const installed = this.state.installed[value];

                        const title = (adapter.title.toString() || '').replace('ioBroker Visualisation - ', '');
                        const desc = adapter.desc ? adapter.desc[this.props.lang] || adapter.desc['en'] : '';
                        const image = installed ? installed.localIcon : adapter.extIcon;

                        if (title instanceof Object || !desc) {
                            console.log(adapter);
                        }

                        rows.push(
                            <TableRow
                                key={ value }
                                hover
                            >
                                <TableCell>
                                    <Grid container spacing={ 1 } alignItems="center" className={ classes.name }>
                                        <Grid item>
                                            <Avatar
                                                variant="square"
                                                alt={ title.toString() }
                                                src={ image }
                                                className={ classes.smallAvatar }
                                            />
                                        </Grid>
                                        <Grid item>
                                            { title.toString() }
                                        </Grid>
                                    </Grid>
                                </TableCell>
                                <TableCell>
                                    { desc }
                                </TableCell>
                                <TableCell>
                                    { adapter.keywords && adapter.keywords.join(' ') }
                                </TableCell>
                                <TableCell>
                                    { installed &&
                                        installed.version +
                                        (installed.count ? ` (${installed.count}${installed.count !== installed.enabled ? '~' : ''})` : '')
                                    }
                                </TableCell>
                                <TableCell>
                                    { adapter.version }
                                </TableCell>
                                <TableCell>
                                    { adapter.license }
                                </TableCell>
                                <TableCell>
                                    <IconButton
                                        size="small"
                                        onClick={ () => this.addInstance(value) }
                                    >
                                        <AddIcon />
                                    </IconButton>
                                    <IconButton size="small">
                                        <HelpIcon />
                                    </IconButton>
                                    { this.props.expertMode &&
                                        <IconButton
                                            size="small"
                                            className={ !installed ? classes.hidden : '' }
                                            onClick={ () => this.upload(value) }
                                        >
                                            <PublishIcon />
                                        </IconButton>
                                    }
                                    <IconButton size="small" className={ !installed ? classes.hidden : '' }>
                                        <DeleteForeverIcon />
                                    </IconButton>
                                    { this.props.expertMode &&
                                        <IconButton size="small" className={ !installed ? classes.hidden : '' }>
                                            <AddToPhotosIcon />
                                        </IconButton>
                                    }
                                    { this.props.expertMode &&
                                        <IconButton
                                            size="small"
                                            className={ !installed ? classes.hidden : '' }
                                            onClick={ () => this.rebuild(value) }
                                        >
                                            <BuildIcon />
                                        </IconButton>
                                    }
                                </TableCell>
                            </TableRow>
                        );
                    }
                });
            }
        });

        return rows;
    }

    render() {

        if (!this.state.init) {
            return <LinearProgress />
        }

        const { classes } = this.props;

        return (
            <Paper className={ classes.root }>
                <Grid
                    container
                    direction="column"
                    className={ classes.flexContainer }
                >
                    <Grid
                        item
                        container
                        alignItems="center"
                    >
                        <IconButton>
                            <RefreshIcon />
                        </IconButton>
                        <IconButton>
                            <GithubIcon />
                        </IconButton>

                        <TextField label={ this.t('Filter') } />

                    </Grid>
                    <TableContainer className={ classes.container }>

                            <TableHead>
                                <TableRow>
                                    <TableCell className={ classes.name }>
                                        <Typography>{ this.t('Name') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.description }>
                                        <Typography>{ this.t('Description') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.keywords }>
                                        <Typography>{ this.t('Keywords') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.installed }>
                                        <Typography>{ this.t('Installed') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.available }>
                                        <Typography>{ this.t('Available') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.license }>
                                        <Typography>{ this.t('License') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.install }>
                                        <Typography>{ this.t('Install') }</Typography>
                                    </TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                { this.getRows() }
                            </TableBody>

                    </TableContainer>
                </Grid>
            </Paper>
        );
    }
}

export default withStyles(styles)(Adapters);<commit_msg>Fixed repo update on init, added refresh function<commit_after>import React from 'react';

import { withStyles } from '@material-ui/core/styles';
//import { MdContactPhone } from 'react-icons/md';

import Avatar from '@material-ui/core/Avatar';
import Grid from '@material-ui/core/Grid';
import IconButton from '@material-ui/core/IconButton';
import LinearProgress from '@material-ui/core/LinearProgress';
import Paper from '@material-ui/core/Paper';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import TextField from '@material-ui/core/TextField';
import Typography from '@material-ui/core/Typography';

import AddIcon from '@material-ui/icons/Add';
import AddToPhotosIcon from '@material-ui/icons/AddToPhotos';
import BuildIcon from '@material-ui/icons/Build';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import DeleteForeverIcon from '@material-ui/icons/DeleteForever';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import HelpIcon from '@material-ui/icons/Help';
import PublishIcon from '@material-ui/icons/Publish';
import RefreshIcon from '@material-ui/icons/Refresh';

import { FaGithub as GithubIcon } from 'react-icons/fa';

import { blue } from '@material-ui/core/colors';
import { green } from '@material-ui/core/colors';

const styles = theme => ({
    root:{
        marginBottom: theme.spacing(2)
    },
    smallAvatar: {
        width: theme.spacing(3),
        height: theme.spacing(3)
    },
    table: {
        tableLayout: 'fixed',
        minWidth: 960,
        '& td': {
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            textOverflow: 'ellipsis'
        }
    },
    hidden: {
        visibility: 'hidden'
    },
    name: {
        flexWrap: 'nowrap',
        width: 300
    },
    description: {
        width: 600
    },
    keywords: {

    },
    installed: {
        width: 120
    },
    available: {
        width: 100
    },
    license: {
        width: 150
    },
    install:{
        width: 220
    },
    green: {
        color: green[500]
    },
    blue: {
        color: blue[700]
    },
    category: {
        backgroundColor: theme.palette.background.default,
    },
    grow: {
        flexGrow: 1
    }
});

class Adapters extends React.Component {

    constructor(props) {

        super(props);

        this.state = {
            lastUpdate: 0,
            repository: {},
            installed: {},
            instances: {},
            categories: [],
            hostData: {},
            hostOs: '',
            nodeJsVersion: '',
            init: false
        };

        this.t = props.t;
    }

    componentDidMount() {
        if(this.props.ready) {
            this.getAdaptersInfo(true);
        }
    }

    componentDidUpdate() {
        if(!this.state.init && this.props.ready) {
            this.getAdaptersInfo(true);
        }
    }

    async getAdaptersInfo(update, updateRepo = false) {
        if (!this.props.currentHost) {
            return;
        }

        if (update) {
            // Do not update too often
            if (new Date().getTime() - this.state.lastUpdate > 1000) {

                const currentHost = this.props.currentHost;

                try {
                    const hostData = await this.props.socket.getHostInfo(currentHost);
                    const nodeJsVersion = hostData['Node.js'].replace('v', '');
                    const hostOs = hostData.os;

                    const repository = await this.props.socket.getRepository(currentHost, {repo: this.props.systemConfig.common.activeRepo, update: updateRepo});
                    const installed = await this.props.socket.getInstalled(currentHost);
                    const instances = await this.props.socket.getAdapterInstances();
                    const categories = {};
                    const categoriesSorted = [];

                    Object.keys(installed).forEach(value => {

                        const adapter = installed[value];

                        if (!adapter.controller && value !== 'hosts') {
                            if (!repository[value]) {
                                repository[value] = adapter;
                            }
                        }
                    });

                    Object.keys(repository).forEach(value => {

                        const adapter = repository[value];

                        if (!adapter.controller) {

                            const type = adapter.type;
                            const installedInGroup = installed[value];

                            if (!categories[type]) {
                                categories[type] = {
                                    name: type,
                                    translation: this.t(type + '_group'),
                                    expanded: false,
                                    count: 1,
                                    installed: installedInGroup ? 1 : 0
                                };
                            } else {
                                categories[type].count++;
                                if (installedInGroup) {
                                    categories[type].installed++;
                                }
                            }
                        }
                    });

                    Object.keys(instances).forEach(value => {

                        const instance = instances[value];
                        const name = instance.common.name;
                        const enabled = instance.common.enabled;

                        if (installed[name]) {
                            if (installed[name].count) {
                                installed[name].count++;
                            } else {
                                installed[name].count = 1;
                            }

                            if (enabled) {
                                if (installed[name].enabled) {
                                    installed[name].enabled++;
                                } else {
                                    installed[name].enabled = 1;
                                }
                            }
                        }
                    });

                    Object.keys(categories).forEach(value => {
                        categoriesSorted.push(categories[value]);
                    });

                    categoriesSorted.sort((a, b) => {

                        const result = b.installed - a.installed;

                        return result !== 0 ? result : a.translation  b.translation ? 1 : 0;
                    });

                    this.setState({
                        lastUpdate: Date.now(),
                        hostData,
                        hostOs,
                        nodeJsVersion,
                        repository,
                        installed,
                        instances,
                        categories: categoriesSorted,
                        init: true
                    });
                } catch(error) {
                    console.error(error);
                }
            }
        }
    }

    addInstance(adapter) {
        if (this.props.expertMode) {
            /* TODO: Add Dialog */
        } else {
            this.props.executeCommand(`add ${adapter} --host ${this.props.currentHostName}`);
        }
    }

    upload(adapter) {
        this.props.executeCommand('upload ' + adapter);
    }

    rebuild(adapter) {
        this.props.executeCommand('rebuild ' + adapter)
    }

    toggleCategory(category) {

        const categories = this.state.categories;
        categories[category].expanded = !categories[category].expanded;

        this.setState({
            categories
        });
    }

    getRows() {
        const rows = [];
        const { classes } = this.props;

        Object.keys(this.state.categories).forEach(value => {

            const category = this.state.categories[value];
            const categoryName = category.name;

            rows.push(
                <TableRow
                    key={ categoryName }
                    className={ classes.category }
                >
                    <TableCell>
                        <Grid container spacing={ 1 } alignItems="center" className={ classes.name }>
                            <Grid item>
                                <IconButton
                                    size="small"
                                    onClick={ () => this.toggleCategory(value) }
                                >
                                    { category.expanded ? <ExpandMoreIcon /> : <ChevronRightIcon />}
                                </IconButton>
                            </Grid>
                            <Grid item>
                                { category.translation }
                            </Grid>
                        </Grid>
                    </TableCell>
                    <TableCell>
                        <Typography component="span" variant="body2" className={ classes.green }>
                            { category.installed }
                        </Typography>
                        { ` ${this.t('of')} ` }
                        <Typography component="span" variant="body2" className={ classes.blue }>
                            { category.count }
                        </Typography>
                        { ` ${this.t('Adapters from this Group installed')}` }
                    </TableCell>
                    <TableCell />
                    <TableCell />
                    <TableCell />
                    <TableCell />
                    <TableCell />
                </TableRow>
            );

            if (category.expanded) {

                Object.keys(this.state.repository).forEach(value => {

                    const adapter = this.state.repository[value];

                    if (!adapter.controller && adapter.type === categoryName) {

                        const installed = this.state.installed[value];

                        const title = (adapter.title.toString() || '').replace('ioBroker Visualisation - ', '');
                        const desc = adapter.desc ? adapter.desc[this.props.lang] || adapter.desc['en'] : '';
                        const image = installed ? installed.localIcon : adapter.extIcon;

                        if (title instanceof Object || !desc) {
                            console.log(adapter);
                        }

                        rows.push(
                            <TableRow
                                key={ value }
                                hover
                            >
                                <TableCell>
                                    <Grid container spacing={ 1 } alignItems="center" className={ classes.name }>
                                        <Grid item>
                                            <Avatar
                                                variant="square"
                                                alt={ title.toString() }
                                                src={ image }
                                                className={ classes.smallAvatar }
                                            />
                                        </Grid>
                                        <Grid item>
                                            { title.toString() }
                                        </Grid>
                                    </Grid>
                                </TableCell>
                                <TableCell>
                                    { desc }
                                </TableCell>
                                <TableCell>
                                    { adapter.keywords && adapter.keywords.join(' ') }
                                </TableCell>
                                <TableCell>
                                    { installed &&
                                        installed.version +
                                        (installed.count ? ` (${installed.count}${installed.count !== installed.enabled ? '~' : ''})` : '')
                                    }
                                </TableCell>
                                <TableCell>
                                    { adapter.version }
                                </TableCell>
                                <TableCell>
                                    { adapter.license }
                                </TableCell>
                                <TableCell>
                                    <IconButton
                                        size="small"
                                        onClick={ () => this.addInstance(value) }
                                    >
                                        <AddIcon />
                                    </IconButton>
                                    <IconButton size="small">
                                        <HelpIcon />
                                    </IconButton>
                                    { this.props.expertMode &&
                                        <IconButton
                                            size="small"
                                            className={ !installed ? classes.hidden : '' }
                                            onClick={ () => this.upload(value) }
                                        >
                                            <PublishIcon />
                                        </IconButton>
                                    }
                                    <IconButton size="small" className={ !installed ? classes.hidden : '' }>
                                        <DeleteForeverIcon />
                                    </IconButton>
                                    { this.props.expertMode &&
                                        <IconButton size="small" className={ !installed ? classes.hidden : '' }>
                                            <AddToPhotosIcon />
                                        </IconButton>
                                    }
                                    { this.props.expertMode &&
                                        <IconButton
                                            size="small"
                                            className={ !installed ? classes.hidden : '' }
                                            onClick={ () => this.rebuild(value) }
                                        >
                                            <BuildIcon />
                                        </IconButton>
                                    }
                                </TableCell>
                            </TableRow>
                        );
                    }
                });
            }
        });

        return rows;
    }

    render() {

        if (!this.state.init) {
            return <LinearProgress />
        }

        const { classes } = this.props;

        return (
            <Paper className={ classes.root }>
                <Grid
                    container
                    direction="column"
                    className={ classes.flexContainer }
                >
                    <Grid
                        item
                        container
                        alignItems="center"
                    >
                        <IconButton
                            onClick={ () => this.getAdaptersInfo(true, true) }
                        >
                            <RefreshIcon />
                        </IconButton>
                        <IconButton>
                            <GithubIcon />
                        </IconButton>

                        <TextField label={ this.t('Filter') } />

                    </Grid>
                    <TableContainer className={ classes.container }>

                            <TableHead>
                                <TableRow>
                                    <TableCell className={ classes.name }>
                                        <Typography>{ this.t('Name') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.description }>
                                        <Typography>{ this.t('Description') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.keywords }>
                                        <Typography>{ this.t('Keywords') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.installed }>
                                        <Typography>{ this.t('Installed') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.available }>
                                        <Typography>{ this.t('Available') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.license }>
                                        <Typography>{ this.t('License') }</Typography>
                                    </TableCell>
                                    <TableCell className={ classes.install }>
                                        <Typography>{ this.t('Install') }</Typography>
                                    </TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                { this.getRows() }
                            </TableBody>

                    </TableContainer>
                </Grid>
            </Paper>
        );
    }
}

export default withStyles(styles)(Adapters);<|endoftext|>


<commit_before>// Object.keys(require.cache).forEach(function(key) {
//   delete require.cache[key]
// });

var sep = require('path').sep;
var libFolder = __dirname + sep + 'lib' + sep;
var maximumPings = 1000;
var libFolder ;
var Mesh = require('../');

describe('a3 - Bounces a message between two components, demonstrates how the events layer works', function(done) {
///events/testComponent2Component/component1/maximum-pings-reached
///events/testComponent2Component/component1/maximum-pings-reached

  var config = {
    name:"testInjectionResponse",
    modules: {
      "module1":{
        path:libFolder + "12-module1",
        construct:{
          type:"sync",
          parameters:[
            {value:{maximumPings:maximumPings}}
          ]
        }
      }
    },
    components: {
      "component1": {
        moduleName:"module1"
      }
    }
  };

  var mesh;

  it('starts the mesh, listens for the ping pong completed event, that module1 emits', function(done) {

    mesh = new Mesh();

    this.timeout(6000);

    var onEventRef;

    mesh.initialize(config, function(err) {

      if (err) {
        console.log(err.stack);
        done(err);
      }else{
        mesh.exchange.component1.exposedMethod('a message', function(e, response){
          setTimeout(function(){
            done();
          }, 2000);
        });
      }
    });
  });

  after(function(done){
     mesh.stop(done);
  });

});

<commit_msg>upped timeout test a3<commit_after>// Object.keys(require.cache).forEach(function(key) {
//   delete require.cache[key]
// });

var sep = require('path').sep;
var libFolder = __dirname + sep + 'lib' + sep;
var maximumPings = 1000;
var libFolder ;
var Mesh = require('../');

describe('a3 - Bounces a message between two components, demonstrates how the events layer works', function(done) {
///events/testComponent2Component/component1/maximum-pings-reached
///events/testComponent2Component/component1/maximum-pings-reached

  var config = {
    name:"testInjectionResponse",
    modules: {
      "module1":{
        path:libFolder + "12-module1",
        construct:{
          type:"sync",
          parameters:[
            {value:{maximumPings:maximumPings}}
          ]
        }
      }
    },
    components: {
      "component1": {
        moduleName:"module1"
      }
    }
  };

  var mesh;

  it('starts the mesh, listens for the ping pong completed event, that module1 emits', function(done) {

    mesh = new Mesh();

    this.timeout(20000);

    var onEventRef;

    mesh.initialize(config, function(err) {

      if (err) {
        console.log(err.stack);
        done(err);
      }else{
        mesh.exchange.component1.exposedMethod('a message', function(e, response){
          setTimeout(function(){
            done();
          }, 2000);
        });
      }
    });
  });

  after(function(done){
     mesh.stop(done);
  });

});

<|endoftext|>


<commit_before>module('Constraint.BoundingPlane');

var ParticleSystem = Particulate.ParticleSystem;
var BoundingPlaneConstraint = Particulate.BoundingPlaneConstraint;
var Vec3 = Particulate.Vec3;

test('Creation', function () {
  var origin = [0, 1, 2];
  var normal = [0, 1, 0];
  var constraint = BoundingPlaneConstraint.create(origin, normal);

  Test.assert.equalArray(constraint.bufferVec3, [].concat(origin, normal),
    'Should initialize origin and normal vec3s.');
});

test('Application', function () {
  var system = ParticleSystem.create(2, 10);
  var origin = [5, 6, 7];
  var normal = [0, 0, 1];
  var constraint = BoundingPlaneConstraint.create(origin, normal);
  var pos = Vec3.create();

  system.setPosition(0, [10, 5, 20]);
  system.setPosition(1, [10, 10, 10]);
  system.addConstraint(constraint);
  system.tick(1);

  Test.assert.range(system.getPosition(0, pos)[2], origin[2], Infinity,
    'Should constrain particles behind plane.');
  Test.assert.equalArray(system.getPosition(1, pos), [10, 10, 10],
    'Should not affect particles in front of plane.');
});
<commit_msg>Improve BoundingPlaneConstraint tests<commit_after>module('Constraint.BoundingPlane');

var ParticleSystem = Particulate.ParticleSystem;
var BoundingPlaneConstraint = Particulate.BoundingPlaneConstraint;
var Vec3 = Particulate.Vec3;

test('Creation', function () {
  var origin = [0, 1, 2];
  var normal = [0, 1, 0];
  var constraint = BoundingPlaneConstraint.create(origin, normal);

  Test.assert.equalArray(constraint.bufferVec3, [].concat(origin, normal),
    'Should initialize origin and normal vec3s.');
});

test('Application', function () {
  var system = ParticleSystem.create(2, 10);
  var origin = [5, 6, 7];
  var normal = [0, 0, 1];
  var constraint = BoundingPlaneConstraint.create(origin, normal);
  var pos = Vec3.create();

  system.setPosition(0, [10, 5, 20]);
  system.setPosition(1, [10, 10, 10]);
  system.addConstraint(constraint);
  system.tick(1);

  Test.assert.range(system.getPosition(0, pos)[2], origin[2], Infinity,
    'Should constrain particles behind plane.');
  Test.assert.equalArray(system.getPosition(1, pos), [10, 10, 10],
    'Should not affect particles in front of plane.');
});

test('Application with distance influence', function () {
  var system = ParticleSystem.create(2, 10);
  var origin = [5, 6, 7];
  var normal = [0, 0, 1];
  var distance = Infinity;
  var constraint = BoundingPlaneConstraint.create(origin, normal, distance);
  var pos = Vec3.create();

  system.setPosition(0, [10, 5, 20]);
  system.setPosition(1, [10, 10, 10]);
  system.addConstraint(constraint);
  system.tick(1);

  Test.assert.close(system.getPosition(0, pos)[2], origin[2], 0.1,
    'Should constrain particles behind plane.');
  Test.assert.close(system.getPosition(1, pos)[2], origin[2], 0.1,
    'Should constrain particles in front of plane within distance influence.');
});
<|endoftext|>


<commit_before>'use strict';

const Promise = require('bluebird');
const CONST = require('../lib/constants');
const eventmesh = require('../lib/eventmesh');

const {
  Etcd3
} = require('etcd3');

describe.only('eventmesh', () => {
  describe('Etcd3EventMeshServer', () => {
    let sandbox, valueStub, prefixWatcherStub, keyWatcherStub;
    sandbox = sinon.sandbox.create();
    valueStub = sandbox.stub();
    sandbox.stub(Etcd3.prototype, 'watch', () => {
      return {
        prefix: prefixWatcherStub,
        key: keyWatcherStub
      };
    });
    let putstub = sandbox.stub(Etcd3.prototype, 'put', () => {
      return {
        value: (val) => Promise.resolve(valueStub(val))
      };
    });
    let getstub = sandbox.stub(Etcd3.prototype, 'get', () => {
      return {
        json: () => Promise.resolve(['dummy json']),
        string: () => Promise.resolve('dummy string'),
      };
    });

    beforeEach(() => {
      prefixWatcherStub = sandbox.stub().returns({
        create: () => Promise.resolve({
          on: () => Promise.resolve('')
        }),
      });
      keyWatcherStub = sandbox.stub().returns({
        create: () => Promise.resolve({
          on: () => Promise.resolve('')
        }),
      });
    });

    afterEach(function () {
      valueStub.reset();
      prefixWatcherStub.reset();
      keyWatcherStub.reset();
      putstub.reset();
      getstub.reset();
    });

    describe('#registerService', () => {
      it('should register attributes and plans', () => {
        return eventmesh.server.registerService('fakeresourceType', 'fakeserviceId', ['fakeserviceAttributesJsonValue'], ['fakeservicePlansJsonValue'])
          .then(() => {
            expect(putstub.args[0][0]).to.equal('services/fakeresourceType/fakeserviceId/attributes');
            expect(putstub.args[1][0]).to.equal('services/fakeresourceType/fakeserviceId/plans');
            expect(valueStub.args[0][0]).to.equal(JSON.stringify(['fakeserviceAttributesJsonValue']));
            expect(valueStub.args[1][0]).to.equal(JSON.stringify(['fakeservicePlansJsonValue']));
          });
      });
    });

    describe('#getServiceAttributes', () => {
      it('should get service attributes for resource type and serviceid', () => {
        return eventmesh.server.getServiceAttributes('fakeResourceType', 'fakeServiceId')
          .then(() => expect(getstub.args[0][0]).to.equal('services/fakeResourceType/fakeServiceId/attributes'));
      });
    });

    describe('#getServicePlans', () => {
      it('should get plans for resource type and service id ', () => {
        return eventmesh.server.getServicePlans('fakeResourceType', 'fakeServiceId')
          .then(() => expect(getstub.args[0][0]).to.equal('services/fakeResourceType/fakeServiceId/plans'));
      });
    });

    describe('#createResource', () => {
      it('should set options, state and lastoperation keys for new resource', () => {
        return eventmesh.server.createResource('fakeResourceType', 'fakeResourceId', 'fakeValue')
          .then(() => {
            expect(putstub.args[0][0]).to.equal('deployments/fakeResourceType/fakeResourceId/options');
            expect(putstub.args[1][0]).to.equal('deployments/fakeResourceType/fakeResourceId/state');
            expect(putstub.args[2][0]).to.equal('deployments/fakeResourceType/fakeResourceId/lastoperation');
            expect(valueStub.args[0][0]).to.equal('fakeValue');
            expect(valueStub.args[1][0]).to.equal(CONST.RESOURCE_STATE.IN_QUEUE);
            expect(valueStub.args[2][0]).to.equal('');
          });
      });
    });

    describe('#updateResourceState', () => {
      it('should update resource state with state value', () => {
        return eventmesh.server.updateResourceState('fakeResourceType', 'fakeResourceId', 'stateValue')
          .then(() => {
            expect(putstub.args[0][0]).to.equal('deployments/fakeResourceType/fakeResourceId/state');
            expect(valueStub.args[0][0]).to.equal('stateValue');
          });
      });
    });

    describe('#updateResourceKey', () => {
      it('should update the resouce key with given value', () => {
        return eventmesh.server.updateResourceKey('fakeResourceType', 'fakeResourceId', 'fakekey', 'fakeValue')
          .then(
            () => {
              expect(putstub.args[0][0]).to.equal('deployments/fakeResourceType/fakeResourceId/fakekey');
              expect(valueStub.args[0][0]).to.equal('fakeValue');
            }
          );
      });
    });

    describe('#getResourceKey', () => {
      it('should get the resource key', () => {
        return eventmesh.server.getResourceKey('fakeResourceType', 'fakeResourceId', 'fakeKey')
          .then(() => {
            expect(getstub.args[0][0]).to.equal('deployments/fakeResourceType/fakeResourceId/fakeKey');
          });
      });
    });

    describe('#getResourceState', () => {
      it('should get the resource state', () => {
        return eventmesh.server.getResourceState('fakeResourceType', 'fakeResourceId')
          .then(() => {
            expect(getstub.args[0][0]).to.equal('deployments/fakeResourceType/fakeResourceId/state');
          });
      });
    });

    describe('#registerWatcher', () => {
      it('should register reccursively on key when isRecursive is true', () => {
        let isRecursive = true;
        return eventmesh.server.registerWatcher('fakeKey', 'fakeCallback', isRecursive)
          .then(() => {
            expect(keyWatcherStub.args[0]).to.equal(undefined);
            expect(prefixWatcherStub.args[0][0]).to.equal('fakeKey');
          });
      });
      it('should register non-reccursively on key when isRecursive is false', () => {
        let isRecursive = false;
        return eventmesh.server.registerWatcher('fakeKey', 'fakeCallback', isRecursive)
          .then(() => {
            expect(keyWatcherStub.args[0][0]).to.equal('fakeKey');
            expect(prefixWatcherStub.args[0]).to.equal(undefined);
          });
      });
    });

    describe('#annotateResource', () => {
      it('should annotate the resourse with option and state keys', () => {
        return eventmesh.server.annotateResource('fakeResourceType', 'fakeResourceId', 'fakeAnnotationName', 'fakeOperationType', 'fakeOperationId', 'fakeVal')
          .then(() => {
            expect(putstub.args[0][0]).to.equal('deployments/fakeResourceType/fakeResourceId/fakeAnnotationName/fakeOperationType/fakeOperationId/options');
            expect(putstub.args[1][0]).to.equal('deployments/fakeResourceType/fakeResourceId/fakeAnnotationName/fakeOperationType/fakeOperationId/state');
            expect(valueStub.args[0][0]).to.equal('fakeVal');
            expect(valueStub.args[1][0]).to.equal(CONST.RESOURCE_STATE.IN_QUEUE);
          });
      });
    });

    describe('#updateAnnotationState', () => {
      it('should update the annotation state key', () => {
        return eventmesh.server.updateAnnotationState('fakeResourceType', 'fakeResourceId', 'fakeAnnotationName', 'fakeOperationType', 'fakeOperationId', 'fakeStateValue')
          .then(() => {
            expect(putstub.args[0][0]).to.equal('deployments/fakeResourceType/fakeResourceId/fakeAnnotationName/fakeOperationType/fakeOperationId/state');
            expect(valueStub.args[0][0]).to.equal('fakeStateValue');
          });
      });
    });

    describe('#updateAnnotationKey', () => {
      it('should update the annotation key specified', () => {
        return eventmesh.server.updateAnnotationKey('fakeResourceType', 'fakeResourceId', 'fakeAnnotationName', 'fakeOperationType', 'fakeOperationId', 'fakeKey', 'fakeValue')
          .then(() => {
            expect(putstub.args[0][0]).to.equal('deployments/fakeResourceType/fakeResourceId/fakeAnnotationName/fakeOperationType/fakeOperationId/fakeKey');
            expect(valueStub.args[0][0]).to.equal('fakeValue');
          });
      });
    });

    describe('#getAnnotationKey', () => {
      it('should get the annotation key', () => {
        return eventmesh.server.getAnnotationKey('fakeResourceType', 'fakeResourceId', 'fakeAnnotationName', 'fakeOperationType', 'fakeOperationId', 'fakeKey')
          .then(() => {
            expect(getstub.args[0][0]).to.equal('deployments/fakeResourceType/fakeResourceId/fakeAnnotationName/fakeOperationType/fakeOperationId/fakeKey');
          });
      });
    });

    describe('#getAnnotationState', () => {
      it('should get the annotation state', () => {
        return eventmesh.server.getAnnotationState('fakeResourceType', 'fakeResourceId', 'fakeAnnotationName', 'fakeOperationType', 'fakeOperationId')
          .then(() => {
            expect(getstub.args[0][0]).to.equal('deployments/fakeResourceType/fakeResourceId/fakeAnnotationName/fakeOperationType/fakeOperationId/state');
          });
      });
    });

  });
});<commit_msg>Remove only<commit_after>'use strict';

const Promise = require('bluebird');
const CONST = require('../lib/constants');
const eventmesh = require('../lib/eventmesh');

const {
  Etcd3
} = require('etcd3');

describe('eventmesh', () => {
  describe('Etcd3EventMeshServer', () => {
    let sandbox, valueStub, prefixWatcherStub, keyWatcherStub;
    sandbox = sinon.sandbox.create();
    valueStub = sandbox.stub();
    sandbox.stub(Etcd3.prototype, 'watch', () => {
      return {
        prefix: prefixWatcherStub,
        key: keyWatcherStub
      };
    });
    let putstub = sandbox.stub(Etcd3.prototype, 'put', () => {
      return {
        value: (val) => Promise.resolve(valueStub(val))
      };
    });
    let getstub = sandbox.stub(Etcd3.prototype, 'get', () => {
      return {
        json: () => Promise.resolve(['dummy json']),
        string: () => Promise.resolve('dummy string'),
      };
    });

    beforeEach(() => {
      prefixWatcherStub = sandbox.stub().returns({
        create: () => Promise.resolve({
          on: () => Promise.resolve('')
        }),
      });
      keyWatcherStub = sandbox.stub().returns({
        create: () => Promise.resolve({
          on: () => Promise.resolve('')
        }),
      });
    });

    afterEach(function () {
      valueStub.reset();
      prefixWatcherStub.reset();
      keyWatcherStub.reset();
      putstub.reset();
      getstub.reset();
    });

    describe('#registerService', () => {
      it('should register attributes and plans', () => {
        return eventmesh.server.registerService('fakeresourceType', 'fakeserviceId', ['fakeserviceAttributesJsonValue'], ['fakeservicePlansJsonValue'])
          .then(() => {
            expect(putstub.args[0][0]).to.equal('services/fakeresourceType/fakeserviceId/attributes');
            expect(putstub.args[1][0]).to.equal('services/fakeresourceType/fakeserviceId/plans');
            expect(valueStub.args[0][0]).to.equal(JSON.stringify(['fakeserviceAttributesJsonValue']));
            expect(valueStub.args[1][0]).to.equal(JSON.stringify(['fakeservicePlansJsonValue']));
          });
      });
    });

    describe('#getServiceAttributes', () => {
      it('should get service attributes for resource type and serviceid', () => {
        return eventmesh.server.getServiceAttributes('fakeResourceType', 'fakeServiceId')
          .then(() => expect(getstub.args[0][0]).to.equal('services/fakeResourceType/fakeServiceId/attributes'));
      });
    });

    describe('#getServicePlans', () => {
      it('should get plans for resource type and service id ', () => {
        return eventmesh.server.getServicePlans('fakeResourceType', 'fakeServiceId')
          .then(() => expect(getstub.args[0][0]).to.equal('services/fakeResourceType/fakeServiceId/plans'));
      });
    });

    describe('#createResource', () => {
      it('should set options, state and lastoperation keys for new resource', () => {
        return eventmesh.server.createResource('fakeResourceType', 'fakeResourceId', 'fakeValue')
          .then(() => {
            expect(putstub.args[0][0]).to.equal('deployments/fakeResourceType/fakeResourceId/options');
            expect(putstub.args[1][0]).to.equal('deployments/fakeResourceType/fakeResourceId/state');
            expect(putstub.args[2][0]).to.equal('deployments/fakeResourceType/fakeResourceId/lastoperation');
            expect(valueStub.args[0][0]).to.equal('fakeValue');
            expect(valueStub.args[1][0]).to.equal(CONST.RESOURCE_STATE.IN_QUEUE);
            expect(valueStub.args[2][0]).to.equal('');
          });
      });
    });

    describe('#updateResourceState', () => {
      it('should update resource state with state value', () => {
        return eventmesh.server.updateResourceState('fakeResourceType', 'fakeResourceId', 'stateValue')
          .then(() => {
            expect(putstub.args[0][0]).to.equal('deployments/fakeResourceType/fakeResourceId/state');
            expect(valueStub.args[0][0]).to.equal('stateValue');
          });
      });
    });

    describe('#updateResourceKey', () => {
      it('should update the resouce key with given value', () => {
        return eventmesh.server.updateResourceKey('fakeResourceType', 'fakeResourceId', 'fakekey', 'fakeValue')
          .then(
            () => {
              expect(putstub.args[0][0]).to.equal('deployments/fakeResourceType/fakeResourceId/fakekey');
              expect(valueStub.args[0][0]).to.equal('fakeValue');
            }
          );
      });
    });

    describe('#getResourceKey', () => {
      it('should get the resource key', () => {
        return eventmesh.server.getResourceKey('fakeResourceType', 'fakeResourceId', 'fakeKey')
          .then(() => {
            expect(getstub.args[0][0]).to.equal('deployments/fakeResourceType/fakeResourceId/fakeKey');
          });
      });
    });

    describe('#getResourceState', () => {
      it('should get the resource state', () => {
        return eventmesh.server.getResourceState('fakeResourceType', 'fakeResourceId')
          .then(() => {
            expect(getstub.args[0][0]).to.equal('deployments/fakeResourceType/fakeResourceId/state');
          });
      });
    });

    describe('#registerWatcher', () => {
      it('should register reccursively on key when isRecursive is true', () => {
        let isRecursive = true;
        return eventmesh.server.registerWatcher('fakeKey', 'fakeCallback', isRecursive)
          .then(() => {
            expect(keyWatcherStub.args[0]).to.equal(undefined);
            expect(prefixWatcherStub.args[0][0]).to.equal('fakeKey');
          });
      });
      it('should register non-reccursively on key when isRecursive is false', () => {
        let isRecursive = false;
        return eventmesh.server.registerWatcher('fakeKey', 'fakeCallback', isRecursive)
          .then(() => {
            expect(keyWatcherStub.args[0][0]).to.equal('fakeKey');
            expect(prefixWatcherStub.args[0]).to.equal(undefined);
          });
      });
    });

    describe('#annotateResource', () => {
      it('should annotate the resourse with option and state keys', () => {
        return eventmesh.server.annotateResource('fakeResourceType', 'fakeResourceId', 'fakeAnnotationName', 'fakeOperationType', 'fakeOperationId', 'fakeVal')
          .then(() => {
            expect(putstub.args[0][0]).to.equal('deployments/fakeResourceType/fakeResourceId/fakeAnnotationName/fakeOperationType/fakeOperationId/options');
            expect(putstub.args[1][0]).to.equal('deployments/fakeResourceType/fakeResourceId/fakeAnnotationName/fakeOperationType/fakeOperationId/state');
            expect(valueStub.args[0][0]).to.equal('fakeVal');
            expect(valueStub.args[1][0]).to.equal(CONST.RESOURCE_STATE.IN_QUEUE);
          });
      });
    });

    describe('#updateAnnotationState', () => {
      it('should update the annotation state key', () => {
        return eventmesh.server.updateAnnotationState('fakeResourceType', 'fakeResourceId', 'fakeAnnotationName', 'fakeOperationType', 'fakeOperationId', 'fakeStateValue')
          .then(() => {
            expect(putstub.args[0][0]).to.equal('deployments/fakeResourceType/fakeResourceId/fakeAnnotationName/fakeOperationType/fakeOperationId/state');
            expect(valueStub.args[0][0]).to.equal('fakeStateValue');
          });
      });
    });

    describe('#updateAnnotationKey', () => {
      it('should update the annotation key specified', () => {
        return eventmesh.server.updateAnnotationKey('fakeResourceType', 'fakeResourceId', 'fakeAnnotationName', 'fakeOperationType', 'fakeOperationId', 'fakeKey', 'fakeValue')
          .then(() => {
            expect(putstub.args[0][0]).to.equal('deployments/fakeResourceType/fakeResourceId/fakeAnnotationName/fakeOperationType/fakeOperationId/fakeKey');
            expect(valueStub.args[0][0]).to.equal('fakeValue');
          });
      });
    });

    describe('#getAnnotationKey', () => {
      it('should get the annotation key', () => {
        return eventmesh.server.getAnnotationKey('fakeResourceType', 'fakeResourceId', 'fakeAnnotationName', 'fakeOperationType', 'fakeOperationId', 'fakeKey')
          .then(() => {
            expect(getstub.args[0][0]).to.equal('deployments/fakeResourceType/fakeResourceId/fakeAnnotationName/fakeOperationType/fakeOperationId/fakeKey');
          });
      });
    });

    describe('#getAnnotationState', () => {
      it('should get the annotation state', () => {
        return eventmesh.server.getAnnotationState('fakeResourceType', 'fakeResourceId', 'fakeAnnotationName', 'fakeOperationType', 'fakeOperationId')
          .then(() => {
            expect(getstub.args[0][0]).to.equal('deployments/fakeResourceType/fakeResourceId/fakeAnnotationName/fakeOperationType/fakeOperationId/state');
          });
      });
    });

  });
});
<|endoftext|>


<commit_before>'use strict';

// Vocablists controller
angular.module('vocablists').
  controller('TestController',
    ['$scope', '$stateParams', '$location', 'Authentication', 'Vocablists',
      function($scope, $stateParams, $location, Authentication, Vocablists) {

        Authentication.redirectUnauthenticated();
        $scope.vocablist = Vocablists.get(
          {
            vocablistId: $stateParams.vocablistId
          },
          function(value, responseHeaders) {
            if (value.user !== Authentication.user._id) {
              $scope.authenticationError = 'You are not authorized to use this vocablist';
            }
          }
        );
        $scope.isSubmitted = false;
        $scope.responses = [];
        $scope.grades = [];
        $scope.grade = 0;
        for (var i = 0; i < $scope.vocablist.length; i++) {
          $scope.grades[i] = false;
        }
        $scope.finished = {};

        function isFinished(i) {
          return $scope.finished[i];
        }

        function markFinished(i) {
          $scope.finished[i] = true;
        }

        function guessIsCorrect(i) {
          return $scope.responses[i] === $scope.vocablist.vocab[i].translation;
        }

        function markCorrect(i) {
          $scope.grades[i] = true;
          $scope.grade++;
          $scope.vocablist.vocab[i].timesCorrect++;
        }

        function gradeQuestion(i) {
          if (isFinished(i)) {
            return;
          }
          if (guessIsCorrect(i)) {
            markCorrect(i);
            markFinished(i);
          }
          $scope.vocablist.vocab[i].timesTested++;
        }

        $scope.test = function() {
          $scope.isSubmitted = false;
          $scope.findOne();
          $scope.responses = [];
          $scope.grades = [];
          $scope.grade = 0;
          for (var i = 0; i < $scope.vocablist.length; i++) {
            $scope.grades[i] = false;
          }
        };

        $scope.restartTest = function() {
          $scope.isSubmitted = false;
          $scope.grades = [];
          $scope.responses = [];
          $scope.finished = {};
        };

        $scope.retestIncorrect = function() {
          $scope.isSubmitted = false;
          $scope.responses = [];
        };

        $scope.gradeTest = function() {
          $scope.isSubmitted = true;
          for (var i = 0; i < $scope.vocablist.vocab.length; i++) {
            gradeQuestion(i);
          }
          $scope.vocablist.$update(
            null,
            function(vocablist) {
              $scope.vocablist = vocablist;
            },
            function(errorResponse) {
              $scope.error = errorResponse.data.message;
            });
        };

        $scope.isTextFieldEnabled = function(index) {
          return !$scope.isSubmitted && !$scope.grades[index];
        };

      }
]);
<commit_msg>Updates redirection method<commit_after>'use strict';

// Vocablists controller
angular.module('vocablists').
  controller('TestController',
    ['$scope', '$stateParams', '$location', 'Authentication', 'Vocablists',
      function($scope, $stateParams, $location, Authentication, Vocablists) {

        if (!Authentication.currentUser()) {
          $location.path('/');
          return;
        }
        $scope.vocablist = Vocablists.get(
          {
            vocablistId: $stateParams.vocablistId
          },
          function(value, responseHeaders) {
            if (value.user !== Authentication.user._id) {
              $scope.authenticationError = 'You are not authorized to use this vocablist';
            }
          }
        );
        $scope.isSubmitted = false;
        $scope.responses = [];
        $scope.grades = [];
        $scope.grade = 0;
        for (var i = 0; i < $scope.vocablist.length; i++) {
          $scope.grades[i] = false;
        }
        $scope.finished = {};

        function isFinished(i) {
          return $scope.finished[i];
        }

        function markFinished(i) {
          $scope.finished[i] = true;
        }

        function guessIsCorrect(i) {
          return $scope.responses[i] === $scope.vocablist.vocab[i].translation;
        }

        function markCorrect(i) {
          $scope.grades[i] = true;
          $scope.grade++;
          $scope.vocablist.vocab[i].timesCorrect++;
        }

        function gradeQuestion(i) {
          if (isFinished(i)) {
            return;
          }
          if (guessIsCorrect(i)) {
            markCorrect(i);
            markFinished(i);
          }
          $scope.vocablist.vocab[i].timesTested++;
        }

        $scope.test = function() {
          $scope.isSubmitted = false;
          $scope.findOne();
          $scope.responses = [];
          $scope.grades = [];
          $scope.grade = 0;
          for (var i = 0; i < $scope.vocablist.length; i++) {
            $scope.grades[i] = false;
          }
        };

        $scope.restartTest = function() {
          $scope.isSubmitted = false;
          $scope.grades = [];
          $scope.responses = [];
          $scope.finished = {};
        };

        $scope.retestIncorrect = function() {
          $scope.isSubmitted = false;
          $scope.responses = [];
        };

        $scope.gradeTest = function() {
          $scope.isSubmitted = true;
          for (var i = 0; i < $scope.vocablist.vocab.length; i++) {
            gradeQuestion(i);
          }
          $scope.vocablist.$update(
            null,
            function(vocablist) {
              $scope.vocablist = vocablist;
            },
            function(errorResponse) {
              $scope.error = errorResponse.data.message;
            });
        };

        $scope.isTextFieldEnabled = function(index) {
          return !$scope.isSubmitted && !$scope.grades[index];
        };

      }
]);
<|endoftext|>


<commit_before>

function next_page(start_point_list) {
	var form = $('#fullsearch');

	query_string = form.serialize();
	// Increase page count
	var page = parseInt(form.find('input[name=page]').val()) + 1;
	query_string = query_string.replace(new RegExp("page=\\d+"), 'page='+page);

	// Set start points
	query_string += '&' + $.param(start_point_list)

	document.location.search = '?' + query_string;
	return false;
}

function add_author_input(elem) {
	$(elem).parent('div').before(
		'
<input type="text" name="author"/> ' +
		'remove
'
	);
	return false;
}

function remove_author_input(elem) {
	$(elem).parent('div').remove();
	return false;
}
<commit_msg>Resolving issue #8: fixing pagination for now.<commit_after>

function next_page(start_point_list) {
	var form = $('#fullsearch');

	query_string = form.serialize();
	// Increase page count
	var page = parseInt(form.find('input[name=page]').val()) + 1;
	query_string = query_string.replace(new RegExp("page=\\d+"), 'page='+page);

	// Set start points
	query_string += '&' + $.param(start_point_list)

	document.location.search = '?' + query_string;
	return false;
}

function add_author_input(elem) {
	$(elem).parent('div').before(
		'
<input type="text" name="author"/> ' +
		'remove
'
	);
	return false;
}

function remove_author_input(elem) {
	$(elem).parent('div').remove();
	return false;
}

$(document).ready(function() {
	$('#fullsearch input').change(function() {
		$('#fullsearch input[name="page"]').val(1);
	})
})
<|endoftext|>


<commit_before>/*jshint node:true, es3:false, latedef:false*/

'use strict';

var fs      = require('fs');
var path    = require('path');
var express = require('express');
var connect = require('connect');

module.exports = function (task) {
    task
    .id('server')
    .name('Server')
    .author('Indigo United')
    .description('Run server')
    .option('env', 'The environment that the server will run', 'dev')
    .option('port', 'The port to listen for requests', 8080)
    .option('host', 'The host to listen for requests', '127.0.0.1')

    .setup(function (options, ctx, next) {
        options.index = './index_' + options.env + '.html';
        options.assetsDir = options.env;

        if (options.env !== 'dev') {
            options.rewrite = true;
            options.gzip = true;
        }

        next();
    })

    .do(function (options, ctx, next) {
        // Change cwd to the web folder
        process.chdir('web');

        var web = process.cwd(),
            env = options.env,
            link;

        // Check if the env is valid
        try {
            fs.statSync(options.index);
        } catch (e) {
            if (e.code === 'ENOENT') {
                return next(new Error('Invalid environment: ' + env));
            }
        }

        options.web = web;

        // Create dev symlink
        if (options.env === 'dev') {
            try {
                link = fs.readlinkSync('dev');
            } catch (e) {}

            if (!link || link !== '..') {
                try {
                    fs.unlinkSync('dev');
                } catch (e) {}

                // In windows, users can't create symlinks in the console
                // without running the actual command with Administrator permissions
                // see: http://ahtik.com/blog/2012/08/16/fixing-your-virtualbox-shared-folder-symlink-error
                if (process.platform === 'win32') {
                    try {
                        fs.symlinkSync('..', 'dev', 'dir');
                    } catch (e) {
                        if (e.code === 'EPERM') {
                            return next(new Error('No permission to create symlink (try running as an Administrator).'));
                        }
                    }
                } else {
                    fs.symlinkSync('..', 'dev', 'dir');
                }
            }
        // Check assets dir
        } else {
            try {
                fs.statSync(options.assetsDir);
            } catch (e) {
                if (e.code === 'ENOENT') {
                    return next(new Error('Directory "' + options.assetsDir + '" not found, did you forgot to build?'));
                }
            }
        }

        next();
    }, {
        description: 'Prepare server'
    })
    .do(function (opts, ctx) {
        // Check if assets dir exists
        var site = express();

        // Enable compression?
        if (opts.gzip) {
            site.use(connect.compress());
        }

        // Serve index
        site.get('/', function (req, res) {
            return res.sendfile(opts.index);
        });

        // Serve favicon.ico
        site.use(express.favicon('./favicon.ico'));

        // Serve files & folders
        site.get('/*', function (req, res) {
            // Get the requested file
            // If there are query parameters, remove them
            var file = path.join(opts.web, req.url.substr(1));
            file = file.split('?')[0];

            fs.stat(file, function (err, stat) {
                // If file does not exists, serve 404 page
                if (err) {
                    if (err.code === 'ENOENT') {
                        serve404(opts, res);
                    } else {
                        res.send(500);
                    }
                // If it exists and is a file, serve it
                } else if (stat.isFile()) {
                    res.sendfile(file);
                // Otherwise is a folder, so we deny the access
                } else {
                    res.send(403);
                }
            });
        });

        // Effectively listen
        site.listen(opts.port, opts.host);
        ctx.log.writeln('Listening on http://' + (opts.host === '127.0.0.1' ? 'localhost' : opts.host) + ':' + opts.port + ' (' + opts.env + ' environment)');
    }, {
        description: 'Serve files'
    });
};

/**
 * Serve 404 page.
 *
 * @param {Object} The task options
 * @param {Object} The express response object
 */
function serve404(options, res) {
    // If the rewrite is disabled, we attempt to serve the 404.html page
    // Otherwise we rewrite to the front controller (index)
    if (!options.rewrite) {
        var file404 = path.join(options.web, '404.html');
        fs.stat(file404, function (err) {
            if (!err) {
                res.status(404);
                res.sendfile('404.html');
            } else {
                res.send(404);
            }
        });
    } else {
        if (/\.[a-z0-9]{1,4}$/i.test(file)) {
            ctx.log.warnln('File does not exist', file);
        }

        res.sendfile(options.index);
    }
}
<commit_msg>Update server.js<commit_after>/*jshint node:true, es3:false, latedef:false*/

'use strict';

var fs      = require('fs');
var path    = require('path');
var express = require('express');
var connect = require('connect');

module.exports = function (task) {
    task
    .id('server')
    .name('Server')
    .author('Indigo United')
    .description('Run server')
    .option('env', 'The environment that the server will run', 'dev')
    .option('port', 'The port to listen for requests', 8080)
    .option('host', 'The host to listen for requests', '127.0.0.1')

    .setup(function (options, ctx, next) {
        options.index = './index_' + options.env + '.html';
        options.assetsDir = options.env;

        if (options.env !== 'dev') {
            options.rewrite = true;
            options.gzip = true;
        }

        next();
    })

    .do(function (options, ctx, next) {
        // Change cwd to the web folder
        process.chdir('web');

        var web = process.cwd(),
            env = options.env,
            link;

        // Check if the env is valid
        try {
            fs.statSync(options.index);
        } catch (e) {
            if (e.code === 'ENOENT') {
                return next(new Error('Invalid environment: ' + env));
            }
        }

        options.web = web;

        // Create dev symlink
        if (options.env === 'dev') {
            try {
                link = fs.readlinkSync('dev');
            } catch (e) {}

            if (!link || link !== '..') {
                try {
                    fs.unlinkSync('dev');
                } catch (e) {}

                // In windows, users can't create symlinks in the console
                // without running the actual command with Administrator permissions
                // see: http://ahtik.com/blog/2012/08/16/fixing-your-virtualbox-shared-folder-symlink-error
                if (process.platform === 'win32') {
                    try {
                        fs.symlinkSync('..', 'dev', 'dir');
                    } catch (e) {
                        if (e.code === 'EPERM') {
                            return next(new Error('No permission to create symlink (try running as an Administrator).'));
                        }
                    }
                } else {
                    fs.symlinkSync('..', 'dev', 'dir');
                }
            }
        // Check assets dir
        } else {
            try {
                fs.statSync(options.assetsDir);
            } catch (e) {
                if (e.code === 'ENOENT') {
                    return next(new Error('Directory "' + options.assetsDir + '" not found, did you forgot to build?'));
                }
            }
        }

        next();
    }, {
        description: 'Prepare server'
    })
    .do(function (opts, ctx) {
        // Check if assets dir exists
        var site = express();

        // Enable compression?
        if (opts.gzip) {
            site.use(connect.compress());
        }

        // Serve index
        site.get('/', function (req, res) {
            return res.sendfile(opts.index);
        });

        // Serve favicon.ico
        site.use(express.favicon('./favicon.ico'));

        // Serve files & folders
        site.get('/*', function (req, res) {
            // Get the requested file
            // If there are query parameters, remove them
            var file = path.join(opts.web, req.url.substr(1));
            file = file.split('?')[0];

            fs.stat(file, function (err, stat) {
                // If file does not exists
                if (err) {
                    if (err.code === 'ENOENT') {
                        inexistentFile(file, opts, res, ctx);
                    } else {
                        res.send(500);
                    }
                // If it exists and is a file, serve it
                } else if (stat.isFile()) {
                    res.sendfile(file);
                // Otherwise is a folder, so we deny the access
                } else {
                    res.send(403);
                }
            });
        });

        // Effectively listen
        site.listen(opts.port, opts.host);
        ctx.log.writeln('Listening on http://' + (opts.host === '127.0.0.1' ? 'localhost' : opts.host) + ':' + opts.port + ' (' + opts.env + ' environment)');
    }, {
        description: 'Serve files'
    });
};

/**
 * Handles a request to an inexistent file.
 *
 * @param {Object} file    The request file
 * @param {Object} options The task options
 * @param {Object} res     The express response object
 * @param {Object} ctx     The automaton context
 */
function inexistentFile(file, options, res, ctx) {
    // If the rewrite is disabled, we attempt to serve the 404.html page
    if (!options.rewrite) {
        var file404 = path.join(options.web, '404.html');
        fs.stat(file404, function (err) {
            if (!err) {
                res.status(404);
                res.sendfile('404.html');
            } else {
                res.send(404);
            }
        });
    // Otherwise we rewrite to the front controller (index)
    } else {
        if (/\.[a-z0-9]{1,4}$/i.test(file)) {
            ctx.log.warnln('Could not locate file', file);
        }

        res.sendfile(options.index);
    }
}
<|endoftext|>


<commit_before>var logger = require('_pr/logger')(module);
var CatalystCronJob = require('_pr/cronjobs/CatalystCronJob');
var AWSProvider = require('_pr/model/classes/masters/cloudprovider/awsCloudProvider.js');
var MasterUtils = require('_pr/lib/utils/masterUtil.js');
var tagsModel = require('_pr/model/tags');
var async = require('async');
var resources = require('_pr/model/resources/resources');
var unassignedInstancesModel = require('_pr/model/unassigned-instances');

var ProviderTagsAggregation = Object.create(CatalystCronJob);
ProviderTagsAggregation.execute = providerTagAggregation;

module.exports = ProviderTagsAggregation;

function providerTagAggregation() {
    MasterUtils.getAllActiveOrg(function(err, orgs) {
        if(err) {
            logger.error(err);
        }else if(orgs.length > 0){
            for(var i = 0; i < orgs.length; i++){
                (function(org){
                    AWSProvider.getAWSProvidersByOrgId(org._id, function(err, providers) {
                        if(err) {
                            logger.error(err);
                            return;
                        } else if(providers.length > 0){
                            var count = 0;
                            for(var j = 0; j < providers.length; j++){
                                (function(provider){
                                    count++;
                                    aggregateTagForProvider(provider)
                                })(providers[j]);
                            }
                            if(count ===providers.length){
                                return;
                            }

                        }else{
                            logger.info("Please configure Provider in Organization " +org.orgname+" for  Tag Aggregation");
                            return;
                        }
                    });

                })(orgs[i]);
            }

        }else{
            logger.info("Please configure Organization for Tag Aggregation");
            return;
        }
    });
};

function aggregateTagForProvider(provider) {
    var tags={};
    logger.info('Tags aggregation started for provider '+provider._id);
    async.waterfall([
        function (next) {
            tagsModel.getTagsByProviderId(provider._id, next);
        },
        function (tags, next) {
            var tagDetails = {};
            var count = 0;
            if (tags.length === 0) {
                next(null, tags);
            } else {
                for (var i = 0; i < tags.length; i++) {
                    tagDetails[tags[i].name] = tags[i];
                    if (i === tags.length - 1) {
                        next(null, tagDetails);
                    }
                }
            }
        },
        function (tagDetails, next) {
            tags = tagDetails;
            getResourcesForTagAggregation(provider,next);
        },
        function (resourceDetails, next) {
            getResourceTags(tags,resourceDetails,provider, next);
        },
        function (tagsDetails, next) {
            saveAndUpdateResourceTags(tagsDetails,provider, next);
        }
    ], function (err, results) {
        if (err) {
            logger.error(err);
            return;
        }else {
            logger.info('Tags aggregation ended for Provider'+provider._id);
            return;
        }
    })
};

function getResourcesForTagAggregation(provider,next){
    var resourcesList=[];
    async.waterfall([
        function(next){
            unassignedInstancesModel.getUnAssignedInstancesByProviderId(provider._id, next);
        },
        function(instances,next){
            resourcesList = instances;
            resources.getResourcesByProviderId(provider._id, next);
        },
        function(resources,next){
            if(resources.length > 0){
                var count = 0;
                for(var i = 0; i < resources.length ; i++){
                    count++;
                    resourcesList.push(resources[i]);
                }
                if(count === resources.length){
                    next(null,resourcesList);
                }
            }else{
                next(null,resourcesList);
            }
        }
    ],function(err,results){
        if(err){
            next(err);
        }else{
            next(null,results);
        }

    })
};

function getResourceTags(tagDetails,resourceDetails,provider,next){
    if(resourceDetails.length > 0) {
        var count = 0;
        for (var m = 0; m < resourceDetails.length; m++) {
            count++;
            for (var tagName in resourceDetails[m].tags) {
                var tagValue = resourceDetails[m].tags[tagName];
                if (tagName in tagDetails) {
                    if (tagDetails[tagName].values.indexOf(tagValue) < 0) {
                        tagDetails[tagName].values.push(tagValue);
                    }
                } else {
                    tagDetails[tagName] = {
                        'providerId': provider._id,
                        'orgId': provider.orgId[0],
                        'name': tagName,
                        'values': [tagValue],
                        'new': true
                    }
                }
            }
        }
        if (resourceDetails.length === count) {
            next(null, tagDetails);
        }
    }else{
        next(null,{});
    }
};

function saveAndUpdateResourceTags(tags,provider,next){
    if(tags) {
        var count = 0;
        for (var tagName in tags) {
            if (tags[tagName].new) {
                count++;
                var tagObject = tags[tagName];
                delete tagObject.new;
                tagsModel.createNew(tagObject);
            } else {
                count++;
                var params = {
                    'providerId': provider._id,
                    'name': tagName
                }
                var fields = {
                    'values': tags[tagName].values
                }
                tagsModel.updateTag(params, fields);
            }
        }
        if(count ===Object.keys(tags).length){
            next(null,tags);
        }
    }else{
        next(null,{});
    }
};<commit_msg>CAT-2257 Fixed<commit_after>var logger = require('_pr/logger')(module);
var CatalystCronJob = require('_pr/cronjobs/CatalystCronJob');
var AWSProvider = require('_pr/model/classes/masters/cloudprovider/awsCloudProvider.js');
var MasterUtils = require('_pr/lib/utils/masterUtil.js');
var tagsModel = require('_pr/model/tags');
var async = require('async');
var resources = require('_pr/model/resources/resources');
var unassignedInstancesModel = require('_pr/model/unassigned-instances');

var ProviderTagsAggregation = Object.create(CatalystCronJob);
ProviderTagsAggregation.execute = providerTagAggregation;

module.exports = ProviderTagsAggregation;

function providerTagAggregation() {
    MasterUtils.getAllActiveOrg(function(err, orgs) {
        if(err) {
            logger.error(err);
        }else if(orgs.length > 0){
            for(var i = 0; i < orgs.length; i++){
                (function(org){
                    AWSProvider.getAWSProvidersByOrgId(org.rowid, function(err, providers) {
                        if(err) {
                            logger.error(err);
                            return;
                        } else if(providers.length > 0){
                            var count = 0;
                            for(var j = 0; j < providers.length; j++){
                                (function(provider){
                                    count++;
                                    aggregateTagForProvider(provider)
                                })(providers[j]);
                            }
                            if(count ===providers.length){
                                return;
                            }

                        }else{
                            logger.info("Please configure Provider in Organization " +org.orgname+" for  Tag Aggregation");
                            return;
                        }
                    });

                })(orgs[i]);
            }

        }else{
            logger.info("Please configure Organization for Tag Aggregation");
            return;
        }
    });
};

function aggregateTagForProvider(provider) {
    var tags={};
    logger.info('Tags aggregation started for provider '+provider._id);
    async.waterfall([
        function (next) {
            tagsModel.getTagsByProviderId(provider._id, next);
        },
        function (tags, next) {
            var tagDetails = {};
            var count = 0;
            if (tags.length === 0) {
                next(null, tags);
            } else {
                for (var i = 0; i < tags.length; i++) {
                    tagDetails[tags[i].name] = tags[i];
                    if (i === tags.length - 1) {
                        next(null, tagDetails);
                    }
                }
            }
        },
        function (tagDetails, next) {
            tags = tagDetails;
            getResourcesForTagAggregation(provider,next);
        },
        function (resourceDetails, next) {
            getResourceTags(tags,resourceDetails,provider, next);
        },
        function (tagsDetails, next) {
            saveAndUpdateResourceTags(tagsDetails,provider, next);
        }
    ], function (err, results) {
        if (err) {
            logger.error(err);
            return;
        }else {
            logger.info('Tags aggregation ended for Provider'+provider._id);
            return;
        }
    })
};

function getResourcesForTagAggregation(provider,next){
    var resourcesList=[];
    async.waterfall([
        function(next){
            unassignedInstancesModel.getUnAssignedInstancesByProviderId(provider._id, next);
        },
        function(instances,next){
            resourcesList = instances;
            resources.getResourcesByProviderId(provider._id, next);
        },
        function(resources,next){
            if(resources.length > 0){
                var count = 0;
                for(var i = 0; i < resources.length ; i++){
                    count++;
                    resourcesList.push(resources[i]);
                }
                if(count === resources.length){
                    next(null,resourcesList);
                }
            }else{
                next(null,resourcesList);
            }
        }
    ],function(err,results){
        if(err){
            next(err);
        }else{
            next(null,results);
        }

    })
};

function getResourceTags(tagDetails,resourceDetails,provider,next){
    if(resourceDetails.length > 0) {
        var count = 0;
        for (var m = 0; m < resourceDetails.length; m++) {
            count++;
            for (var tagName in resourceDetails[m].tags) {
                var tagValue = resourceDetails[m].tags[tagName];
                if (tagName in tagDetails) {
                    if (tagDetails[tagName].values.indexOf(tagValue) < 0) {
                        tagDetails[tagName].values.push(tagValue);
                    }
                } else {
                    tagDetails[tagName] = {
                        'providerId': provider._id,
                        'orgId': provider.orgId[0],
                        'name': tagName,
                        'values': [tagValue],
                        'new': true
                    }
                }
            }
        }
        if (resourceDetails.length === count) {
            next(null, tagDetails);
        }
    }else{
        next(null,{});
    }
};

function saveAndUpdateResourceTags(tags,provider,next){
    if(tags) {
        var count = 0;
        for (var tagName in tags) {
            if (tags[tagName].new) {
                count++;
                var tagObject = tags[tagName];
                delete tagObject.new;
                tagsModel.createNew(tagObject);
            } else {
                count++;
                var params = {
                    'providerId': provider._id,
                    'name': tagName
                }
                var fields = {
                    'values': tags[tagName].values
                }
                tagsModel.updateTag(params, fields);
            }
        }
        if(count ===Object.keys(tags).length){
            next(null,tags);
        }
    }else{
        next(null,{});
    }
};<|endoftext|>