<commit_before>import React, { cloneElement, Component, PropTypes } from 'react';
import Dock from 'react-dock';
import { POSITIONS } from './constants';
import { toggleVisibility, changePosition, changeSize } from './actions';
import reducer from './reducers';
import parseKey from 'parse-key';

export default class DockMonitor extends Component {
  static update = reducer;

  static propTypes = {
    defaultPosition: PropTypes.oneOf(POSITIONS).isRequired,
    defaultIsVisible: PropTypes.bool.isRequired,
    defaultSize: PropTypes.number.isRequired,
    toggleVisibilityKey: PropTypes.string.isRequired,
    changePositionKey: PropTypes.string.isRequired,
    fluid: PropTypes.bool,
    children: PropTypes.element,

    dispatch: PropTypes.func,
    monitorState: PropTypes.shape({
      position: PropTypes.oneOf(POSITIONS).isRequired,
      size: PropTypes.number.isRequired,
      isVisible: PropTypes.bool.isRequired,
      childMonitorState: PropTypes.any
    })
  };

  static defaultProps = {
    defaultIsVisible: true,
    defaultPosition: 'right',
    defaultSize: 0.3,
    fluid: true
  };

  constructor(props) {
    super(props);
    this.handleKeyDown = this.handleKeyDown.bind(this);
    this.handleSizeChange = this.handleSizeChange.bind(this);
  }

  componentDidMount() {
    window.addEventListener('keydown', this.handleKeyDown);
  }

  componentWillUnmount() {
    window.removeEventListener('keydown', this.handleKeyDown);
  }

  matchesKey(key, event) {
    const charCode = event.keyCode || event.which;
    const char = String.fromCharCode(charCode);
    return key.name.toUpperCase() === char.toUpperCase() &&
      key.alt === event.altKey &&
      key.ctrl === event.ctrlKey &&
      key.meta === event.metaKey &&
      key.shift === event.shiftKey;
  }

  handleKeyDown(e) {
    const visibilityKey = parseKey(this.props.toggleVisibilityKey);
    const positionKey = parseKey(this.props.changePositionKey);

    if (this.matchesKey(visibilityKey, e)) {
      e.preventDefault();
      this.props.dispatch(toggleVisibility());
    } else if (this.matchesKey(positionKey, e)) {
      e.preventDefault();
      this.props.dispatch(changePosition());
    }
  }

  handleSizeChange(requestedSize) {
    this.props.dispatch(changeSize(requestedSize));
  }

  render() {
    const { monitorState, children, fluid, ...rest } = this.props;
    const { position, isVisible, size } = monitorState;
    const childProps = {
      ...rest,
      monitorState: monitorState.childMonitorState
    };

    return (
      <Dock position={position}
            isVisible={isVisible}
            size={size}
            fluid={fluid}
            onSizeChange={this.handleSizeChange}
            dimMode='none'>
        {cloneElement(children, childProps)}
      </Dock>
    );
  }
}
<commit_msg>do not trigger shortcuts if an input-like element is focused<commit_after>import React, { cloneElement, Component, PropTypes } from 'react';
import Dock from 'react-dock';
import { POSITIONS } from './constants';
import { toggleVisibility, changePosition, changeSize } from './actions';
import reducer from './reducers';
import parseKey from 'parse-key';

export default class DockMonitor extends Component {
  static update = reducer;

  static propTypes = {
    defaultPosition: PropTypes.oneOf(POSITIONS).isRequired,
    defaultIsVisible: PropTypes.bool.isRequired,
    defaultSize: PropTypes.number.isRequired,
    toggleVisibilityKey: PropTypes.string.isRequired,
    changePositionKey: PropTypes.string.isRequired,
    fluid: PropTypes.bool,
    children: PropTypes.element,

    dispatch: PropTypes.func,
    monitorState: PropTypes.shape({
      position: PropTypes.oneOf(POSITIONS).isRequired,
      size: PropTypes.number.isRequired,
      isVisible: PropTypes.bool.isRequired,
      childMonitorState: PropTypes.any
    })
  };

  static defaultProps = {
    defaultIsVisible: true,
    defaultPosition: 'right',
    defaultSize: 0.3,
    fluid: true
  };

  constructor(props) {
    super(props);
    this.handleKeyDown = this.handleKeyDown.bind(this);
    this.handleSizeChange = this.handleSizeChange.bind(this);
  }

  componentDidMount() {
    window.addEventListener('keydown', this.handleKeyDown);
  }

  componentWillUnmount() {
    window.removeEventListener('keydown', this.handleKeyDown);
  }

  matchesKey(key, event) {
    const charCode = event.keyCode || event.which;
    const char = String.fromCharCode(charCode);
    return key.name.toUpperCase() === char.toUpperCase() &&
      key.alt === event.altKey &&
      key.ctrl === event.ctrlKey &&
      key.meta === event.metaKey &&
      key.shift === event.shiftKey;
  }

  handleKeyDown(e) {
    const visibilityKey = parseKey(this.props.toggleVisibilityKey);
    const positionKey = parseKey(this.props.changePositionKey);

    // do not trigger action if an input-like element is focused
    if (e.target.tagName == 'INPUT' || e.target.tagName == 'SELECT' ||
        e.target.tagName == 'TEXTAREA' || e.target.isContentEditable) {
      return
    }

    if (this.matchesKey(visibilityKey, e)) {
      e.preventDefault();
      this.props.dispatch(toggleVisibility());
    } else if (this.matchesKey(positionKey, e)) {
      e.preventDefault();
      this.props.dispatch(changePosition());
    }
  }

  handleSizeChange(requestedSize) {
    this.props.dispatch(changeSize(requestedSize));
  }

  render() {
    const { monitorState, children, fluid, ...rest } = this.props;
    const { position, isVisible, size } = monitorState;
    const childProps = {
      ...rest,
      monitorState: monitorState.childMonitorState
    };

    return (
      <Dock position={position}
            isVisible={isVisible}
            size={size}
            fluid={fluid}
            onSizeChange={this.handleSizeChange}
            dimMode='none'>
        {cloneElement(children, childProps)}
      </Dock>
    );
  }
}
<|endoftext|>


<commit_before>/**
 * grunt-jasmine-webpack
 */
 /* globals __dirname*/

'use strict';

var path = require('path'),
    fs = require('fs'),

    _ = require('underscore'),
    webpack = require('webpack'),
    minimatch = require('minimatch'),
    chalk = require('chalk'),

    Reporter = require('./lib/Reporter'),

    jasmine = require('jasmine-core'),

    tempDir = '.grunt/grunt-jasmine-webpack';

module.exports = function (grunt) {

    var reporter = new Reporter(grunt);

    grunt.registerMultiTask('jasmine_webpack', 'A plugin to run webpack tests via jasmine', function () {
        var promisePolyfillPath = require.resolve('es6-promise-polyfill')
                           .match(/.*\/node_modules\/[^/]+\//)[0] + "promise.min.js",
            done = this.async(),
            phantomjs = require('grunt-lib-phantomjs').init(grunt),

            options = this.options({
                specRunnerDest: '_SpecRunner.html',
                template: path.join(__dirname, '/templates/SpecRunner.tmpl'),
                templateOptions: {},
                keepRunner: false,
                norun: false,
                styles: [],
                helpers: [],
                vendor: [],
                polyfills: [promisePolyfillPath],
                display: 'full',
                summary: true
            }),

            filter = grunt.option('filter'),
            fileFilter,
            suiteFilter,
            specFilter,

            outdir = path.dirname(options.specRunnerDest),

            webpackConfig = _.defaults(options.webpack || {}, {
                devtool: 'eval',
                output: {
                    path: path.resolve(tempDir + '/specs'),
                    filename: '[name].js',
                    libraryTarget: 'var'
                }
            }),

            entries = {},
            specFiles = [];

        if (filter) {
            filter = filter.split(':');
            fileFilter = filter[0];
            suiteFilter = filter[1];
            specFilter = filter[2];
        }

        if (options.norun) {
            options.keepRunner = true;
        }

        // Webpack the test files.
        this.filesSrc.forEach(function (f) {
            var filename = path.basename(f, '.js');

            // Filter out any spec files that don't match the filter.
            if (!fileFilter || minimatch(f, fileFilter, {matchBase: true})) {
                specFiles.push(
                    path.relative(outdir, path.join(tempDir + '/specs', filename + ".js"))
                );
                entries[filename] = f;
            }
        });

        if (specFiles.length === 0) {
            grunt.log.error('No tests found');
            done(false);
        }

        webpackConfig.entry = entries;

        // Webpack 2 changed most plugins to be ES6 classes, so this.options()
        // returns an object and the apply function is not present.
        // Use .getRaw to get the actual instances of the plugins
        webpackConfig.plugins = grunt.config.getRaw([this.name, this.target, 'options', 'webpack', 'plugins']);

        webpack(webpackConfig, function (err, stats) {
            if (stats.hasErrors()) {
                grunt.log.writeln("Got error when building webpack files: " + stats.toJson().errors);
                done(false);
                return;
            }

            var totalSpecs = 0,
                passedSpecs = 0,
                failedSpecs = 0,
                skippedSpecs = 0,

                skippedSuites = 0,

                ignoreSuite = false,
                ignoreSpec = false;

            // Copy Jasmine files into temp dir.
            [].concat(
                jasmine.files.cssFiles,
                jasmine.files.jsFiles,
                jasmine.files.bootFiles
            ).forEach(function (file) {
                grunt.file.copy(
                    path.join(jasmine.files.path, file),
                    path.join(tempDir, file)
                );
            });

            [].concat(
                options.styles,
                options.helpers,
                options.vendor,
                options.polyfills
            ).forEach(function (file) {
                var basename = path.basename(file);
                grunt.file.copy(
                    file,
                    path.join(tempDir, basename)
                );
            });

            grunt.file.copy(
                path.join(__dirname, '/reporters/phantom-reporter.js'),
                path.join(tempDir, 'reporter.js')
            );

            grunt.file.write(
                options.specRunnerDest,
                _.template(grunt.file.read(options.template))({
                    options: options.templateOptions,
                    css: jasmine.files.cssFiles.map(function (cssFile) {
                        return path.relative(outdir, path.join(tempDir, cssFile));
                    }).concat(options.styles.map(function (f) {
                        var basename = path.basename(f);
                        return path.relative(outdir, path.join(tempDir, basename));
                    })),
                    scripts: {
                        specs: specFiles,

                        jasmine: jasmine.files.jsFiles.map(function (jsFile) {
                            return path.relative(outdir, path.join(tempDir, jsFile));
                        }),
                        boot: jasmine.files.bootFiles.map(function (bootFile) {
                            return path.relative(outdir, path.join(tempDir, bootFile));
                        }),

                        helpers: options.helpers.map(function (f) {
                            var basename = path.basename(f);
                            return path.relative(outdir, path.join(tempDir, basename));
                        }),
                        vendor: options.vendor.map(function (f) {
                            var basename = path.basename(f);
                            return path.relative(outdir, path.join(tempDir, basename));
                        }),
                        polyfills: options.polyfills.map(function (f) {
                            var basename = path.basename(f);
                            return path.relative(outdir, path.join(tempDir, basename));
                        }),

                        reporters: [path.relative(outdir, path.join(tempDir, 'reporter.js'))]
                    }
                })
            );

            if (!options.norun) {

                phantomjs.on('fail.load', function (url) {
                    phantomjs.halt();
                    grunt.log.error('PhantomJS unable to load URL ' + url);
                    done(false);
                });

                phantomjs.on('fail.timeout', function () {
                    phantomjs.halt();
                    grunt.log.error('PhantomJS timed out.');
                    done(false);
                });

                // Run tests in phantomjs, if options.norun is false.
                phantomjs.spawn(options.specRunnerDest, {
                    done: function () {
                        // Clean up.
                        if (!options.keepRunner) {
                            // Bit of a faff here, but basically I coudn't get rimraf
                            // to work without causing phantom to crash, so here
                            // we find and remove all files and dirs we've created.
                            var subdirs = [];
                            fs.unlinkSync(options.specRunnerDest);
                            grunt.file.recurse(tempDir, function (filepath, rootdir, subdir) {
                                fs.unlinkSync(filepath);
                                if (subdir) {
                                    subdirs.push(path.join(rootdir, subdir));
                                }
                            });
                            subdirs.forEach(function (dir) {
                                try {
                                    fs.rmdirSync(dir);
                                } catch (e) {}
                            });
                            fs.rmdirSync(tempDir);

                            // Try to remove .grunt as well, but there could be other things in there.
                            try {
                                fs.rmdirSync('.grunt');
                            } catch (e) {}
                        }
                        done(failedSpecs <= 0);
                    }
                });

                phantomjs.on('jasmine.done', function () {
                    if (totalSpecs === 0) {
                        grunt.log.error('No tests found for filter "' + filter.join(':') + '"');
                        done(false);
                    }

                    if (options.display === 'short') {
                        grunt.log.writeln();
                    }

                    if (options.summary) {
                        reporter.reportFinish({
                            totalSpecs: totalSpecs,
                            passedSpecs: passedSpecs,
                            failedSpecs: failedSpecs,
                            skippedSpecs: skippedSpecs,
                            skippedSuites: skippedSuites
                        });
                    }
                    grunt.verbose.writeln('Halting phantomjs');
                    phantomjs.halt();
                });

                phantomjs.on('jasmine.started', function () {
                    grunt.verbose.ok('Jasmine suite started');
                });

                phantomjs.on('jasmine.suiteStarted', function (suiteMetadata) {
                    if (!suiteFilter || suiteMetadata.description === suiteFilter) {
                        if (options.display === 'full') {
                            reporter.reportSuiteStarted(suiteMetadata.description);
                        }
                    } else {
                        ignoreSuite = true;
                    }
                });

                phantomjs.on('jasmine.suiteDone', function (suiteMetadata) {
                    if (!ignoreSuite) {
                        var disabled = suiteMetadata.status === 'disabled';

                        if (options.display === 'full') {
                            reporter.reportSuiteDone(disabled);
                        }

                        if (disabled) {
                            skippedSuites++;
                        }
                    } else {
                        ignoreSuite = false;
                    }
                });

                phantomjs.on('jasmine.specStarted', function (specMetadata) {
                    if (!ignoreSuite && (!specFilter || specFilter === specMetadata.description)) {
                        totalSpecs++;
                    } else {
                        ignoreSpec = true;
                    }
                });

                phantomjs.on('jasmine.specDone', function (specMetadata) {
                    if (!ignoreSuite && !ignoreSpec) {
                        var skipped = specMetadata.status === 'pending';

                        if (options.display !== 'none') {
                            reporter.reportSpec(
                                specMetadata.description,
                                skipped,
                                specMetadata.passedExpectations,
                                specMetadata.failedExpectations,
                                options.display
                            );
                        }

                        if (specMetadata.failedExpectations.length !== 0) {
                            failedSpecs++;
                        } else if (skipped) {
                            skippedSpecs++;
                        } else {
                            passedSpecs++;
                        }
                    } else {
                        ignoreSpec = false;
                    }
                });

                phantomjs.on('console', function (msg) {
                    if (options.display === 'full') {
                        grunt.log.writeln('\n' + chalk.yellow('log: ') + msg);
                    }
                });
            } else {
                done();
                return;
            }
        });
    });
};
<commit_msg>Get rid of regex to find minified version of polyfill<commit_after>/**
 * grunt-jasmine-webpack
 */
 /* globals __dirname*/

'use strict';

var path = require('path'),
    fs = require('fs'),

    _ = require('underscore'),
    webpack = require('webpack'),
    minimatch = require('minimatch'),
    chalk = require('chalk'),

    Reporter = require('./lib/Reporter'),

    jasmine = require('jasmine-core'),

    tempDir = '.grunt/grunt-jasmine-webpack';

module.exports = function (grunt) {

    var reporter = new Reporter(grunt);

    grunt.registerMultiTask('jasmine_webpack', 'A plugin to run webpack tests via jasmine', function () {
        var promisePolyfillPath = require.resolve('es6-promise-polyfill'),
            done = this.async(),
            phantomjs = require('grunt-lib-phantomjs').init(grunt),

            options = this.options({
                specRunnerDest: '_SpecRunner.html',
                template: path.join(__dirname, '/templates/SpecRunner.tmpl'),
                templateOptions: {},
                keepRunner: false,
                norun: false,
                styles: [],
                helpers: [],
                vendor: [],
                polyfills: [promisePolyfillPath],
                display: 'full',
                summary: true
            }),

            filter = grunt.option('filter'),
            fileFilter,
            suiteFilter,
            specFilter,

            outdir = path.dirname(options.specRunnerDest),

            webpackConfig = _.defaults(options.webpack || {}, {
                devtool: 'eval',
                output: {
                    path: path.resolve(tempDir + '/specs'),
                    filename: '[name].js',
                    libraryTarget: 'var'
                }
            }),

            entries = {},
            specFiles = [];

        if (filter) {
            filter = filter.split(':');
            fileFilter = filter[0];
            suiteFilter = filter[1];
            specFilter = filter[2];
        }

        if (options.norun) {
            options.keepRunner = true;
        }

        // Webpack the test files.
        this.filesSrc.forEach(function (f) {
            var filename = path.basename(f, '.js');

            // Filter out any spec files that don't match the filter.
            if (!fileFilter || minimatch(f, fileFilter, {matchBase: true})) {
                specFiles.push(
                    path.relative(outdir, path.join(tempDir + '/specs', filename + ".js"))
                );
                entries[filename] = f;
            }
        });

        if (specFiles.length === 0) {
            grunt.log.error('No tests found');
            done(false);
        }

        webpackConfig.entry = entries;

        // Webpack 2 changed most plugins to be ES6 classes, so this.options()
        // returns an object and the apply function is not present.
        // Use .getRaw to get the actual instances of the plugins
        webpackConfig.plugins = grunt.config.getRaw([this.name, this.target, 'options', 'webpack', 'plugins']);

        webpack(webpackConfig, function (err, stats) {
            if (stats.hasErrors()) {
                grunt.log.writeln("Got error when building webpack files: " + stats.toJson().errors);
                done(false);
                return;
            }

            var totalSpecs = 0,
                passedSpecs = 0,
                failedSpecs = 0,
                skippedSpecs = 0,

                skippedSuites = 0,

                ignoreSuite = false,
                ignoreSpec = false;

            // Copy Jasmine files into temp dir.
            [].concat(
                jasmine.files.cssFiles,
                jasmine.files.jsFiles,
                jasmine.files.bootFiles
            ).forEach(function (file) {
                grunt.file.copy(
                    path.join(jasmine.files.path, file),
                    path.join(tempDir, file)
                );
            });

            [].concat(
                options.styles,
                options.helpers,
                options.vendor,
                options.polyfills
            ).forEach(function (file) {
                var basename = path.basename(file);
                grunt.file.copy(
                    file,
                    path.join(tempDir, basename)
                );
            });

            grunt.file.copy(
                path.join(__dirname, '/reporters/phantom-reporter.js'),
                path.join(tempDir, 'reporter.js')
            );

            grunt.file.write(
                options.specRunnerDest,
                _.template(grunt.file.read(options.template))({
                    options: options.templateOptions,
                    css: jasmine.files.cssFiles.map(function (cssFile) {
                        return path.relative(outdir, path.join(tempDir, cssFile));
                    }).concat(options.styles.map(function (f) {
                        var basename = path.basename(f);
                        return path.relative(outdir, path.join(tempDir, basename));
                    })),
                    scripts: {
                        specs: specFiles,

                        jasmine: jasmine.files.jsFiles.map(function (jsFile) {
                            return path.relative(outdir, path.join(tempDir, jsFile));
                        }),
                        boot: jasmine.files.bootFiles.map(function (bootFile) {
                            return path.relative(outdir, path.join(tempDir, bootFile));
                        }),

                        helpers: options.helpers.map(function (f) {
                            var basename = path.basename(f);
                            return path.relative(outdir, path.join(tempDir, basename));
                        }),
                        vendor: options.vendor.map(function (f) {
                            var basename = path.basename(f);
                            return path.relative(outdir, path.join(tempDir, basename));
                        }),
                        polyfills: options.polyfills.map(function (f) {
                            var basename = path.basename(f);
                            return path.relative(outdir, path.join(tempDir, basename));
                        }),

                        reporters: [path.relative(outdir, path.join(tempDir, 'reporter.js'))]
                    }
                })
            );

            if (!options.norun) {

                phantomjs.on('fail.load', function (url) {
                    phantomjs.halt();
                    grunt.log.error('PhantomJS unable to load URL ' + url);
                    done(false);
                });

                phantomjs.on('fail.timeout', function () {
                    phantomjs.halt();
                    grunt.log.error('PhantomJS timed out.');
                    done(false);
                });

                // Run tests in phantomjs, if options.norun is false.
                phantomjs.spawn(options.specRunnerDest, {
                    done: function () {
                        // Clean up.
                        if (!options.keepRunner) {
                            // Bit of a faff here, but basically I coudn't get rimraf
                            // to work without causing phantom to crash, so here
                            // we find and remove all files and dirs we've created.
                            var subdirs = [];
                            fs.unlinkSync(options.specRunnerDest);
                            grunt.file.recurse(tempDir, function (filepath, rootdir, subdir) {
                                fs.unlinkSync(filepath);
                                if (subdir) {
                                    subdirs.push(path.join(rootdir, subdir));
                                }
                            });
                            subdirs.forEach(function (dir) {
                                try {
                                    fs.rmdirSync(dir);
                                } catch (e) {}
                            });
                            fs.rmdirSync(tempDir);

                            // Try to remove .grunt as well, but there could be other things in there.
                            try {
                                fs.rmdirSync('.grunt');
                            } catch (e) {}
                        }
                        done(failedSpecs <= 0);
                    }
                });

                phantomjs.on('jasmine.done', function () {
                    if (totalSpecs === 0) {
                        grunt.log.error('No tests found for filter "' + filter.join(':') + '"');
                        done(false);
                    }

                    if (options.display === 'short') {
                        grunt.log.writeln();
                    }

                    if (options.summary) {
                        reporter.reportFinish({
                            totalSpecs: totalSpecs,
                            passedSpecs: passedSpecs,
                            failedSpecs: failedSpecs,
                            skippedSpecs: skippedSpecs,
                            skippedSuites: skippedSuites
                        });
                    }
                    grunt.verbose.writeln('Halting phantomjs');
                    phantomjs.halt();
                });

                phantomjs.on('jasmine.started', function () {
                    grunt.verbose.ok('Jasmine suite started');
                });

                phantomjs.on('jasmine.suiteStarted', function (suiteMetadata) {
                    if (!suiteFilter || suiteMetadata.description === suiteFilter) {
                        if (options.display === 'full') {
                            reporter.reportSuiteStarted(suiteMetadata.description);
                        }
                    } else {
                        ignoreSuite = true;
                    }
                });

                phantomjs.on('jasmine.suiteDone', function (suiteMetadata) {
                    if (!ignoreSuite) {
                        var disabled = suiteMetadata.status === 'disabled';

                        if (options.display === 'full') {
                            reporter.reportSuiteDone(disabled);
                        }

                        if (disabled) {
                            skippedSuites++;
                        }
                    } else {
                        ignoreSuite = false;
                    }
                });

                phantomjs.on('jasmine.specStarted', function (specMetadata) {
                    if (!ignoreSuite && (!specFilter || specFilter === specMetadata.description)) {
                        totalSpecs++;
                    } else {
                        ignoreSpec = true;
                    }
                });

                phantomjs.on('jasmine.specDone', function (specMetadata) {
                    if (!ignoreSuite && !ignoreSpec) {
                        var skipped = specMetadata.status === 'pending';

                        if (options.display !== 'none') {
                            reporter.reportSpec(
                                specMetadata.description,
                                skipped,
                                specMetadata.passedExpectations,
                                specMetadata.failedExpectations,
                                options.display
                            );
                        }

                        if (specMetadata.failedExpectations.length !== 0) {
                            failedSpecs++;
                        } else if (skipped) {
                            skippedSpecs++;
                        } else {
                            passedSpecs++;
                        }
                    } else {
                        ignoreSpec = false;
                    }
                });

                phantomjs.on('console', function (msg) {
                    if (options.display === 'full') {
                        grunt.log.writeln('\n' + chalk.yellow('log: ') + msg);
                    }
                });
            } else {
                done();
                return;
            }
        });
    });
};
<|endoftext|>


<commit_before>'use strict';

var LoginPage = require('../pages/login_page.js');
var LogoutPage = require('../pages/logout_page.js');

describe('OCL Org Page', function () {
    var loginPage;
    var logoutPage;

    beforeEach(function () {
        loginPage = new LoginPage();
        logoutPage = new LogoutPage();
    });

    it('should login', function () {
        var loginPage = new LoginPage();
        loginPage.visit();
        loginPage.login('awadhwa','root123');

        expect(element(by.className('alert-success')).getText()).toEqual('Successfully signed in as awadhwa.');
    });

    var getRandomString = function(length) {
        var string = '';
        var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        for (var i = 0; i < length; i++) {
            string += letters.charAt(Math.floor(Math.random() * letters.length));
        }
        return string;
    };

    it('should create organization', function () {
        element(by.linkText('Create New Organization')).click();
        element(by.id('id_short_name')).sendKeys(getRandomString(5));
        element(by.id('id_name')).sendKeys('Full name');
        element(by.id('id_website')).sendKeys('http://www.google.com/');
        element(by.id('id_company')).sendKeys('TW');
        element(by.id('id_location')).sendKeys('India');
        element(by.buttonText('Create Organization')).click();

        expect(element(by.className('alert-info')).getText()).toEqual('Organization Added');
    });

    // it('should create collection under org', function () {
    //     element(by.linkText('Collections')).click();
    //     element(by.linkText(' New Collection')).click();
    //     element(by.id('id_short_code')).sendKeys('C1');
    //     element(by.id('id_name')).sendKeys('org col 1');
    //     element(by.id('id_full_name')).sendKeys('organization collection 1');
    //     element(by.id('id_supported_locales')).sendKeys('en');
    //     element(by.buttonText('Add')).click();
    //
    //     expect(element(by.className('alert-info')).getText()).toEqual('Collection created');
    // });

    it('should create source', function () {
        element(by.linkText('Sources')).click();
        element(by.linkText(' New Source')).click();
        element(by.id('id_short_name')).sendKeys('S1');
        element(by.id('id_full_name')).sendKeys('source 1');
        element(by.id('id_supported_locales')).sendKeys('en');
        element(by.buttonText('Create Source')).click();

        expect(element(by.className('alert-info')).getText()).toEqual('Source created');
    });

    // it('should create source version', function () {
    //     element(by.linkText('Versions')).click();
    //     element(by.linkText(' New Source Version')).click();
    //     element(by.id('id_id')).sendKeys('v1');
    //     element(by.id('id_description')).sendKeys('version 1');
    //     element(by.buttonText('Create Source Version')).click();
    //
    //     expect(element(by.className('alert-info')).getText()).toEqual('Source version created!');
    // });

    it('should create concept', function () {
        element(by.linkText('Concepts')).click();
        element(by.linkText(' New Concept')).click();
        element(by.id('id_concept_id')).sendKeys('C1');
        element(by.id('id_name')).sendKeys('concept 1');
        element(by.id('id_name_type')).sendKeys('Fully_specified');
        element(by.buttonText('Create Concept')).click();

        expect(element(by.className('alert-info')).getText()).toEqual('Concept created.');
    });

     it('should logout', function () {
         var logoutPage = new LogoutPage();
         logoutPage.logout();

        expect(element(by.className('alert-success')).getText()).toEqual('You have signed out.');
    });

});
<commit_msg>Added e2e test for create source version and collection<commit_after>'use strict';

var LoginPage = require('../pages/login_page.js');
var LogoutPage = require('../pages/logout_page.js');

describe('OCL Org Page', function () {
    var loginPage;
    var logoutPage;
    var orgShortCode = '';

    beforeEach(function () {
        loginPage = new LoginPage();
        logoutPage = new LogoutPage();
    });

    it('should login', function () {
        var loginPage = new LoginPage();
        loginPage.visit();
        loginPage.login('awadhwa','root123');

        expect(element(by.className('alert-success')).getText()).toEqual('Successfully signed in as awadhwa.');
    });

    var getRandomString = function(length) {
        var string = '';
        var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        for (var i = 0; i < length; i++) {
            string += letters.charAt(Math.floor(Math.random() * letters.length));
        }
        return string;
    };

    it('should create organization', function () {
        element(by.linkText('Create New Organization')).click();
        orgShortCode = getRandomString(5);
        element(by.id('id_short_name')).sendKeys(orgShortCode);
        element(by.id('id_name')).sendKeys('Full name');
        element(by.id('id_website')).sendKeys('http://www.google.com/');
        element(by.id('id_company')).sendKeys('TW');
        element(by.id('id_location')).sendKeys('India');
        element(by.buttonText('Create Organization')).click();

        expect(element(by.className('alert-info')).getText()).toEqual('Organization Added');
    });

    it('should create collection under org', function () {
        element(by.linkText('Collections')).click();
        element(by.linkText(' New Collection')).click();
        element(by.id('id_short_code')).sendKeys('C1');
        element(by.id('id_name')).sendKeys('org col 1');
        element(by.id('id_full_name')).sendKeys('organization collection 1');
        element(by.id('id_supported_locales')).sendKeys('en');
        element(by.buttonText('Add')).click();

        expect(element(by.className('alert-info')).getText()).toEqual('Collection created');

        element(by.linkText('  '+orgShortCode)).click();
    });

    it('should create source', function () {
        element(by.linkText('Sources')).click();
        element(by.linkText(' New Source')).click();
        element(by.id('id_short_name')).sendKeys('S1');
        element(by.id('id_full_name')).sendKeys('source 1');
        element(by.id('id_supported_locales')).sendKeys('en');
        element(by.buttonText('Create Source')).click();

        expect(element(by.className('alert-info')).getText()).toEqual('Source created');
    });

    it('should create source version', function () {
        element(by.linkText('Versions')).click();
        element(by.linkText('New Source Version')).click();
        element(by.id('id_id')).sendKeys('v1');
        element(by.id('id_description')).sendKeys('version 1');
        element(by.buttonText('Create Source Version')).click();

        expect(element(by.className('alert-info')).getText()).toEqual('Source version created!');
    });

    it('should create concept', function () {
        element(by.linkText('Concepts')).click();
        element(by.linkText(' New Concept')).click();
        element(by.id('id_concept_id')).sendKeys('C1');
        element(by.id('id_name')).sendKeys('concept 1');
        element(by.id('id_name_type')).sendKeys('Fully_specified');
        element(by.buttonText('Create Concept')).click();

        expect(element(by.className('alert-info')).getText()).toEqual('Concept created.');
    });

     it('should logout', function () {
         var logoutPage = new LogoutPage();
         logoutPage.logout();

        expect(element(by.className('alert-success')).getText()).toEqual('You have signed out.');
    });

});
<|endoftext|>


<commit_before>var SIGINT_HOOKED = false;

module.exports = function sigintHook( fn ) {
	if ( SIGINT_HOOKED ) {
		return;
	}
	SIGINT_HOOKED = true;
	// ctrl+c should stop this task and quit grunt gracefully
	// (process.on("SIGINT", fn) doesn't behave correctly on Windows):
	var rl = require( "readline" ).createInterface( {
		input: process.stdin,
		output: process.stdout
	} );
	rl.on( "SIGINT", function() {
		fn();
		rl.close();
	} );
};<commit_msg>Do not use 'constant' syntax if it's not constant.<commit_after>var sigintHooked = false;

module.exports = function sigintHook( fn ) {
	if ( sigintHooked ) {
		return;
	}
	sigintHooked = true;
	// ctrl+c should stop this task and quit grunt gracefully
	// (process.on("SIGINT", fn) doesn't behave correctly on Windows):
	var rl = require( "readline" ).createInterface( {
		input: process.stdin,
		output: process.stdout
	} );
	rl.on( "SIGINT", function() {
		fn();
		rl.close();
	} );
};<|endoftext|>


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

(function() {
  'use strict';

  var Scanner = traceur.syntax.Scanner;
  var SourceRange = traceur.util.SourceRange;
  var TokenType = traceur.syntax.TokenType;
  var PredefinedName = traceur.syntax.PredefinedName;
  var ErrorReporter = traceur.util.ErrorReporter;
  var SourceFile = traceur.syntax.SourceFile;
  var Keywords = traceur.syntax.Keywords;

  var Classification = {
    ERROR: 'error',
    COMMENT: 'comment',
    IDENTIFIER: 'identifier',
    KEYWORD: 'keyword',
    PUNCTUATOR: 'punctuator',
    STRING: 'string',
    NUMBER: 'number',
    REGEX: 'regex',
    CONTEXTUAL: 'contextual'
  };

  /**
   * Represents the classification of a region of text
   * @param {Classification} category
   * @param {string} text
   * @constructor
   */
  function ClassifiedText(category, text) {
    this.category = category;
    this.text = text;
    Object.freeze(this);
  }

  /**
   * Classifies javascript tokens into their token category. This can be used
   * for colorization.
   *
   * TODO(jmesserly): regex and contextual keywords need a parse to be colorized
   * correctly.
   *
   * @param {ErrorReport} errorReporter
   * @param {SourceFile} file
   * @param {number=} opt_offset
   * @constructor
   * @extends {Scanner}
   */
  function Classifier(errorReporter, file, opt_offset) {
    Scanner.call(this, errorReporter, file, opt_offset);
    this.classifications_ = [];
  }

  var proto = Scanner.prototype;
  Classifier.prototype = {
    __proto__: proto,

    /** @type {number} */
    lastClassifierLocation_: 0,

    /**
     * @param {Classification} category
     * @param {SourceRange} location
     */
    pushResult_: function(category, location) {
      var start = location.start.offset;
      var end = location.end.offset;
      var contents = this.source_.contents;

      traceur.assert(this.lastClassifierLocation_ <= start);
      var code;
      if (this.lastClassifierLocation_ < start) {
        code = contents.substring(this.lastClassifierLocation_, start);

        this.classifications_.push(new ClassifiedText(null, code));
      }

      code = contents.substring(start, end);
      this.classifications_.push(new ClassifiedText(category, code));
      this.lastClassifierLocation_ = end;
    },

    // Comments don't come back as tokens, so we need to override them to
    // capture the spans.
    skipSingleLineComment_: function() {
      var beginToken = this.index_;
      proto.skipSingleLineComment_.call(this);
      this.pushResult_(Classification.COMMENT, this.getTokenRange_(beginToken));
    },

    skipMultiLineComment_: function() {
      var beginToken = this.index_;
      proto.skipMultiLineComment_.call(this);
      this.pushResult_(Classification.COMMENT, this.getTokenRange_(beginToken));
    },

    scanToken_: function() {
      var token = proto.scanToken_.call(this);
      var c;
      switch (token.type) {
        case TokenType.ERROR:
          c = Classification.ERROR;
          break;

        case TokenType.IDENTIFIER:
          // contextual keywords
          switch (token.value) {
            case PredefinedName.GET:
            case PredefinedName.MIXIN:
            case PredefinedName.MODULE:
            case PredefinedName.MODULE:
            case PredefinedName.REQUIRE:
            case PredefinedName.REQUIRES:
            case PredefinedName.SET:
            case PredefinedName.TRAIT:
              c = Classification.CONTEXTUAL;
              break;
            default: // otherwise, identifier
              c = Classification.IDENTIFIER;
          }
          break;

        case TokenType.OPEN_CURLY:
        case TokenType.CLOSE_CURLY:
        case TokenType.OPEN_PAREN:
        case TokenType.CLOSE_PAREN:
        case TokenType.OPEN_SQUARE:
        case TokenType.CLOSE_SQUARE:
        case TokenType.PERIOD:
        case TokenType.SEMI_COLON:
        case TokenType.COMMA:
        case TokenType.OPEN_ANGLE:
        case TokenType.CLOSE_ANGLE:
        case TokenType.LESS_EQUAL:
        case TokenType.GREATER_EQUAL:
        case TokenType.EQUAL_EQUAL:
        case TokenType.NOT_EQUAL:
        case TokenType.EQUAL_EQUAL_EQUAL:
        case TokenType.NOT_EQUAL_EQUAL:
        case TokenType.PLUS:
        case TokenType.MINUS:
        case TokenType.STAR:
        case TokenType.PERCENT:
        case TokenType.PLUS_PLUS:
        case TokenType.MINUS_MINUS:
        case TokenType.LEFT_SHIFT:
        case TokenType.RIGHT_SHIFT:
        case TokenType.UNSIGNED_RIGHT_SHIFT:
        case TokenType.AMPERSAND:
        case TokenType.BAR:
        case TokenType.CARET:
        case TokenType.BANG:
        case TokenType.TILDE:
        case TokenType.AND:
        case TokenType.OR:
        case TokenType.QUESTION:
        case TokenType.COLON:
        case TokenType.EQUAL:
        case TokenType.PLUS_EQUAL:
        case TokenType.MINUS_EQUAL:
        case TokenType.STAR_EQUAL:
        case TokenType.PERCENT_EQUAL:
        case TokenType.LEFT_SHIFT_EQUAL:
        case TokenType.RIGHT_SHIFT_EQUAL:
        case TokenType.UNSIGNED_RIGHT_SHIFT_EQUAL:
        case TokenType.AMPERSAND_EQUAL:
        case TokenType.BAR_EQUAL:
        case TokenType.CARET_EQUAL:
        case TokenType.SLASH:
        case TokenType.SLASH_EQUAL:
        case TokenType.SPREAD:
          c = Classification.OPERATOR;
          break;

        // 7.8 Literals
        case TokenType.NUMBER:
          c = Classification.NUMBER;
          break;

        case TokenType.STRING:
          c = Classification.STRING;
          break;

        case TokenType.REGULAR_EXPRESSION:
          c = Classification.REGEX;
          break;

        // These are treated as keywords in other colorizers
        case TokenType.NULL:
        case TokenType.TRUE:
        case TokenType.FALSE:

        // Seems like this should be colorized as a keyword, since it's a
        // short form of "function"
        case TokenType.POUND:
          c = Classification.KEYWORD;
          break;

        case TokenType.END_OF_FILE:
        default:
          if (Keywords.isKeyword(token.type)) {
            c = Classification.KEYWORD;
            break;
          }
          // EOF, or we didn't understand something. Exit.
          return token;
      }
      this.pushResult_(c, token.location);
      return token;
    }
  };

  /**
   * @param {string} source
   * @return {Array.<Classification>}
   */
  function getClassifiedTokens(source) {
    var sourceFile = new SourceFile('inline-script', source);
    var classifier = new Classifier(new ErrorReporter(), sourceFile);

    while (classifier.nextToken().type !== TokenType.END_OF_FILE) {
    }

    return classifier.classifications_;
  }

  /**
   * @param {string} source
   * @return {string} source the source with classification  tags added.
   */
  function classifySource(source) {
    var result = [];
    getClassifiedTokens(source).forEach(function(c) {
      if (c.category) {
        result.push('', c.text, '');
      } else {
        result.push(c.text);
      }
    });
    return result.join('');
  }

  function classifyAllScripts() {
    var scripts = document.querySelectorAll('pre');
    Array.prototype.forEach.call(scripts, function(preElement) {
      // get textContent to strip out existing tags
      var source = preElement.textContent;
      var classifiedSource = classifySource(source);

      // write it back as innerHTML to preserve  tags
      preElement.innerHTML = classifiedSource;
    });
  }

  classifyAllScripts();

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

var classifyTraceurTokens = function() {};

(function() {
  'use strict';

  var Scanner = traceur.syntax.Scanner;
  var SourceRange = traceur.util.SourceRange;
  var TokenType = traceur.syntax.TokenType;
  var PredefinedName = traceur.syntax.PredefinedName;
  var ErrorReporter = traceur.util.ErrorReporter;
  var SourceFile = traceur.syntax.SourceFile;
  var Keywords = traceur.syntax.Keywords;

  var Classification = {
    ERROR: 'error',
    COMMENT: 'comment',
    IDENTIFIER: 'identifier',
    KEYWORD: 'keyword',
    PUNCTUATOR: 'punctuator',
    STRING: 'string',
    NUMBER: 'number',
    REGEX: 'regex',
    CONTEXTUAL: 'contextual'
  };

  /**
   * Represents the classification of a region of text
   * @param {Classification} category
   * @param {string} text
   * @constructor
   */
  function ClassifiedText(category, text) {
    this.category = category;
    this.text = text;
    Object.freeze(this);
  }

  /**
   * Classifies javascript tokens into their token category. This can be used
   * for colorization.
   *
   * TODO(jmesserly): regex and contextual keywords need a parse to be colorized
   * correctly.
   *
   * @param {ErrorReport} errorReporter
   * @param {SourceFile} file
   * @param {number=} opt_offset
   * @constructor
   * @extends {Scanner}
   */
  function Classifier(errorReporter, file, opt_offset) {
    Scanner.call(this, errorReporter, file, opt_offset);
    this.classifications_ = [];
  }

  var proto = Scanner.prototype;
  Classifier.prototype = {
    __proto__: proto,

    /** @type {number} */
    lastClassifierLocation_: 0,

    /**
     * @param {Classification} category
     * @param {SourceRange} location
     */
    pushResult_: function(category, location) {
      var start = location.start.offset;
      var end = location.end.offset;
      var contents = this.source_.contents;

      traceur.assert(this.lastClassifierLocation_ <= start);
      var code;
      if (this.lastClassifierLocation_ < start) {
        code = contents.substring(this.lastClassifierLocation_, start);

        this.classifications_.push(new ClassifiedText(null, code));
      }

      code = contents.substring(start, end);
      this.classifications_.push(new ClassifiedText(category, code));
      this.lastClassifierLocation_ = end;
    },

    // Comments don't come back as tokens, so we need to override them to
    // capture the spans.
    skipSingleLineComment_: function() {
      var beginToken = this.index_;
      proto.skipSingleLineComment_.call(this);
      this.pushResult_(Classification.COMMENT, this.getTokenRange_(beginToken));
    },

    skipMultiLineComment_: function() {
      var beginToken = this.index_;
      proto.skipMultiLineComment_.call(this);
      this.pushResult_(Classification.COMMENT, this.getTokenRange_(beginToken));
    },

    scanToken_: function() {
      var token = proto.scanToken_.call(this);
      var c;
      switch (token.type) {
        case TokenType.ERROR:
          c = Classification.ERROR;
          break;

        case TokenType.IDENTIFIER:
          // contextual keywords
          switch (token.value) {
            case PredefinedName.GET:
            case PredefinedName.MIXIN:
            case PredefinedName.MODULE:
            case PredefinedName.MODULE:
            case PredefinedName.REQUIRE:
            case PredefinedName.REQUIRES:
            case PredefinedName.SET:
            case PredefinedName.TRAIT:
              c = Classification.CONTEXTUAL;
              break;
            default: // otherwise, identifier
              c = Classification.IDENTIFIER;
          }
          break;

        case TokenType.OPEN_CURLY:
        case TokenType.CLOSE_CURLY:
        case TokenType.OPEN_PAREN:
        case TokenType.CLOSE_PAREN:
        case TokenType.OPEN_SQUARE:
        case TokenType.CLOSE_SQUARE:
        case TokenType.PERIOD:
        case TokenType.SEMI_COLON:
        case TokenType.COMMA:
        case TokenType.OPEN_ANGLE:
        case TokenType.CLOSE_ANGLE:
        case TokenType.LESS_EQUAL:
        case TokenType.GREATER_EQUAL:
        case TokenType.EQUAL_EQUAL:
        case TokenType.NOT_EQUAL:
        case TokenType.EQUAL_EQUAL_EQUAL:
        case TokenType.NOT_EQUAL_EQUAL:
        case TokenType.PLUS:
        case TokenType.MINUS:
        case TokenType.STAR:
        case TokenType.PERCENT:
        case TokenType.PLUS_PLUS:
        case TokenType.MINUS_MINUS:
        case TokenType.LEFT_SHIFT:
        case TokenType.RIGHT_SHIFT:
        case TokenType.UNSIGNED_RIGHT_SHIFT:
        case TokenType.AMPERSAND:
        case TokenType.BAR:
        case TokenType.CARET:
        case TokenType.BANG:
        case TokenType.TILDE:
        case TokenType.AND:
        case TokenType.OR:
        case TokenType.QUESTION:
        case TokenType.COLON:
        case TokenType.EQUAL:
        case TokenType.PLUS_EQUAL:
        case TokenType.MINUS_EQUAL:
        case TokenType.STAR_EQUAL:
        case TokenType.PERCENT_EQUAL:
        case TokenType.LEFT_SHIFT_EQUAL:
        case TokenType.RIGHT_SHIFT_EQUAL:
        case TokenType.UNSIGNED_RIGHT_SHIFT_EQUAL:
        case TokenType.AMPERSAND_EQUAL:
        case TokenType.BAR_EQUAL:
        case TokenType.CARET_EQUAL:
        case TokenType.SLASH:
        case TokenType.SLASH_EQUAL:
        case TokenType.SPREAD:
          c = Classification.OPERATOR;
          break;

        // 7.8 Literals
        case TokenType.NUMBER:
          c = Classification.NUMBER;
          break;

        case TokenType.STRING:
          c = Classification.STRING;
          break;

        case TokenType.REGULAR_EXPRESSION:
          c = Classification.REGEX;
          break;

        // These are treated as keywords in other colorizers
        case TokenType.NULL:
        case TokenType.TRUE:
        case TokenType.FALSE:

        // Seems like this should be colorized as a keyword, since it's a
        // short form of "function"
        case TokenType.POUND:
          c = Classification.KEYWORD;
          break;

        case TokenType.END_OF_FILE:
        default:
          if (Keywords.isKeyword(token.type)) {
            c = Classification.KEYWORD;
            break;
          }
          // EOF, or we didn't understand something. Exit.
          return token;
      }
      this.pushResult_(c, token.location);
      return token;
    }
  };

  /**
   * @param {string} source
   * @return {Array.<Classification>}
   */
  function getClassifiedTokens(source) {
    var sourceFile = new SourceFile('inline-script', source);
    var classifier = new Classifier(new ErrorReporter(), sourceFile);

    while (classifier.nextToken().type !== TokenType.END_OF_FILE) {
    }

    return classifier.classifications_;
  }

  /**
   * @param {string} source
   * @return {string} source the source with classification  tags added.
   */
  function classifySource(source) {
    var result = [];
    getClassifiedTokens(source).forEach(function(c) {
      if (c.category) {
        result.push('', c.text, '');
      } else {
        result.push(c.text);
      }
    });
    return result.join('');
  }

  classifyTraceurTokens = classifySource;

  function classifyAllScripts() {
    var scripts = document.querySelectorAll('pre');
    Array.prototype.forEach.call(scripts, function(preElement) {
      // get textContent to strip out existing tags
      var source = preElement.textContent;
      var classifiedSource = classifySource(source);

      // write it back as innerHTML to preserve  tags
      preElement.innerHTML = classifiedSource;
    });
  }

  classifyAllScripts();

})();
<|endoftext|>


<commit_before>function ResponseShowWindow(responseID) {
  var ResponseShowView = require('ui/common/responses/ResponseShowView');
  var ResponseEditWindow = require('ui/handheld/android/ResponseEditWindow');

  var self = Ti.UI.createWindow({
    navBarHidden : true,
    backgroundColor : "#fff"
  });
  var view = new ResponseShowView(responseID);
  self.add(view);

  var activityIndicator = Ti.UI.Android.createProgressIndicator({
    message : L('activity_indicator'),
    location : Ti.UI.Android.PROGRESS_INDICATOR_DIALOG,
    type : Ti.UI.Android.PROGRESS_INDICATOR_INDETERMINANT
  });
  self.add(activityIndicator);

  view.addEventListener('ResponseShowView:responseEdit', function(e) {
    activityIndicator.show();
    new ResponseEditWindow(e.responseID).open();
    activityIndicator.hide();
  });

  view.addEventListener('ResponseShowView:responseDeleted', function(e) {
    self.close();
    Ti.App.fireEvent('ResponseShowWindow:closed');
  });

  self.addEventListener('android:back', function() {
    view.cleanup();
    view = null;
    self.close();
    Ti.App.fireEvent('ResponseShowWindow:back');
  });

  return self;
}

module.exports = ResponseShowWindow;
<commit_msg>Add a check in ResponsesShowWindow  if view is defined or not<commit_after>function ResponseShowWindow(responseID) {
  var ResponseShowView = require('ui/common/responses/ResponseShowView');
  var ResponseEditWindow = require('ui/handheld/android/ResponseEditWindow');

  var self = Ti.UI.createWindow({
    navBarHidden : true,
    backgroundColor : "#fff"
  });
  var view = new ResponseShowView(responseID);
  self.add(view);

  var activityIndicator = Ti.UI.Android.createProgressIndicator({
    message : L('activity_indicator'),
    location : Ti.UI.Android.PROGRESS_INDICATOR_DIALOG,
    type : Ti.UI.Android.PROGRESS_INDICATOR_INDETERMINANT
  });
  self.add(activityIndicator);

  view.addEventListener('ResponseShowView:responseEdit', function(e) {
    activityIndicator.show();
    new ResponseEditWindow(e.responseID).open();
    activityIndicator.hide();
  });

  view.addEventListener('ResponseShowView:responseDeleted', function(e) {
    self.close();
    Ti.App.fireEvent('ResponseShowWindow:closed');
  });

  self.addEventListener('android:back', function() {
    if (view)
      view.cleanup();
    view = null;
    self.close();
    Ti.App.fireEvent('ResponseShowWindow:back');
  });

  return self;
}

module.exports = ResponseShowWindow;
<|endoftext|>


<commit_before>nb.define('progress', {
    events: {
        'init': 'oninit'
    },

    oninit: function() {
        var data = this.data();

        if ('type' in data) {
            this.type = data.type;
        }

        this.$title = $(this.node).find('.js-title');
        this.$bar = $(this.node).find('.js-bar');
    },

    /**
     * Изменяет значение прогресс бара
     * @param {String} Новое значение.
     */

    update: function(newVal) {
        var newVal = parseFloat(newVal)

        this.$bar.css({width: newVal + '%'})

        if (this.type == 'percentage'){
            this.$title.html(newVal + '%')
        }

        this.data('progress', newVal)
    },

    /**
     * Меняет значение на еденицу
     */
    tick: function() {
        var newVal = parseFloat(this.data('progress'))

        newVal < 100 ?  newVal = newVal + 1 : newVal

        this.update(newVal)
    }
})<commit_msg>Progress<commit_after>nb.define('progress', {
    events: {
        'init': 'oninit'
    },

    oninit: function() {
        var data = this.data();

        if ('type' in data) {
            this.type = data.type;
        }

        this.$title = $(this.node).find('.js-title');
        this.$bar = $(this.node).find('.js-bar');
    },

    /**
     * Изменяет значение прогресс бара
     * @param {String} Новое значение.
     */

    update: function(newVal) {
        var newVal = parseFloat(newVal)

        this.$bar.css({width: newVal + '%'})

        if (this.type == 'percentage'){
            this.$title.html(newVal + '%')
        }

        this.data('progress', newVal)
    },

    /**
     * Меняет значение на еденицу
     */
    tick: function() {
        var newVal = parseFloat(this.data('progress'))

        newVal < 100 ? newVal++ : newVal

        this.update(newVal)
    }
})<|endoftext|>


<commit_before>import .physics;
import .utils;
import .shapes.ShapeFactory as ShapeFactory;

var shapes = ShapeFactory.get();
var readOnlyProp = utils.addReadOnlyProperty;

exports = Class(function () {
  this.name = "EntityModel";

  /**
   * ~ REQUIRED
   * ~ init is the constructor for each model instance
   */
  this.init = function (opts) {
    // public props
    this.fixed = false;

    // private props
    this._shape = null;
    this._entity = opts.entity;
    this._offset = { x: 0, y: 0 };
    this._previous = { x: 0, y: 0 };
    this._velocity = { x: 0, y: 0 };
    this._acceleration = { x: 0, y: 0 };
  };

  this._initShape = function (opts) {
    this._shape = shapes.getShape(opts);
  };

  /**
   * ~ REQUIRED
   * ~ reset is called when an entity becomes active
   */
  this.reset = function (opts) {
    var hitOpts = opts.hitOpts = opts.hitOpts || {};
    hitOpts.x = opts.x || 0;
    hitOpts.y = opts.y || 0;
    hitOpts.offsetX = hitOpts.offsetX || opts.offsetX || 0;
    hitOpts.offsetY = hitOpts.offsetY || opts.offsetY || 0;
    hitOpts.width = hitOpts.width || opts.width || 0;
    hitOpts.height = hitOpts.height || opts.height || 0;
    this._initShape(hitOpts);

    this.fixed = hitOpts.fixed || false;
    this._offset.x = hitOpts.offsetX;
    this._offset.y = hitOpts.offsetY;
    this._previous.x = this.x;
    this._previous.y = this.y;
    this._velocity.x = opts.vx || 0;
    this._velocity.y = opts.vy || 0;
    this._acceleration.x = opts.ax || 0;
    this._acceleration.y = opts.ay || 0;
    return this._validate();
  };

  /**
   * ~ REQUIRED
   * ~ update is called each tick while an entity is active
   */
  this.update = function (dt) {
    this._previous.x = this.x;
    this._previous.y = this.y;
    physics.step(this, dt);
  };

  /**
   * ~ REQUIRED
   * ~ collidesWith defines how collisions are detected
   * ~ by default, only works with circles and axis-aligned rectangles
   */
  this.collidesWith = function (model) {
    return physics.collide(this, model);
  };

  /**
   * ~ REQUIRED
   * ~ resolveCollisionWith guarantees that two models are not colliding
   *   by pushing them apart
   * ~ shapes with fixed = true are never moved
   * ~ returns total distance moved to separate the objects
   */
  this.resolveCollisionWith = function (model) {
    return physics.resolveCollision(this, model);
  };

  /**
   * ~ REQUIRED
   * ~ isInside is used to determine if one entity is fully contained by another
   * ~ by default, returns a bool, and only works with circles and rects
   */
  this.isInside = function (model) {
    return physics.isInside(this, model);
  };

  /**
   * ~ _validate warns if a model is improperly configured or broken
   */
  this._validate = function () {
    var valid = true;
    if (this._shape.radius !== undefined) {
      if (this._shape.radius <= 0) {
        logger.warn("Invalid circle radius:", this._entity.uid, this._shape);
        valid = false;
      }
    } else if (this._shape.width !== undefined) {
      if (this._shape.width <= 0 || this._shape.height <= 0) {
        logger.warn("Invalid rect dimensions:", this._entity.uid, this._shape);
        valid = false;
      }
    }
    return valid;
  };

  /**
   * Public API Extensions
   * ~ properties exposed for ease of use
   */

  // expose x position
  Object.defineProperty(this, 'x', {
    enumerable: true,
    configurable: true,
    get: function () { return this._shape.x + this._offset.x; },
    set: function (value) { this._shape.x = value - this._offset.x; }
  });

  // expose y position
  Object.defineProperty(this, 'y', {
    enumerable: true,
    configurable: true,
    get: function () { return this._shape.y + this._offset.y; },
    set: function (value) { this._shape.y = value - this._offset.y; }
  });

  // expose x offset
  Object.defineProperty(this, 'offsetX', {
    enumerable: true,
    configurable: true,
    get: function () { return this._offset.x; },
    set: function (value) { this._offset.x = value; }
  });

  // expose y offset
  Object.defineProperty(this, 'offsetY', {
    enumerable: true,
    configurable: true,
    get: function () { return this._offset.y; },
    set: function (value) { this._offset.y = value; }
  });

  // expose read-only previous x position
  readOnlyProp(this, 'previousX', function () { return this._previous.x; });

  // expose read-only previous y position
  readOnlyProp(this, 'previousY', function () { return this._previous.y; });

  // expose x velocity
  Object.defineProperty(this, 'vx', {
    enumerable: true,
    configurable: true,
    get: function () { return this._velocity.x; },
    set: function (value) { this._velocity.x = value; }
  });

  // expose y velocity
  Object.defineProperty(this, 'vy', {
    enumerable: true,
    configurable: true,
    get: function () { return this._velocity.y; },
    set: function (value) { this._velocity.y = value; }
  });

  // expose x acceleration
  Object.defineProperty(this, 'ax', {
    enumerable: true,
    configurable: true,
    get: function () { return this._acceleration.x; },
    set: function (value) { this._acceleration.x = value; }
  });

  // expose y acceleration
  Object.defineProperty(this, 'ay', {
    enumerable: true,
    configurable: true,
    get: function () { return this._acceleration.y; },
    set: function (value) { this._acceleration.y = value; }
  });

  // expose read-only shape
  readOnlyProp(this, 'shape', function () { return this._shape; });

  // expose shape width as a hidden collision helper
  Object.defineProperty(this, 'width', {
    enumerable: false,
    configurable: true,
    get: function () { return this._shape.width || 0; },
    set: function (value) { this._shape.width = value; }
  });

  // expose shape height as a hidden collision helper
  Object.defineProperty(this, 'height', {
    enumerable: false,
    configurable: true,
    get: function () { return this._shape.height || 0; },
    set: function (value) { this._shape.height = value; }
  });

  // expose shape radius as a hidden collision helper
  Object.defineProperty(this, 'radius', {
    enumerable: false,
    configurable: true,
    get: function () { return this._shape.radius || 0; },
    set: function (value) { this._shape.radius = value; }
  });

});
<commit_msg>undefined should be exposed to match shape<commit_after>import .physics;
import .utils;
import .shapes.ShapeFactory as ShapeFactory;

var shapes = ShapeFactory.get();
var readOnlyProp = utils.addReadOnlyProperty;

exports = Class(function () {
  this.name = "EntityModel";

  /**
   * ~ REQUIRED
   * ~ init is the constructor for each model instance
   */
  this.init = function (opts) {
    // public props
    this.fixed = false;

    // private props
    this._shape = null;
    this._entity = opts.entity;
    this._offset = { x: 0, y: 0 };
    this._previous = { x: 0, y: 0 };
    this._velocity = { x: 0, y: 0 };
    this._acceleration = { x: 0, y: 0 };
  };

  this._initShape = function (opts) {
    this._shape = shapes.getShape(opts);
  };

  /**
   * ~ REQUIRED
   * ~ reset is called when an entity becomes active
   */
  this.reset = function (opts) {
    var hitOpts = opts.hitOpts = opts.hitOpts || {};
    hitOpts.x = opts.x || 0;
    hitOpts.y = opts.y || 0;
    hitOpts.offsetX = hitOpts.offsetX || opts.offsetX || 0;
    hitOpts.offsetY = hitOpts.offsetY || opts.offsetY || 0;
    hitOpts.width = hitOpts.width || opts.width || 0;
    hitOpts.height = hitOpts.height || opts.height || 0;
    this._initShape(hitOpts);

    this.fixed = hitOpts.fixed || false;
    this._offset.x = hitOpts.offsetX;
    this._offset.y = hitOpts.offsetY;
    this._previous.x = this.x;
    this._previous.y = this.y;
    this._velocity.x = opts.vx || 0;
    this._velocity.y = opts.vy || 0;
    this._acceleration.x = opts.ax || 0;
    this._acceleration.y = opts.ay || 0;
    return this._validate();
  };

  /**
   * ~ REQUIRED
   * ~ update is called each tick while an entity is active
   */
  this.update = function (dt) {
    this._previous.x = this.x;
    this._previous.y = this.y;
    physics.step(this, dt);
  };

  /**
   * ~ REQUIRED
   * ~ collidesWith defines how collisions are detected
   * ~ by default, only works with circles and axis-aligned rectangles
   */
  this.collidesWith = function (model) {
    return physics.collide(this, model);
  };

  /**
   * ~ REQUIRED
   * ~ resolveCollisionWith guarantees that two models are not colliding
   *   by pushing them apart
   * ~ shapes with fixed = true are never moved
   * ~ returns total distance moved to separate the objects
   */
  this.resolveCollisionWith = function (model) {
    return physics.resolveCollision(this, model);
  };

  /**
   * ~ REQUIRED
   * ~ isInside is used to determine if one entity is fully contained by another
   * ~ by default, returns a bool, and only works with circles and rects
   */
  this.isInside = function (model) {
    return physics.isInside(this, model);
  };

  /**
   * ~ _validate warns if a model is improperly configured or broken
   */
  this._validate = function () {
    var valid = true;
    if (this._shape.radius !== undefined) {
      if (this._shape.radius <= 0) {
        logger.warn("Invalid circle radius:", this._entity.uid, this._shape);
        valid = false;
      }
    } else if (this._shape.width !== undefined) {
      if (this._shape.width <= 0 || this._shape.height <= 0) {
        logger.warn("Invalid rect dimensions:", this._entity.uid, this._shape);
        valid = false;
      }
    }
    return valid;
  };

  /**
   * Public API Extensions
   * ~ properties exposed for ease of use
   */

  // expose x position
  Object.defineProperty(this, 'x', {
    enumerable: true,
    configurable: true,
    get: function () { return this._shape.x + this._offset.x; },
    set: function (value) { this._shape.x = value - this._offset.x; }
  });

  // expose y position
  Object.defineProperty(this, 'y', {
    enumerable: true,
    configurable: true,
    get: function () { return this._shape.y + this._offset.y; },
    set: function (value) { this._shape.y = value - this._offset.y; }
  });

  // expose x offset
  Object.defineProperty(this, 'offsetX', {
    enumerable: true,
    configurable: true,
    get: function () { return this._offset.x; },
    set: function (value) { this._offset.x = value; }
  });

  // expose y offset
  Object.defineProperty(this, 'offsetY', {
    enumerable: true,
    configurable: true,
    get: function () { return this._offset.y; },
    set: function (value) { this._offset.y = value; }
  });

  // expose read-only previous x position
  readOnlyProp(this, 'previousX', function () { return this._previous.x; });

  // expose read-only previous y position
  readOnlyProp(this, 'previousY', function () { return this._previous.y; });

  // expose x velocity
  Object.defineProperty(this, 'vx', {
    enumerable: true,
    configurable: true,
    get: function () { return this._velocity.x; },
    set: function (value) { this._velocity.x = value; }
  });

  // expose y velocity
  Object.defineProperty(this, 'vy', {
    enumerable: true,
    configurable: true,
    get: function () { return this._velocity.y; },
    set: function (value) { this._velocity.y = value; }
  });

  // expose x acceleration
  Object.defineProperty(this, 'ax', {
    enumerable: true,
    configurable: true,
    get: function () { return this._acceleration.x; },
    set: function (value) { this._acceleration.x = value; }
  });

  // expose y acceleration
  Object.defineProperty(this, 'ay', {
    enumerable: true,
    configurable: true,
    get: function () { return this._acceleration.y; },
    set: function (value) { this._acceleration.y = value; }
  });

  // expose read-only shape
  readOnlyProp(this, 'shape', function () { return this._shape; });

  // expose shape width as a hidden collision helper
  Object.defineProperty(this, 'width', {
    enumerable: false,
    configurable: true,
    get: function () { return this._shape.width; },
    set: function (value) { this._shape.width = value; }
  });

  // expose shape height as a hidden collision helper
  Object.defineProperty(this, 'height', {
    enumerable: false,
    configurable: true,
    get: function () { return this._shape.height; },
    set: function (value) { this._shape.height = value; }
  });

  // expose shape radius as a hidden collision helper
  Object.defineProperty(this, 'radius', {
    enumerable: false,
    configurable: true,
    get: function () { return this._shape.radius; },
    set: function (value) { this._shape.radius = value; }
  });

});
<|endoftext|>


<commit_before>'use strict';

var logger = require('logfmt');
var EventEmitter = require('events').EventEmitter;
let Connector = require('./lib/Connector');

class Service extends EventEmitter {
  constructor (mongoUrl, rabbitUrl) {
    super();
    this.qConfigs = [];
    this.queues = 0;
    this.namedQueues = new Map(); // Exchange name > exchange
    this.connection = new Connector(mongoUrl, rabbitUrl);
    this.mongoose = this.connection.getMongooseReference();
    this.connection.once('ready', this._onReady.bind(this));
    this.connection.once('lost', this._onLost.bind(this));
  }

  addQueues (queueConfigs) {
    if (!Array.isArray(queueConfigs)) {
      throw new Error('queueConfigs must be an array of queue config objects');
    }
    this.qConfigs = queueConfigs;

    this.qConfigs.forEach(qConfig => {
      // TODO: make this more programmatic, so we just shave off handler and feed in the whole config
      let newQueue = this.connection.exchange.queue({name: qConfig.name, durable: qConfig.durable});
      this.namedQueues.set(qConfig.name, newQueue);
    });
  }

  getMongooseReference () {
    return this.mongoose;
  }

  /*
  * @throws {Error} handler must be defined for all queues
  *
  */
  start () {
    this.qConfigs.forEach(queueConfig => {
      let queue = this.namedQueues.get(queueConfig.name);
      if (typeof queueConfig.handler !== 'function') {
        throw new Error('You must defined a handler for all queues');
      }
      queue.consume(queueConfig.handler);
    });
  }

  publish (queueName, payload) {
    this.connection.exchange.publish(payload, { key: queueName });
  }

  _onReady () {
    logger.log({ type: 'info', msg: 'app.ready' });
    this.emit('ready');
  }

  _onLost () {
    logger.log({ type: 'info', msg: 'app.lost' });
    this.emit('lost');
  }

  stop () {
    this.qConfigs.forEach(queueConfig => {
      this.connection.queue.ignore(queueConfig.name);
    });
  }

}

module.exports = Service;
<commit_msg>Make sure we don't double up connections<commit_after>'use strict';

var logger = require('logfmt');
var EventEmitter = require('events').EventEmitter;
let Connector = require('./lib/Connector');

class Service extends EventEmitter {
  constructor (mongoUrl, rabbitUrl) {
    super();
    this.qConfigs = [];
    this.queues = 0;
    this.namedQueues = new Map(); // Exchange name > exchange
    if (!global.connection) {
      global.connection = new Connector(mongoUrl, rabbitUrl);
    }
    this.connection = global.connection;
    this.mongoose = global.connection.getMongooseReference();
    this.connection.once('ready', this._onReady.bind(this));
    this.connection.once('lost', this._onLost.bind(this));
  }

  addQueues (queueConfigs) {
    if (!Array.isArray(queueConfigs)) {
      throw new Error('queueConfigs must be an array of queue config objects');
    }
    this.qConfigs = queueConfigs;

    this.qConfigs.forEach(qConfig => {
      // TODO: make this more programmatic, so we just shave off handler and feed in the whole config
      let newQueue = this.connection.exchange.queue({name: qConfig.name, durable: qConfig.durable});
      this.namedQueues.set(qConfig.name, newQueue);
    });
  }

  getMongooseReference () {
    return this.mongoose;
  }

  /*
  * @throws {Error} handler must be defined for all queues
  *
  */
  start () {
    this.qConfigs.forEach(queueConfig => {
      let queue = this.namedQueues.get(queueConfig.name);
      if (typeof queueConfig.handler !== 'function') {
        throw new Error('You must defined a handler for all queues');
      }
      queue.consume(queueConfig.handler);
    });
  }

  publish (queueName, payload) {
    this.connection.exchange.publish(payload, { key: queueName });
  }

  _onReady () {
    logger.log({ type: 'info', msg: 'app.ready' });
    this.emit('ready');
  }

  _onLost () {
    logger.log({ type: 'info', msg: 'app.lost' });
    this.emit('lost');
  }

  stop () {
    this.qConfigs.forEach(queueConfig => {
      this.connection.queue.ignore(queueConfig.name);
    });
  }

}

module.exports = Service;
<|endoftext|>


<commit_before>/*
 * grunt-partial-extract
 * https://github.com/tilmanjusten/grunt-partial-extract
 *
 * Copyright (c) 2014 Tilman Justen
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  var options = {};

  grunt.registerMultiTask('partial-extract', 'Extract partials from any text based file and write to distinct file.', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    options = this.options({
      pattern: [
        /<\!--\s*extract:\s*(([\w\/-_]+\/)([\w_\.-]+))(.*)-->/,
        /<\!--\s*endextract\s*-->/
      ],
            // wrap partial
            partialWrap: {
                before: '<template id="partial" {{options}}>',
                after:  '</template>'
            },
      wrap: [],
      dest: './'
    });

    grunt.log.writeln('Destination: ' + options.dest);
    grunt.verbose.writeln('Files: ' + this.files.length);
    grunt.log.writeln();

    var existingFiles = [];

    // Iterate over all specified file groups.
    this.files.forEach(function(file) {
      var content = grunt.util.normalizelf(grunt.file.read(file.src));

      if (!options.pattern[0].test(content)) {
        grunt.log.errorlns('No partials in file ' + file.src);
        grunt.verbose.writeln();

        return;
      }

      var lines = content.split(grunt.util.linefeed);
      var blocks = getPartials(lines);

      grunt.log.oklns('Found ' + blocks.length + ' partials in file ' + file.src);

      // Write blocks to separate files
      blocks.filter(function (block) {
        if (existingFiles.indexOf(block.dest) !== -1) {
          grunt.verbose.warn("Skip file " + block.dest + " which already exists.");
          return false;
        } else {
          return true;
        }
      }).map(function (block) {
        var lines = block.lines.map(properIndentation);
        var leadingWhitespace = lines.map(countWhitespace);
        var crop = leadingWhitespace.reduce(getLeadingWhitespace);
        var wrap = block.options.wrap || options.wrap;
                var partialWrapOptions = optionsToDataString(block.options);

        lines = trimLines(lines, crop);

                var templateLines = util._extend([], lines);

        // wrap partial if inline option wrap: exists
        if (wrap.length) {
          lines = raiseIndent(lines);
          lines.unshift('');
          lines.unshift(block.options.wrap[0] || '');
          lines.push('');
          lines.push(block.options.wrap[1] || '');
        }

        // add partialWrap
                if (typeof options.partialWrap === 'object') {
                    var before = options.partialWrap.before || '';
                    var after = options.partialWrap.after || '';

                    before = before.replace('{{options}}', partialWrapOptions);
                    after = after.replace('{{options}}', partialWrapOptions);

                    templateLines.unshift(before);
                    templateLines.push(after);
        }

        grunt.file.write(options.dest + block.dest, lines.join(grunt.util.linefeed));
                block.template      = templateLines.join(grunt.util.linefeed);
                block.optionsData   = partialWrapOptions;
        existingFiles.push(block.dest);
      });

      grunt.verbose.writeln();
    });

    grunt.log.oklns('Extracted ' + existingFiles.length + ' unique partials.');
  });

  /**
   * extract partials
   *
   * @param lines
   * @returns {Array}
   */
  function getPartials(lines) {
    var block;
    var add = false;
    var match;
    var blocks = [];

    // Import blocks from file
    lines.forEach(function (line) {
      if (line.match(options.pattern[1])) {
        add = false;
        blocks.push(block);
      }

      if (add) {
        block.lines.push(line);
      }

      if (match = line.match(options.pattern[0])) {
        add = true;
        block = {dest: match[1], lines: [], options: getBlockOptions(match[0])};
      }
    });

    return blocks;
  }

  /**
   * replace tabs by four spaces
   *
   * @param line
   * @return string
   */
  function properIndentation(line) {
    return line.replace(/\t/, '    ');
  }

  /**
   * count leading whitespace chars
   *
   * @param line
   * @return integer
   */
  function countWhitespace(line) {
    // return a somewhat high value for empty lines
    return line.length ? line.match(/^\s*/)[0].length : 9999;
  }

  /**
   * get lowest value of leading whitespace in a given block
   *
   * @param previous
   * @param current
   * @returns integer
   */
  function getLeadingWhitespace(previous, current) {
    return previous <= current ? previous : current;
  }

  /**
   * trim given number of leading characters
   *
   * @param lines
   * @param num Number of chars to be removed
   * @returns Array
   */
  function trimLines(lines, num) {
    return lines.map(function (line) {
      return line.substr(num);
    });
  }

  /**
   * read options from annotation
   *
   * e.g.:
   * gets:
   * {
   *   extract: 'teaser/content-teaser--small.html',
   *   wrap: [0: '
', 1: '
']
   * }
   *
   * @param annotation
   * @returns {{}}
   */
  function getBlockOptions(annotation) {
    var optionValues = annotation.split(/\w+\:/).map(function (item) {
      return item.replace(/<\!--\s?|\s?-->|^\s+|\s+$/, '');
    }).filter(function (item) {
      return item.length || false;
    });
    var optionKeys = annotation.match(/(\w+)\:/g).map(function (item) {
      return item.replace(/[^\w]/, '');
    });

    var opts = {};
    var patternMultiple = new RegExp(/\:/);

    optionValues.forEach(function (v, i) {
      var k = optionKeys[i];

      if (typeof k != 'string') {
        return;
      }

      // Treat option value as array if it has a colon
      // @todo: Allow escaped colons to be ignored
      // RegEx lookbehind negate does not work :(
      // Should be /(?<!\\)\:/
      if (v.match(patternMultiple)) {
        v = v.split(patternMultiple);
      }

      opts[k] = v;
    });

    return opts;
  }

  /**
   * raise offset in lines
   *
   * @param lines
   * @param offset
   * @returns {Array}
   */
  function raiseIndent(lines, offset) {
    offset = offset || '    ';

    return lines.map(function (line) {
      return offset + line;
    });
  }

    /**
     * Format options as string of HTML data parameters
     *
     * @param options
     * @returns {string}
     */
    function optionsToDataString(options) {
        if (typeof options !== 'object') {
            return '';
        }

        var prepared = [];
        var el;

        for (el in options) {
            if (options.hasOwnProperty(el) === false) {
                continue;
            }

            var value = options[el];
            var preparedVal = JSON.stringify(options[el]);
            var param = '';

            // Ignore callbacks
            if (typeof value === 'function') {
                continue;
            }

            // Cleanup: Remove leading and trailing " and ', replace " by ' (e.g. in stringified objects)
            preparedVal = preparedVal.replace(/^[\'\"]|[\'\"]$/g, '').replace(/\\?\"/g, '\'');

            // Build data parameter: data-name="value"
            param = 'data-' + el + '="' + preparedVal + '"';

            prepared.push(param);
        }

        return prepared.join(' ');
    }
};
<commit_msg>Store partial origin in partial data<commit_after>/*
 * grunt-partial-extract
 * https://github.com/tilmanjusten/grunt-partial-extract
 *
 * Copyright (c) 2014 Tilman Justen
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  var options = {};

  grunt.registerMultiTask('partial-extract', 'Extract partials from any text based file and write to distinct file.', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    options = this.options({
      pattern: [
        /<\!--\s*extract:\s*(([\w\/-_]+\/)([\w_\.-]+))(.*)-->/,
        /<\!--\s*endextract\s*-->/
      ],
            // wrap partial
            partialWrap: {
                before: '<template id="partial" {{options}}>',
                after:  '</template>'
            },
      wrap: [],
      dest: './'
    });

    grunt.log.writeln('Destination: ' + options.dest);
    grunt.verbose.writeln('Files: ' + this.files.length);
    grunt.log.writeln();

    var existingFiles = [];

    // Iterate over all specified file groups.
    this.files.forEach(function(file) {
      var content = grunt.util.normalizelf(grunt.file.read(file.src));

      if (!options.pattern[0].test(content)) {
        grunt.log.errorlns('No partials in file ' + file.src);
        grunt.verbose.writeln();

        return;
      }

      var lines = content.split(grunt.util.linefeed);
      var blocks = getPartials(lines);
            var origin = file.src;

      grunt.log.oklns('Found ' + blocks.length + ' partials in file ' + file.src);

      // Write blocks to separate files
      blocks.filter(function (block) {
        if (existingFiles.indexOf(block.dest) !== -1) {
          grunt.verbose.warn("Skip file " + block.dest + " which already exists.");
          return false;
        } else {
          return true;
        }
      }).map(function (block) {
        var lines = block.lines.map(properIndentation);
        var leadingWhitespace = lines.map(countWhitespace);
        var crop = leadingWhitespace.reduce(getLeadingWhitespace);
        var wrap = block.options.wrap || options.wrap;
                var partialWrapOptions = optionsToDataString(block.options);

        lines = trimLines(lines, crop);

                var templateLines = util._extend([], lines);

        // wrap partial if inline option wrap: exists
        if (wrap.length) {
          lines = raiseIndent(lines);
          lines.unshift('');
          lines.unshift(block.options.wrap[0] || '');
          lines.push('');
          lines.push(block.options.wrap[1] || '');
        }

        // add partialWrap
                if (typeof options.partialWrap === 'object') {
                    var before = options.partialWrap.before || '';
                    var after = options.partialWrap.after || '';

                    before = before.replace('{{options}}', partialWrapOptions);
                    after = after.replace('{{options}}', partialWrapOptions);

                    templateLines.unshift(before);
                    templateLines.push(after);
        }

        grunt.file.write(options.dest + block.dest, lines.join(grunt.util.linefeed));
                block.template      = templateLines.join(grunt.util.linefeed);
                block.optionsData   = partialWrapOptions;
                block.origin        = origin;

        existingFiles.push(block.dest);
      });

      grunt.verbose.writeln();
    });

    grunt.log.oklns('Extracted ' + existingFiles.length + ' unique partials.');
  });

  /**
   * extract partials
   *
   * @param lines
   * @returns {Array}
   */
  function getPartials(lines) {
    var block;
    var add = false;
    var match;
    var blocks = [];

    // Import blocks from file
    lines.forEach(function (line) {
      if (line.match(options.pattern[1])) {
        add = false;
        blocks.push(block);
      }

      if (add) {
        block.lines.push(line);
      }

      if (match = line.match(options.pattern[0])) {
        add = true;
        block = {dest: match[1], lines: [], options: getBlockOptions(match[0])};
      }
    });

    return blocks;
  }

  /**
   * replace tabs by four spaces
   *
   * @param line
   * @return string
   */
  function properIndentation(line) {
    return line.replace(/\t/, '    ');
  }

  /**
   * count leading whitespace chars
   *
   * @param line
   * @return integer
   */
  function countWhitespace(line) {
    // return a somewhat high value for empty lines
    return line.length ? line.match(/^\s*/)[0].length : 9999;
  }

  /**
   * get lowest value of leading whitespace in a given block
   *
   * @param previous
   * @param current
   * @returns integer
   */
  function getLeadingWhitespace(previous, current) {
    return previous <= current ? previous : current;
  }

  /**
   * trim given number of leading characters
   *
   * @param lines
   * @param num Number of chars to be removed
   * @returns Array
   */
  function trimLines(lines, num) {
    return lines.map(function (line) {
      return line.substr(num);
    });
  }

  /**
   * read options from annotation
   *
   * e.g.:
   * gets:
   * {
   *   extract: 'teaser/content-teaser--small.html',
   *   wrap: [0: '
', 1: '
']
   * }
   *
   * @param annotation
   * @returns {{}}
   */
  function getBlockOptions(annotation) {
    var optionValues = annotation.split(/\w+\:/).map(function (item) {
      return item.replace(/<\!--\s?|\s?-->|^\s+|\s+$/, '');
    }).filter(function (item) {
      return item.length || false;
    });
    var optionKeys = annotation.match(/(\w+)\:/g).map(function (item) {
      return item.replace(/[^\w]/, '');
    });

    var opts = {};
    var patternMultiple = new RegExp(/\:/);

    optionValues.forEach(function (v, i) {
      var k = optionKeys[i];

      if (typeof k != 'string') {
        return;
      }

      // Treat option value as array if it has a colon
      // @todo: Allow escaped colons to be ignored
      // RegEx lookbehind negate does not work :(
      // Should be /(?<!\\)\:/
      if (v.match(patternMultiple)) {
        v = v.split(patternMultiple);
      }

      opts[k] = v;
    });

    return opts;
  }

  /**
   * raise offset in lines
   *
   * @param lines
   * @param offset
   * @returns {Array}
   */
  function raiseIndent(lines, offset) {
    offset = offset || '    ';

    return lines.map(function (line) {
      return offset + line;
    });
  }

    /**
     * Format options as string of HTML data parameters
     *
     * @param options
     * @returns {string}
     */
    function optionsToDataString(options) {
        if (typeof options !== 'object') {
            return '';
        }

        var prepared = [];
        var el;

        for (el in options) {
            if (options.hasOwnProperty(el) === false) {
                continue;
            }

            var value = options[el];
            var preparedVal = JSON.stringify(options[el]);
            var param = '';

            // Ignore callbacks
            if (typeof value === 'function') {
                continue;
            }

            // Cleanup: Remove leading and trailing " and ', replace " by ' (e.g. in stringified objects)
            preparedVal = preparedVal.replace(/^[\'\"]|[\'\"]$/g, '').replace(/\\?\"/g, '\'');

            // Build data parameter: data-name="value"
            param = 'data-' + el + '="' + preparedVal + '"';

            prepared.push(param);
        }

        return prepared.join(' ');
    }
};
<|endoftext|>


<commit_before>var creep_asshealer = {

    /** @param {Creep} creep **/
    run: function(creep) {
        var unboostedTough = 0;
        var unboostedHeal = 0;

        creep.body.forEach(function(thisPart) {
            if (thisPart.type == HEAL && !thisPart.boost){
                unboostedHeal = unboostedHeal + 1;
            }

            if (thisPart.type == TOUGH && !thisPart.boost){
                unboostedTough = unboostedTough + 1;
            }
        });

        //console.log("unboosted heal : " + unboostedHeal + "| unboosted Tough : " + unboostedTough);

        var targetAttacker = _.filter(Game.creeps, (tCreep) => tCreep.name == creep.memory.attackerName);
        if (targetAttacker.length) {
            if (creep.pos.x == 0 || creep.pos.x == 49 || creep.pos.y == 0 || creep.pos.y == 49) {
                var xTarget = 1;
                var yTarget = 1;
                if (creep.pos.x == 49) {
                    xTarget = 48;
                }
                if (creep.pos.y = 49) {
                    yTarget = 48;
                }
                creep.moveTo(xTarget, yTarget);
            } else {
                creep.moveTo(targetAttacker[0], {
                    ignoreCreeps: true
                });
            }

            if (creep.hits < creep.hitsMax - 99) {
                creep.heal(creep);
            } else if (targetAttacker[0].hits < targetAttacker[0].hitsMax) {
                if (creep.pos.getRangeTo(targetAttacker[0]) > 1) {
                    creep.rangedHeal(targetAttacker[0]);
                } else {
                    creep.heal(targetAttacker[0]);
                }
            } else {
                var hurtAlly = creep.pos.findInRange(FIND_MY_CREEPS, 3, {
                    filter: (thisCreep) => thisCreep.hits < thisCreep.hitsMax
                });
                if (hurtAlly.length > 0) {
                    if (creep.pos.getRangeTo(hurtAlly[0]) > 1) {
                        creep.rangedHeal(hurtAlly[0]);
                    } else {
                        creep.heal(hurtAlly[0]);
                    }
                }
            }
        } else {
            if (Game.flags["RallyHere"]) {
                creep.moveTo(Game.flags["RallyHere"]);
            }
            var newTarget = creep.pos.findInRange(FIND_MY_CREEPS, 2, {
                filter: (mCreep) => (mCreep.memory.priority == "assattacker")
            });
            if (newTarget.length) {
                creep.memory.attackerName == newTarget[0].name;
            }
        }
    }

};

module.exports = creep_asshealer;<commit_msg>small tweak<commit_after>var creep_asshealer = {

    /** @param {Creep} creep **/
    run: function(creep) {
        var unboostedTough = 0;
        var unboostedHeal = 0;

        creep.body.forEach(function(thisPart) {
            if (thisPart.type == HEAL && !thisPart.boost) {
                unboostedHeal = unboostedHeal + 1;
            }

            if (thisPart.type == TOUGH && !thisPart.boost) {
                unboostedTough = unboostedTough + 1;
            }
        });

        //console.log("unboosted heal : " + unboostedHeal + "| unboosted Tough : " + unboostedTough);

        var targetAttacker = _.filter(Game.creeps, (tCreep) => tCreep.name == creep.memory.attackerName);
        if (targetAttacker.length) {
            if (creep.pos.x == 0 || creep.pos.x == 49 || creep.pos.y == 0 || creep.pos.y == 49) {
                var xTarget = 1;
                var yTarget = 1;
                if (creep.pos.x == 49) {
                    xTarget = 48;
                }
                if (creep.pos.y = 49) {
                    yTarget = 48;
                }
                creep.moveTo(xTarget, yTarget);
            } else {
                if (creep.room.name == creep.memory.homeRoom) {
                    creep.moveTo(targetAttacker[0]);
                } else {
                    creep.moveTo(targetAttacker[0], {
                        ignoreCreeps: true
                    });
                }

            }

            if (creep.hits < creep.hitsMax - 99) {
                creep.heal(creep);
            } else if (targetAttacker[0].hits < targetAttacker[0].hitsMax) {
                if (creep.pos.getRangeTo(targetAttacker[0]) > 1) {
                    creep.rangedHeal(targetAttacker[0]);
                } else {
                    creep.heal(targetAttacker[0]);
                }
            } else {
                var hurtAlly = creep.pos.findInRange(FIND_MY_CREEPS, 3, {
                    filter: (thisCreep) => thisCreep.hits < thisCreep.hitsMax
                });
                if (hurtAlly.length > 0) {
                    if (creep.pos.getRangeTo(hurtAlly[0]) > 1) {
                        creep.rangedHeal(hurtAlly[0]);
                    } else {
                        creep.heal(hurtAlly[0]);
                    }
                }
            }
        } else {
            if (Game.flags["RallyHere"]) {
                creep.moveTo(Game.flags["RallyHere"]);
            }
            var newTarget = creep.pos.findInRange(FIND_MY_CREEPS, 2, {
                filter: (mCreep) => (mCreep.memory.priority == "assattacker")
            });
            if (newTarget.length) {
                creep.memory.attackerName == newTarget[0].name;
            }
        }
    }

};

module.exports = creep_asshealer;<|endoftext|>