<commit_before>/**
 * Copyright 2013-2020 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * 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.
 */
/* eslint-disable no-console */
const chalk = require('chalk');
const didYouMean = require('didyoumean');
const meow = require('meow');
const yeoman = require('yeoman-environment');
const _ = require('lodash');
const path = require('path');

const { normalizeBlueprintName, packageNameToNamespace, loadYoRc, loadBlueprintsFromConfiguration } = require('../generators/utils');

const CLI_NAME = 'jhipster';
const GENERATOR_NAME = 'generator-jhipster';

const SUCCESS_MESSAGE = 'Congratulations, JHipster execution is complete!';

const debug = function(msg) {
    if (this.debugEnabled) {
        console.log(`${chalk.blue('DEBUG!')}  ${msg}`);
    }
};

const info = function(msg) {
    console.info(`${chalk.green.bold('INFO!')} ${msg}`);
};

const log = function(msg) {
    console.log(msg);
};

const error = function(msg, trace) {
    console.error(`${chalk.red(msg)}`);
    if (trace) {
        console.log(trace);
    }
    process.exitCode = 1;
};

/**
 *  Use with carefull.
 *  process.exit is not recommended by Node.js.
 *  Refer to https://nodejs.org/api/process.html#process_process_exit_code.
 */
const fatal = function(msg, trace) {
    console.error(`${chalk.red(msg)}`);
    if (trace) {
        console.log(trace);
    }
    process.exit(1);
};

const init = function(program) {
    program.option('-d, --debug', 'enable debugger');

    const argv = program.normalize(process.argv);
    this.debugEnabled = program.debug = argv.includes('-d') || argv.includes('--debug'); // Need this early

    if (this.debugEnabled) {
        info('Debug logging is on');
    }
};

const logger = {
    init,
    debug,
    info,
    log,
    error,
    fatal
};

const toString = item => {
    if (typeof item == 'object') {
        if (Array.isArray(item)) {
            return item.map(it => toString(it)).join(', ');
        }
        return Object.keys(item)
            .map(k => `${k}: ${typeof item[k] != 'function' && typeof item[k] != 'object' ? toString(item[k]) : 'Object'}`)
            .join(', ');
    }
    return item ? item.toString() : item;
};

const initHelp = (program, cliName) => {
    program.on('--help', () => {
        logger.debug('Adding additional help info');
        logger.info(`  For more info visit ${chalk.blue('https://www.jhipster.tech')}`);
        logger.info('');
    });

    program.on('command:*', name => {
        console.error(chalk.red(`${chalk.yellow(name)} is not a known command. See '${chalk.white(`${cliName} --help`)}'.`));

        const cmd = Object.values(name).join('');
        const availableCommands = program.commands.map(c => c._name);

        const suggestion = didYouMean(cmd, availableCommands);
        if (suggestion) {
            logger.info(`Did you mean ${chalk.yellow(suggestion)}?`);
        }

        process.exit(1);
    });
};

/**
 * Get arguments
 */
const getArgs = opts => {
    if (opts.argument) {
        return `[${opts.argument.join(' ')}]`;
    }
    return '';
};

/**
 * Get options from arguments
 */
const getOptionsFromArgs = args => {
    const options = [];
    args.forEach(item => {
        if (typeof item == 'string') {
            options.push(item);
        } else if (typeof item == 'object') {
            if (Array.isArray(item)) {
                options.push(...item);
            }
        }
    });
    return options;
};

/* Convert option objects to command line args */
const getOptionAsArgs = (options, withEntities, force) => {
    const args = Object.entries(options).map(([key, value]) => {
        const prefix = key.length === 1 ? '-' : '--';
        if (value === true) {
            return `${prefix}${_.kebabCase(key)}`;
        }
        if (value === false) {
            return `${prefix}no-${_.kebabCase(key)}`;
        }
        return value ? `${prefix}${_.kebabCase(key)} ${value}` : '';
    });
    if (withEntities) args.push('--with-entities');
    if (force) args.push('--force');
    args.push('--from-cli');
    logger.debug(`converted options: ${args}`);
    return _.uniq(args.join(' ').split(' ')).filter(it => it !== '');
};

/**
 *  Get options for the command
 */
const getCommand = (cmd, args, opts) => {
    let options = [];
    if (opts && opts.argument && opts.argument.length > 0) {
        logger.debug('Arguments found');
        options = getOptionsFromArgs(args);
    }
    if (args && args.length === 1) {
        logger.debug('No Arguments found.');
    }
    const cmdArgs = options.join(' ').trim();
    logger.debug(`cmdArgs: ${cmdArgs}`);
    return `${cmd}${cmdArgs ? ` ${cmdArgs}` : ''}`;
};

const getCommandOptions = (pkg, argv) => {
    const options = meow({ help: false, pkg, argv });
    const flags = options ? options.flags : null;
    if (flags) {
        flags['from-cli'] = true;
        // Add un-camelized options too, for legacy
        Object.keys(flags).forEach(key => {
            const legacyKey = key.replace(/[A-Z]/g, m => `-${m.toLowerCase()}`);
            flags[legacyKey] = flags[key];
        });
        return flags;
    }
    return { 'from-cli': true };
};

const doneFactory = successMsg => {
    return errorMsg => {
        if (errorMsg) {
            logger.error(`ERROR! ${errorMsg}`);
        } else if (successMsg) {
            logger.info(chalk.green.bold(successMsg));
        }
    };
};

const printSuccess = () => {
    if (process.exitCode === undefined || process.exitCode === 0) {
        logger.info(chalk.green.bold(SUCCESS_MESSAGE));
    } else {
        logger.error(`ERROR! JHipster finished with code ${process.exitCode}`);
    }
};

const createYeomanEnv = packagePatterns => {
    const env = yeoman.createEnv();
    // Register jhipster generators.
    env.lookup({ packagePaths: [path.join(__dirname, '..')] });
    if (packagePatterns) {
        // Lookup for blueprints.
        env.lookup({ filterPaths: true, packagePatterns });
    }
    return env;
};

const loadBlueprints = () => {
    const blueprintNames = [];
    const indexOfBlueprintArgv = process.argv.indexOf('--blueprint');
    if (indexOfBlueprintArgv > -1) {
        blueprintNames.push(process.argv[indexOfBlueprintArgv + 1]);
    }
    const indexOfBlueprintsArgv = process.argv.indexOf('--blueprints');
    if (indexOfBlueprintsArgv > -1) {
        blueprintNames.push(...process.argv[indexOfBlueprintsArgv + 1].split(','));
    }
    if (!blueprintNames.length) {
        return [];
    }
    return blueprintNames.filter((v, i, a) => a.indexOf(v) === i).map(v => normalizeBlueprintName(v));
};

const loadBlueprintsFromYoRc = () => {
    const yoRc = loadYoRc();
    if (!yoRc || !yoRc['generator-jhipster']) {
        return [];
    }
    return loadBlueprintsFromConfiguration(yoRc['generator-jhipster']);
};

const getBlueprintPackagePaths = (env, blueprints) => {
    if (!blueprints) {
        return undefined;
    }
    return blueprints.map(blueprint => {
        const namespace = packageNameToNamespace(blueprint);
        const packagePath = env.getPackagePath(namespace);
        if (!packagePath) {
            logger.fatal(
                `The ${chalk.yellow(blueprint)} blueprint provided is not installed. Please install it using command ${chalk.yellow(
                    `npm i -g ${blueprint}`
                )}`
            );
        }
        return [blueprint, packagePath];
    });
};

const loadBlueprintCommands = blueprintPackagePaths => {
    if (!blueprintPackagePaths) {
        return undefined;
    }
    let result;
    blueprintPackagePaths.forEach(([blueprint, packagePath]) => {
        /* eslint-disable import/no-dynamic-require */
        /* eslint-disable global-require */
        try {
            const blueprintCommands = require(`${packagePath}/cli/commands`);
            result = { ...result, ...blueprintCommands };
        } catch (e) {
            const msg = `No custom commands found within blueprint: ${blueprint} at ${packagePath}`;
            /* eslint-disable no-console */
            console.info(`${chalk.green.bold('INFO!')} ${msg}`);
        }
    });
    return result;
};

const loadSharedOptions = blueprintPackagePaths => {
    function joiner(objValue, srcValue) {
        if (objValue === undefined) {
            return srcValue;
        }
        if (Array.isArray(objValue) && Array.isArray(srcValue)) {
            return objValue.concat(srcValue);
        }
        if (Array.isArray(objValue)) {
            return [...objValue, srcValue];
        }
        if (Array.isArray(srcValue)) {
            return [objValue, ...srcValue];
        }
        return [objValue, srcValue];
    }

    function loadSharedOptionsFromFile(sharedOptionsFile, msg, errorMsg) {
        /* eslint-disable import/no-dynamic-require */
        /* eslint-disable global-require */
        try {
            const opts = require(sharedOptionsFile);
            /* eslint-disable no-console */
            if (msg) {
                console.info(`${chalk.green.bold('INFO!')} ${msg}`);
            }
            return opts;
        } catch (e) {
            if (errorMsg) {
                console.info(`${chalk.green.bold('INFO!')} ${errorMsg}`);
            }
        }
        return {};
    }

    const localPath = './.jhipster/sharedOptions';
    let result = loadSharedOptionsFromFile(path.resolve(localPath), `SharedOptions found at local config ${localPath}`);

    if (!blueprintPackagePaths) {
        return undefined;
    }

    blueprintPackagePaths.forEach(([blueprint, packagePath]) => {
        const errorMsg = `No custom sharedOptions found within blueprint: ${blueprint} at ${packagePath}`;
        const opts = loadSharedOptionsFromFile(`${packagePath}/cli/sharedOptions`, undefined, errorMsg);
        result = _.mergeWith(result, opts, joiner);
    });
    return result;
};

module.exports = {
    CLI_NAME,
    GENERATOR_NAME,
    toString,
    logger,
    initHelp,
    getArgs,
    getOptionsFromArgs,
    getCommand,
    getCommandOptions,
    doneFactory,
    done: doneFactory(SUCCESS_MESSAGE),
    printSuccess,
    createYeomanEnv,
    loadBlueprints,
    loadBlueprintsFromYoRc,
    getBlueprintPackagePaths,
    loadBlueprintCommands,
    loadSharedOptions,
    getOptionAsArgs
};
<commit_msg>Don't run lookup without blueprints. (#11618)<commit_after>/**
 * Copyright 2013-2020 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * 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.
 */
/* eslint-disable no-console */
const chalk = require('chalk');
const didYouMean = require('didyoumean');
const meow = require('meow');
const yeoman = require('yeoman-environment');
const _ = require('lodash');
const path = require('path');

const { normalizeBlueprintName, packageNameToNamespace, loadYoRc, loadBlueprintsFromConfiguration } = require('../generators/utils');

const CLI_NAME = 'jhipster';
const GENERATOR_NAME = 'generator-jhipster';

const SUCCESS_MESSAGE = 'Congratulations, JHipster execution is complete!';

const debug = function(msg) {
    if (this.debugEnabled) {
        console.log(`${chalk.blue('DEBUG!')}  ${msg}`);
    }
};

const info = function(msg) {
    console.info(`${chalk.green.bold('INFO!')} ${msg}`);
};

const log = function(msg) {
    console.log(msg);
};

const error = function(msg, trace) {
    console.error(`${chalk.red(msg)}`);
    if (trace) {
        console.log(trace);
    }
    process.exitCode = 1;
};

/**
 *  Use with carefull.
 *  process.exit is not recommended by Node.js.
 *  Refer to https://nodejs.org/api/process.html#process_process_exit_code.
 */
const fatal = function(msg, trace) {
    console.error(`${chalk.red(msg)}`);
    if (trace) {
        console.log(trace);
    }
    process.exit(1);
};

const init = function(program) {
    program.option('-d, --debug', 'enable debugger');

    const argv = program.normalize(process.argv);
    this.debugEnabled = program.debug = argv.includes('-d') || argv.includes('--debug'); // Need this early

    if (this.debugEnabled) {
        info('Debug logging is on');
    }
};

const logger = {
    init,
    debug,
    info,
    log,
    error,
    fatal
};

const toString = item => {
    if (typeof item == 'object') {
        if (Array.isArray(item)) {
            return item.map(it => toString(it)).join(', ');
        }
        return Object.keys(item)
            .map(k => `${k}: ${typeof item[k] != 'function' && typeof item[k] != 'object' ? toString(item[k]) : 'Object'}`)
            .join(', ');
    }
    return item ? item.toString() : item;
};

const initHelp = (program, cliName) => {
    program.on('--help', () => {
        logger.debug('Adding additional help info');
        logger.info(`  For more info visit ${chalk.blue('https://www.jhipster.tech')}`);
        logger.info('');
    });

    program.on('command:*', name => {
        console.error(chalk.red(`${chalk.yellow(name)} is not a known command. See '${chalk.white(`${cliName} --help`)}'.`));

        const cmd = Object.values(name).join('');
        const availableCommands = program.commands.map(c => c._name);

        const suggestion = didYouMean(cmd, availableCommands);
        if (suggestion) {
            logger.info(`Did you mean ${chalk.yellow(suggestion)}?`);
        }

        process.exit(1);
    });
};

/**
 * Get arguments
 */
const getArgs = opts => {
    if (opts.argument) {
        return `[${opts.argument.join(' ')}]`;
    }
    return '';
};

/**
 * Get options from arguments
 */
const getOptionsFromArgs = args => {
    const options = [];
    args.forEach(item => {
        if (typeof item == 'string') {
            options.push(item);
        } else if (typeof item == 'object') {
            if (Array.isArray(item)) {
                options.push(...item);
            }
        }
    });
    return options;
};

/* Convert option objects to command line args */
const getOptionAsArgs = (options, withEntities, force) => {
    const args = Object.entries(options).map(([key, value]) => {
        const prefix = key.length === 1 ? '-' : '--';
        if (value === true) {
            return `${prefix}${_.kebabCase(key)}`;
        }
        if (value === false) {
            return `${prefix}no-${_.kebabCase(key)}`;
        }
        return value ? `${prefix}${_.kebabCase(key)} ${value}` : '';
    });
    if (withEntities) args.push('--with-entities');
    if (force) args.push('--force');
    args.push('--from-cli');
    logger.debug(`converted options: ${args}`);
    return _.uniq(args.join(' ').split(' ')).filter(it => it !== '');
};

/**
 *  Get options for the command
 */
const getCommand = (cmd, args, opts) => {
    let options = [];
    if (opts && opts.argument && opts.argument.length > 0) {
        logger.debug('Arguments found');
        options = getOptionsFromArgs(args);
    }
    if (args && args.length === 1) {
        logger.debug('No Arguments found.');
    }
    const cmdArgs = options.join(' ').trim();
    logger.debug(`cmdArgs: ${cmdArgs}`);
    return `${cmd}${cmdArgs ? ` ${cmdArgs}` : ''}`;
};

const getCommandOptions = (pkg, argv) => {
    const options = meow({ help: false, pkg, argv });
    const flags = options ? options.flags : null;
    if (flags) {
        flags['from-cli'] = true;
        // Add un-camelized options too, for legacy
        Object.keys(flags).forEach(key => {
            const legacyKey = key.replace(/[A-Z]/g, m => `-${m.toLowerCase()}`);
            flags[legacyKey] = flags[key];
        });
        return flags;
    }
    return { 'from-cli': true };
};

const doneFactory = successMsg => {
    return errorMsg => {
        if (errorMsg) {
            logger.error(`ERROR! ${errorMsg}`);
        } else if (successMsg) {
            logger.info(chalk.green.bold(successMsg));
        }
    };
};

const printSuccess = () => {
    if (process.exitCode === undefined || process.exitCode === 0) {
        logger.info(chalk.green.bold(SUCCESS_MESSAGE));
    } else {
        logger.error(`ERROR! JHipster finished with code ${process.exitCode}`);
    }
};

const createYeomanEnv = packagePatterns => {
    const env = yeoman.createEnv();
    // Register jhipster generators.
    env.lookup({ packagePaths: [path.join(__dirname, '..')] });
    if (packagePatterns && packagePatterns.length > 0) {
        // Lookup for blueprints.
        env.lookup({ filterPaths: true, packagePatterns });
    }
    return env;
};

const loadBlueprints = () => {
    const blueprintNames = [];
    const indexOfBlueprintArgv = process.argv.indexOf('--blueprint');
    if (indexOfBlueprintArgv > -1) {
        blueprintNames.push(process.argv[indexOfBlueprintArgv + 1]);
    }
    const indexOfBlueprintsArgv = process.argv.indexOf('--blueprints');
    if (indexOfBlueprintsArgv > -1) {
        blueprintNames.push(...process.argv[indexOfBlueprintsArgv + 1].split(','));
    }
    if (!blueprintNames.length) {
        return [];
    }
    return blueprintNames.filter((v, i, a) => a.indexOf(v) === i).map(v => normalizeBlueprintName(v));
};

const loadBlueprintsFromYoRc = () => {
    const yoRc = loadYoRc();
    if (!yoRc || !yoRc['generator-jhipster']) {
        return [];
    }
    return loadBlueprintsFromConfiguration(yoRc['generator-jhipster']);
};

const getBlueprintPackagePaths = (env, blueprints) => {
    if (!blueprints) {
        return undefined;
    }
    return blueprints.map(blueprint => {
        const namespace = packageNameToNamespace(blueprint);
        const packagePath = env.getPackagePath(namespace);
        if (!packagePath) {
            logger.fatal(
                `The ${chalk.yellow(blueprint)} blueprint provided is not installed. Please install it using command ${chalk.yellow(
                    `npm i -g ${blueprint}`
                )}`
            );
        }
        return [blueprint, packagePath];
    });
};

const loadBlueprintCommands = blueprintPackagePaths => {
    if (!blueprintPackagePaths) {
        return undefined;
    }
    let result;
    blueprintPackagePaths.forEach(([blueprint, packagePath]) => {
        /* eslint-disable import/no-dynamic-require */
        /* eslint-disable global-require */
        try {
            const blueprintCommands = require(`${packagePath}/cli/commands`);
            result = { ...result, ...blueprintCommands };
        } catch (e) {
            const msg = `No custom commands found within blueprint: ${blueprint} at ${packagePath}`;
            /* eslint-disable no-console */
            console.info(`${chalk.green.bold('INFO!')} ${msg}`);
        }
    });
    return result;
};

const loadSharedOptions = blueprintPackagePaths => {
    function joiner(objValue, srcValue) {
        if (objValue === undefined) {
            return srcValue;
        }
        if (Array.isArray(objValue) && Array.isArray(srcValue)) {
            return objValue.concat(srcValue);
        }
        if (Array.isArray(objValue)) {
            return [...objValue, srcValue];
        }
        if (Array.isArray(srcValue)) {
            return [objValue, ...srcValue];
        }
        return [objValue, srcValue];
    }

    function loadSharedOptionsFromFile(sharedOptionsFile, msg, errorMsg) {
        /* eslint-disable import/no-dynamic-require */
        /* eslint-disable global-require */
        try {
            const opts = require(sharedOptionsFile);
            /* eslint-disable no-console */
            if (msg) {
                console.info(`${chalk.green.bold('INFO!')} ${msg}`);
            }
            return opts;
        } catch (e) {
            if (errorMsg) {
                console.info(`${chalk.green.bold('INFO!')} ${errorMsg}`);
            }
        }
        return {};
    }

    const localPath = './.jhipster/sharedOptions';
    let result = loadSharedOptionsFromFile(path.resolve(localPath), `SharedOptions found at local config ${localPath}`);

    if (!blueprintPackagePaths) {
        return undefined;
    }

    blueprintPackagePaths.forEach(([blueprint, packagePath]) => {
        const errorMsg = `No custom sharedOptions found within blueprint: ${blueprint} at ${packagePath}`;
        const opts = loadSharedOptionsFromFile(`${packagePath}/cli/sharedOptions`, undefined, errorMsg);
        result = _.mergeWith(result, opts, joiner);
    });
    return result;
};

module.exports = {
    CLI_NAME,
    GENERATOR_NAME,
    toString,
    logger,
    initHelp,
    getArgs,
    getOptionsFromArgs,
    getCommand,
    getCommandOptions,
    doneFactory,
    done: doneFactory(SUCCESS_MESSAGE),
    printSuccess,
    createYeomanEnv,
    loadBlueprints,
    loadBlueprintsFromYoRc,
    getBlueprintPackagePaths,
    loadBlueprintCommands,
    loadSharedOptions,
    getOptionAsArgs
};
<|endoftext|>


<commit_before>
import DBFactory from "../compiled/DBFactory"
import DatabaseSchema from "../compiled/schema/DatabaseSchema"
import ObjectStoreSchema from "../compiled/schema/ObjectStoreSchema"

describe("DBFactory", () => {

  const DB_NAME = "testing database"
  const NONEXISTING_DB_NAME = "nonexisting database"
  const OBJECT_STORE_NAME = "testingStore"

  beforeEach((done) => {
    let request = indexedDB.open(DB_NAME, 1)
    request.onerror = () => fail(request.error)
    request.onblocked = () => fail("failed to create the database")

    request.onupgradeneeded = () => {
      let database = request.result
      database.onerror = fail
      database.createObjectStore(OBJECT_STORE_NAME)
    }

    request.onsuccess = () => {
      let database = request.result
      database.close()

      done()
    }
  })

  afterEach((done) => {
    let request = indexedDB.deleteDatabase(DB_NAME)
    request.onsuccess = () => {
      let request = indexedDB.deleteDatabase(NONEXISTING_DB_NAME)
      request.onsuccess = done
      request.onerror = () => fail(request.error)
    }
    request.onerror = () => fail(request.error)
  })

  it("should connect to an existing database", (done) => {
    DBFactory.open(DB_NAME,
      new DatabaseSchema(1,
        new ObjectStoreSchema(OBJECT_STORE_NAME, null, false)
      )
    ).then((database) => {
      database.close()
      done()
    }).catch((error) => fail(error))
  })

  it("should delete an existing database", (done) => {
    DBFactory.deleteDatabase(DB_NAME).then((deletedVersion) => {
      expect(deletedVersion).toBe(1)
      done()
    }).catch(fail)
  })

  it("should trigger creation of a non-existing database", (done) => {
    DBFactory.open(NONEXISTING_DB_NAME,
      new DatabaseSchema(1,
        new ObjectStoreSchema(OBJECT_STORE_NAME, null, false)
      )
    ).then((database) => {
      database.close()
      done()
    }).catch((error) => fail(error))
  })

  it("should trigger schema upgrade of an outdated database", (done) => {
    DBFactory.open(DB_NAME,
      new DatabaseSchema(1,
        new ObjectStoreSchema(OBJECT_STORE_NAME, null, false)
      ),
      new DatabaseSchema(1,
        new ObjectStoreSchema(OBJECT_STORE_NAME, null, false),
        new ObjectStoreSchema("some other object store", null, false)
      )
    ).then((database) => {
      database.close()
      done()
    }).catch((error) => fail(error))
  })
})
<commit_msg>fixed tests<commit_after>
import DBFactory from "../compiled/DBFactory"
import DatabaseSchema from "../compiled/schema/DatabaseSchema"
import ObjectStoreSchema from "../compiled/schema/ObjectStoreSchema"
import UpgradedDatabaseSchema from "../compiled/schema/UpgradedDatabaseSchema"

describe("DBFactory", () => {

  const DB_NAME = "testing database"
  const NONEXISTING_DB_NAME = "nonexisting database"
  const OBJECT_STORE_NAME = "testingStore"

  beforeEach((done) => {
    let request = indexedDB.open(DB_NAME, 1)
    request.onerror = () => fail(request.error)
    request.onblocked = () => fail("failed to create the database")

    request.onupgradeneeded = () => {
      let database = request.result
      database.onerror = fail
      database.createObjectStore(OBJECT_STORE_NAME)
    }

    request.onsuccess = () => {
      let database = request.result
      database.close()

      done()
    }
  })

  afterEach((done) => {
    let request = indexedDB.deleteDatabase(DB_NAME)
    request.onsuccess = () => {
      let request = indexedDB.deleteDatabase(NONEXISTING_DB_NAME)
      request.onsuccess = done
      request.onerror = () => fail(request.error)
    }
    request.onerror = () => fail(request.error)
  })

  it("should connect to an existing database", (done) => {
    DBFactory.open(DB_NAME,
      new DatabaseSchema(1,
        new ObjectStoreSchema(OBJECT_STORE_NAME, null, false)
      )
    ).then((database) => {
      database.close()
      done()
    }).catch((error) => fail(error))
  })

  it("should delete an existing database", (done) => {
    DBFactory.deleteDatabase(DB_NAME).then((deletedVersion) => {
      expect(deletedVersion).toBe(1)
      done()
    }).catch(fail)
  })

  it("should trigger creation of a non-existing database", (done) => {
    DBFactory.open(NONEXISTING_DB_NAME,
      new DatabaseSchema(1,
        new ObjectStoreSchema(OBJECT_STORE_NAME, null, false)
      )
    ).then((database) => {
      database.close()
      done()
    }).catch((error) => fail(error))
  })

  it("should trigger schema upgrade of an outdated database", (done) => {
    DBFactory.open(DB_NAME,
      new DatabaseSchema(1,
        new ObjectStoreSchema(OBJECT_STORE_NAME, null, false)
      ),
      new UpgradedDatabaseSchema(2,
        [],
        [
          new ObjectStoreSchema(OBJECT_STORE_NAME, null, false),
          new ObjectStoreSchema("some other object store", null, false)
        ]
      )
    ).then((database) => {
      database.close()
      done()
    }).catch((error) => fail(error))
  })
})
<|endoftext|>


<commit_before>var webpageSpellingExtension = {
    settings: null,
    words: null,
    sounds: null,
    mistakes: null,

    setSettings: function(settings) {
        this.settings = settings;
    },

    setDictionaries: function(dictionaries) {
        this.sounds = dictionaries.sounds;
        this.mistakes = dictionaries.mistakes;
    },

    addUnderline: function($el, match) {
        var re = new RegExp(match, 'g');
        $el.html($el.html().replace(re, ''+match+''));
    },

    checkSpelling: function(word, $el) {
        var wordSound = this.soundex(word);

        if(typeof this.sounds[wordSound] != 'undefined') {
            if(this.sounds[wordSound].indexOf(word.toLowerCase())<0) {
                this.addUnderline($el, word);
            }
        } else {
            this.addUnderline($el, word);
        }
    },

    soundex: function (s) {
        var a = s.toLowerCase().split('')
            f = a.shift(),
            r = '',
            codes = {
                a: '', e: '', i: '', o: '', u: '',
                b: 1, f: 1, p: 1, v: 1,
                c: 2, g: 2, j: 2, k: 2, q: 2, s: 2, x: 2, z: 2,
                d: 3, t: 3,
                l: 4,
                m: 5, n: 5,
                r: 6
            };

        r = f +
            a
            .map(function (v, i, a) { return codes[v] })
            .filter(function (v, i, a) {
                return ((i === 0) ? v !== codes[f] : v !== a[i - 1]);
            })
            .join('');

        return (r + '000').slice(0, 4).toUpperCase();
    }
};

jQuery(document).ready(function(){
    chrome.extension.sendRequest({method: "getSettings"}, function(response) {
        webpageSpellingExtension.setSettings(response.data);
    });

    chrome.extension.sendRequest({method: "getDictionaries"}, function(response) {
        webpageSpellingExtension.setDictionaries(response.data);

        jQuery('div,span,p,a,h1,h2,h3,h4,h5,h6,h7,h8,td').each(function(){
            var $elem = jQuery(this);
            var words = jQuery.trim(jQuery(this).text().replace(/[^a-zA-Z -]/g,"").replace(/ +/g, " ")).split(" ");
            jQuery.each(words,function(index, value) {
                if(value != '') {
                    //webpageSpellingExtension.checkSpelling(value, $elem);
                }
            });
        });
    });
});<commit_msg>working on replacement code<commit_after>var webpageSpellingExtension = {
    settings: null,
    words: null,
    sounds: null,
    mistakes: null,

    setSettings: function(settings) {
        this.settings = settings;
    },

    setDictionaries: function(dictionaries) {
        this.sounds = dictionaries.sounds;
        this.mistakes = dictionaries.mistakes;
    },

    addUnderline: function($el, match) {
        var re = new RegExp(match, 'g');
        console.log(match);
        console.log($el);
        console.log($el.text());
        //var newHTML = $el.html().replace(re, ''+match+'');
        //$el.html(newHTML);
    },

    checkSpelling: function(word, $el) {
        var test = jQuery.trim(word.replace(/[0-9]/g,''));

        if(test != '') {
            var wordSound = this.soundex(word);

            if(typeof this.sounds[wordSound] != 'undefined') {
                if(this.sounds[wordSound].indexOf(word.toLowerCase())<0) {
                    this.addUnderline($el, word);
                }
            } else {
                this.addUnderline($el, word);
            }
        }
    },

    soundex: function (s) {
        var a = s.toLowerCase().split('')
            f = a.shift(),
            r = '',
            codes = {
                a: '', e: '', i: '', o: '', u: '',
                b: 1, f: 1, p: 1, v: 1,
                c: 2, g: 2, j: 2, k: 2, q: 2, s: 2, x: 2, z: 2,
                d: 3, t: 3,
                l: 4,
                m: 5, n: 5,
                r: 6
            };

        r = f +
            a
            .map(function (v, i, a) { return codes[v] })
            .filter(function (v, i, a) {
                return ((i === 0) ? v !== codes[f] : v !== a[i - 1]);
            })
            .join('');

        return (r + '000').slice(0, 4).toUpperCase();
    }
};

jQuery(document).ready(function(){
    chrome.extension.sendRequest({method: "getSettings"}, function(response) {
        webpageSpellingExtension.setSettings(response.data);
    });

    chrome.extension.sendRequest({method: "getDictionaries"}, function(response) {
        webpageSpellingExtension.setDictionaries(response.data);

        jQuery('p:visible,a:visible,h1:visible,h2:visible,h3:visible,h4:visible,h5:visible,h6:visible,h7:visible,h8:visible,td:visible').each(function(){
            var $elem = jQuery(this);
            var text = jQuery.trim(jQuery(this).text().replace(/"/g, '"')
                                                      .replace(/'/g, "'")
                                                      .replace(/</g, '<')
                                                      .replace(/>/g, '>')
                                                      .replace(/&/g, '&'))
                                                      .replace(/(<([^>]+)>)/ig,"");

            text = text.replace(/[^a-zA-Z0-9\ \']/g," ").replace(/ +/g, " ");
            var words = text.split(" ");
            jQuery.each(words,function(index, value) {
                if(jQuery.trim(value) != '') {
                    webpageSpellingExtension.checkSpelling(value, $elem);
                }
            });
        });
    });
});<|endoftext|>


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

(function(scope) {

  // imports

  var log = window.logFlags || {};

  // magic words

  var EVENT_PREFIX = 'on-';
  var HANDLED_LIST = '__eventHandledList__';

  // instance events api

  var events = {
    // read-only
    EVENT_PREFIX: EVENT_PREFIX,
    // event name utilities
    hasEventPrefix: function (n) {
      return n.slice(0, prefixLength) === EVENT_PREFIX;
    },
    removeEventPrefix: function(n) {
      return n.slice(prefixLength);
    },
    // event listeners on host
    addHostListeners: function() {
      var events = this.eventDelegates;
      log.events && (Object.keys(events).length > 0) && console.log('[%s] addHostListeners:', this.localName, events);
      this.addNodeListeners(this, events, this.hostEventListener);
    },
    addNodeListeners: function(node, events, listener) {
      // note: conditional inside loop as optimization
      // for empty 'events' object
      var fn;
      for (var n in events) {
        if (!fn) {
          fn = listener.bind(this);
        }
        this.addNodeListener(node, n, fn);
      }
    },
    addNodeListener: function(node, event, listener) {
      node.addEventListener(event, listener);
    },
    hostEventListener: function(event) {
      if (!event.cancelBubble) {
        log.events && console.group("[%s]: hostEventListener(%s)", this.localName, event.type);
        var h = this.findEventDelegate(event);
        if (h) {
          log.events && console.log('[%s] found host handler name [%s]', this.localName, h);
          this.dispatchMethod(this, h, [event, event.detail, this]);
        }
        log.events && console.groupEnd();
      }
    },
    // find the method name in delegates mapped to event.type
    findEventDelegate: function(event) {
      return this.eventDelegates[event.type];
    },
    // call 'methodName' method on 'node' with 'args', if the method exists
    dispatchMethod: function(node, methodName, args) {
      if (node) {
        log.events && console.group('[%s] dispatch [%s]', node.localName, methodName);
        var fn = this[methodName];
        if (fn) {
          fn[args ? 'apply' : 'call'](this, args);
        }
        log.events && console.groupEnd();
        Platform.flush();
      }
    },
    prepareBinding: function(path, name, node) {
      // if lhs an event prefix,
      if (events.hasEventPrefix(name)) {
        // provide an event-binding callback
        return function(model, name, node) {
          console.log('event: [%s].%s => [%s].%s()"', node.localName, name, model.localName, name);
          node.addEventListener(events.removeEventPrefix(name),
            function(event) {
              var ctrlr = findController(node);
              if (ctrlr && ctrlr.dispatchMethod) {
                ctrlr.dispatchMethod(ctrlr, path, [event, event.detail, node]);
              }
            }
          );
        };
      }
    }
  };

  var prefixLength = EVENT_PREFIX.length;

  function findController(node) {
    while (node.parentNode) {
      node = node.parentNode;
    }
    return node.host;
  };

  // exports

  scope.api.instance.events = events;

})(Polymer);
<commit_msg>[micro optimization] unroll comparison<commit_after>/*
 * Copyright 2013 The Polymer Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

(function(scope) {

  // imports

  var log = window.logFlags || {};

  // magic words

  var EVENT_PREFIX = 'on-';
  var HANDLED_LIST = '__eventHandledList__';

  // instance events api

  var events = {
    // read-only
    EVENT_PREFIX: EVENT_PREFIX,
    // event name utilities
    hasEventPrefix: function (n) {
      return n && (n[0] === 'o') && (n[1] === 'n') && (n[2] === '-');
    },
    removeEventPrefix: function(n) {
      return n.slice(prefixLength);
    },
    // event listeners on host
    addHostListeners: function() {
      var events = this.eventDelegates;
      log.events && (Object.keys(events).length > 0) && console.log('[%s] addHostListeners:', this.localName, events);
      this.addNodeListeners(this, events, this.hostEventListener);
    },
    addNodeListeners: function(node, events, listener) {
      // note: conditional inside loop as optimization
      // for empty 'events' object
      var fn;
      for (var n in events) {
        if (!fn) {
          fn = listener.bind(this);
        }
        this.addNodeListener(node, n, fn);
      }
    },
    addNodeListener: function(node, event, listener) {
      node.addEventListener(event, listener);
    },
    hostEventListener: function(event) {
      if (!event.cancelBubble) {
        log.events && console.group("[%s]: hostEventListener(%s)", this.localName, event.type);
        var h = this.findEventDelegate(event);
        if (h) {
          log.events && console.log('[%s] found host handler name [%s]', this.localName, h);
          this.dispatchMethod(this, h, [event, event.detail, this]);
        }
        log.events && console.groupEnd();
      }
    },
    // find the method name in delegates mapped to event.type
    findEventDelegate: function(event) {
      return this.eventDelegates[event.type];
    },
    // call 'methodName' method on 'node' with 'args', if the method exists
    dispatchMethod: function(node, methodName, args) {
      if (node) {
        log.events && console.group('[%s] dispatch [%s]', node.localName, methodName);
        var fn = this[methodName];
        if (fn) {
          fn[args ? 'apply' : 'call'](this, args);
        }
        log.events && console.groupEnd();
        Platform.flush();
      }
    },
    prepareBinding: function(path, name, node) {
      // if lhs an event prefix,
      if (events.hasEventPrefix(name)) {
        // provide an event-binding callback
        return function(model, name, node) {
          console.log('event: [%s].%s => [%s].%s()"', node.localName, name, model.localName, name);
          node.addEventListener(events.removeEventPrefix(name),
            function(event) {
              var ctrlr = findController(node);
              if (ctrlr && ctrlr.dispatchMethod) {
                ctrlr.dispatchMethod(ctrlr, path, [event, event.detail, node]);
              }
            }
          );
        };
      }
    }
  };

  var prefixLength = EVENT_PREFIX.length;

  function findController(node) {
    while (node.parentNode) {
      node = node.parentNode;
    }
    return node.host;
  };

  // exports

  scope.api.instance.events = events;

})(Polymer);
<|endoftext|>


<commit_before>var gulp         = require('gulp');
var gulpSequence = require('gulp-sequence');

gulp.task('build:production', function(cb) {
  process.env.NODE_ENV = 'production'
  //gulpSequence('karma', 'clean', ['fonts', 'iconFont', 'images'], ['webpack:production'], 'html', 'rev', cb);
  gulpSequence('clean', 'copy', ['fonts', 'images'], ['webpack:production'] ['html', 'rev'], cb);
});
<commit_msg>Missing comma<commit_after>var gulp         = require('gulp');
var gulpSequence = require('gulp-sequence');

gulp.task('build:production', function(cb) {
  process.env.NODE_ENV = 'production'
  //gulpSequence('karma', 'clean', ['fonts', 'iconFont', 'images'], ['webpack:production'], 'html', 'rev', cb);
  gulpSequence('clean', 'copy', ['fonts', 'images'], ['webpack:production'], ['html', 'rev'], cb);
});
<|endoftext|>


<commit_before>var util = require('util');

exports.add_routes = function(webapp, velbus, config) {

function reply_to_get(req, res, next) {
	var addr = parseInt( req.params[0], 16 );
	var relay = parseInt( req.params[1] );
	var field = req.params[2];
	var addr_h = addr.toString(16);
	if( addr_h.length == 1 ) addr_h = '0' + addr_h;

	// Set up listener for the answer
	var timeout;
	var send_answer = function(msg) {
		clearTimeout(timeout);

		delete msg.data;

		if( field != undefined && field != '' ) {
			if( msg.hasOwnProperty(field) ) {
				res.send( msg[field].toString(), {'Content-Type': 'text/plain'} );
			} else {
				res.send("Unknown property", 404);
			}
		} else {
			res.send(msg);
		}
	};
	velbus.once('relay status ' + addr_h + '-' + relay, send_answer);
	timeout = setTimeout(function() {
			velbus.removeListener('relay status ' + addr_h + '-' + relay, send_answer);
			res.send("Timeout", 500);
		}, config.webapp.timeout);

	// Now send the request
	util.log("[" + req.connection.remoteAddress + "]:"
			+ req.connection.remotePort + " : "
			+ "Sending ModuleStatusRequest to 0x" + addr_h + " to get relay status");
	var relaybit = String.fromCharCode( 1 << (relay-1) );
	velbus.send_message(3, addr, 0, "\xfa" + relaybit );
}

webapp.get(/\/control\/relay\/([0-9a-fA-F]{2})-([1-4])(?:\/([a-zA-Z ]*))?$/, reply_to_get);

webapp.post(/\/control\/relay\/([0-9a-fA-F]{2})-([1-4])\/([a-zA-Z ]*)$/, function(req, res, next) {
	var addr = parseInt( req.params[0], 16 );
	var relay = parseInt( req.params[1] );
	var field = req.params[2];
	var addr_h = addr.toString(16);
	if( addr_h.length == 1 ) addr_h = '0' + addr_h;

	var relaybit = 1 << (relay-1);

	// We expect a single value in the body
	var value = Object.keys( req.body )
	if( value.length != 1 ) {
		res.send("Expecting single value in POST body", 400);
		return;
	}
	value = value[0];

	switch( field ) {
	case "status":
		var command;
		switch( value ) {
		case "on":
			if( req.body[ value ] == undefined ) {
				command = new Buffer([ 0x02, relaybit ] );
				util.log("[" + req.connection.remoteAddress + "]:"
						+ req.connection.remotePort + " : "
						+ "Sending SwitchRelayOn to 0x" + addr_h);
			} else {
				// Start timer for the specified number of seconds
				var delay = parseInt( req.body[ value ] );
				command = new Buffer([ 0x03, relaybit, (delay>>16) & 0xff, (delay>>8) & 0xff, (delay) & 0xff ]);
				util.log("[" + req.connection.remoteAddress + "]:"
						+ req.connection.remotePort + " : "
						+ "Sending StartRelayTimer to 0x" + addr_h);
			}
			break;

		case "off":
			command = new Buffer([ 0x01, relaybit ]);
			util.log("[" + req.connection.remoteAddress + "]:"
					+ req.connection.remotePort + " : "
					+ "Sending SwitchRelayOff to 0x" + addr);
			break;

		default:
			res.send("Unknown status", 400);
			return;
		}
		velbus.send_message(0, addr, 0, command);
		break;

	default:
		res.send("Not implemented", 501);
		return;
	}

	// And fall through to the GET response
	reply_to_get(req, res, next);
});

}

exports.add_watchers = function(velbus, state, config) {
	velbus.on('relay status', function(msg) {
		state.set( msg.id + '.status', msg.status );
		state.set( msg.id + '.timer', { 'value': msg.timer, 'ref': +new Date() });
	});

	// And initialize the current status of all relays in config
	for(var control in config.controls) {
		if( config.controls[control].type != "relay" ) continue;

		velbus.once('connect', function(id, control) { return function() {
			// Closure with id and control

			var addr = id.split('-');
			var relaybit = String.fromCharCode( 1 << (addr[1]-1) );

			// Spread queries in time in order not to overload the bus when starting up
			var starttime = Math.random() * Object.keys(config.controls).length * 100;
			setTimeout(function() {
				util.log("startup : "
						+ "Sending ModuleStatusRequest to 0x" + addr + " to get relay status");
				velbus.send_message(3, parseInt(addr[0],16), 0, "\xfa" + relaybit );
				}, starttime);
		}}(control, config.controls[control]));
	}
}
<commit_msg>Potential bugfix: empty string != undefined<commit_after>var util = require('util');

exports.add_routes = function(webapp, velbus, config) {

function reply_to_get(req, res, next) {
	var addr = parseInt( req.params[0], 16 );
	var relay = parseInt( req.params[1] );
	var field = req.params[2];
	var addr_h = addr.toString(16);
	if( addr_h.length == 1 ) addr_h = '0' + addr_h;

	// Set up listener for the answer
	var timeout;
	var send_answer = function(msg) {
		clearTimeout(timeout);

		delete msg.data;

		if( field != undefined && field != '' ) {
			if( msg.hasOwnProperty(field) ) {
				res.send( msg[field].toString(), {'Content-Type': 'text/plain'} );
			} else {
				res.send("Unknown property", 404);
			}
		} else {
			res.send(msg);
		}
	};
	velbus.once('relay status ' + addr_h + '-' + relay, send_answer);
	timeout = setTimeout(function() {
			velbus.removeListener('relay status ' + addr_h + '-' + relay, send_answer);
			res.send("Timeout", 500);
		}, config.webapp.timeout);

	// Now send the request
	util.log("[" + req.connection.remoteAddress + "]:"
			+ req.connection.remotePort + " : "
			+ "Sending ModuleStatusRequest to 0x" + addr_h + " to get relay status");
	var relaybit = String.fromCharCode( 1 << (relay-1) );
	velbus.send_message(3, addr, 0, "\xfa" + relaybit );
}

webapp.get(/\/control\/relay\/([0-9a-fA-F]{2})-([1-4])(?:\/([a-zA-Z ]*))?$/, reply_to_get);

webapp.post(/\/control\/relay\/([0-9a-fA-F]{2})-([1-4])\/([a-zA-Z ]*)$/, function(req, res, next) {
	var addr = parseInt( req.params[0], 16 );
	var relay = parseInt( req.params[1] );
	var field = req.params[2];
	var addr_h = addr.toString(16);
	if( addr_h.length == 1 ) addr_h = '0' + addr_h;

	var relaybit = 1 << (relay-1);

	// We expect a single value in the body
	var value = Object.keys( req.body )
	if( value.length != 1 ) {
		res.send("Expecting single value in POST body", 400);
		return;
	}
	value = value[0];

	switch( field ) {
	case "status":
		var command;
		switch( value ) {
		case "on":
			if( req.body[ value ] == undefined || req.body[ value ] == '' ) {
				command = new Buffer([ 0x02, relaybit ] );
				util.log("[" + req.connection.remoteAddress + "]:"
						+ req.connection.remotePort + " : "
						+ "Sending SwitchRelayOn to 0x" + addr_h);
			} else {
				// Start timer for the specified number of seconds
				var delay = parseInt( req.body[ value ] );
				command = new Buffer([ 0x03, relaybit, (delay>>16) & 0xff, (delay>>8) & 0xff, (delay) & 0xff ]);
				util.log("[" + req.connection.remoteAddress + "]:"
						+ req.connection.remotePort + " : "
						+ "Sending StartRelayTimer(" + delay + ") to 0x" + addr_h);
			}
			break;

		case "off":
			command = new Buffer([ 0x01, relaybit ]);
			util.log("[" + req.connection.remoteAddress + "]:"
					+ req.connection.remotePort + " : "
					+ "Sending SwitchRelayOff to 0x" + addr);
			break;

		default:
			res.send("Unknown status", 400);
			return;
		}
		velbus.send_message(0, addr, 0, command);
		break;

	default:
		res.send("Not implemented", 501);
		return;
	}

	// And fall through to the GET response
	reply_to_get(req, res, next);
});

}

exports.add_watchers = function(velbus, state, config) {
	velbus.on('relay status', function(msg) {
		state.set( msg.id + '.status', msg.status );
		state.set( msg.id + '.timer', { 'value': msg.timer, 'ref': +new Date() });
	});

	// And initialize the current status of all relays in config
	for(var control in config.controls) {
		if( config.controls[control].type != "relay" ) continue;

		velbus.once('connect', function(id, control) { return function() {
			// Closure with id and control

			var addr = id.split('-');
			var relaybit = String.fromCharCode( 1 << (addr[1]-1) );

			// Spread queries in time in order not to overload the bus when starting up
			var starttime = Math.random() * Object.keys(config.controls).length * 100;
			setTimeout(function() {
				util.log("startup : "
						+ "Sending ModuleStatusRequest to 0x" + addr + " to get relay status");
				velbus.send_message(3, parseInt(addr[0],16), 0, "\xfa" + relaybit );
				}, starttime);
		}}(control, config.controls[control]));
	}
}
<|endoftext|>


<commit_before>angular.module('starter.controllers', [])

.controller('StepsCtrl', function($scope, $ionicModal, $ionicSlideBoxDelegate) {
  $scope.data = {};

  $ionicModal.fromTemplateUrl('templates/modal-steps.html', {
    //scope: $scope,
    animation: 'slide-in-up'
  }).then(function(modal) {
    $scope.modal = modal;
	$scope.modal.show();
	$ionicSlideBoxDelegate.update();
  });

  $scope.openModal = function() {
    $scope.modal.show();
  };

  $scope.closeModal = function() {
    $scope.modal.hide();
    console.log('closed');
  };

  // Cleanup the modal when we're done with it!
  $scope.$on('$destroy', function() {
    $scope.modal.remove();
  });

  // Execute action on hide modal
  $scope.$on('modal.hidden', function() {
    // Execute action
  });

  // Execute action on remove modal
  $scope.$on('modal.removed', function() {
    // Execute action
  });
})

.controller('ResultsCtrl', function($scope) {

});
<commit_msg>remove unnecessary call to update<commit_after>angular.module('starter.controllers', [])

.controller('StepsCtrl', function($scope, $ionicModal, $ionicSlideBoxDelegate) {
  $scope.data = {};

  $ionicModal.fromTemplateUrl('templates/modal-steps.html', {
    //scope: $scope,
    animation: 'slide-in-up'
  }).then(function(modal) {
    $scope.modal = modal;
	$scope.modal.show();
  });

  $scope.openModal = function() {
    $scope.modal.show();
  };

  $scope.closeModal = function() {
    $scope.modal.hide();
    console.log('closed');
  };

  // Cleanup the modal when we're done with it!
  $scope.$on('$destroy', function() {
    $scope.modal.remove();
  });

  // Execute action on hide modal
  $scope.$on('modal.hidden', function() {
    // Execute action
  });

  // Execute action on remove modal
  $scope.$on('modal.removed', function() {
    // Execute action
  });
})

.controller('ResultsCtrl', function($scope) {

});
<|endoftext|>


<commit_before><commit_msg>Added MapController dummy<commit_after><|endoftext|>


<commit_before>'use strict';

angular.module('myApp.controllers', [])
    .controller('MainCtrl', ['$scope', '$rootScope', '$window', '$location', function ($scope, $rootScope, $window, $location) {
        $scope.slide = '';
        $rootScope.back = function() {
          $scope.slide = 'slide-right';
          $window.history.back();
        }
        $rootScope.go = function(path){
          $scope.slide = 'slide-left';
          $location.url(path);
        }
        $rootScope.logout = function() {
            window.localStorage.clear();
            window.location = "#/login";
            return false;
        }
    }])
    .controller('LoginCtrl', ['$scope', 'Employee', '$http', function ($scope, Employee, $http) {
        // $scope.employees = Employee.query();
        $scope.doLogin = function() {
            $scope.error = {};

            if ( $scope.user === undefined || !$scope.user.username || !$scope.user.password) {
                $scope.error.message = 'Invalid login details';
                return;
            }

            $http.post("http://offerfans.ngrok.com/api/v1/auth/login", $scope.user)
                 .success(function(data, status, headers, config) {
                    window.localStorage.setItem("access_token", data.token);
                    window.localStorage.setItem("username", $scope.user.username);
                    window.location = "#/scan";
                    return true;
                 })
                 .error(function(data, status, headers, config) {
                    $scope.error.message = data.error;
                    window.localStorage.clear();
                    return;
                 });
        }
    }])
    .controller('ScanCtrl', ['$scope', 'Scanner', function ($scope, Scanner) {

        if (!window.localStorage.getItem("access_token")) {
            window.location = "#/login";
            return false;
        }

        $scope.user  = { username: window.localStorage.getItem("username") };

        $scope.scan = function() {
           $scope.error = {};
           Scanner.scan(onSuccess, onFail);
        }

        var onSuccess = function (result) {
           console.log("Scanner result: \n" +
                "text: " + result.text + "\n" +
                "format: " + result.format + "\n" +
                "cancelled: " + result.cancelled + "\n");

            if (result.cancelled) {
                $scope.error.message = "Cancelled";
            } else if (result.format != "QR_CODE") {
                $scope.error.message = "Unknown barcode format";
            } else {
                if (result.text) {
                    redeemCode(result.text);
                } else {
                    $scope.error.message = "Can not read barcode";
                }
            }

            $scope.$apply();
        }

        var onFail = function (error) {
            $scope.error.message = "Scanning failed: " + error;
            $scope.$apply();
        }

        var redeemCode = function(code) {
            // $scope.code = code;
            // $scope.$apply();
            var options = {
                headers: {
                    'Access-Token' : window.localStorage.getItem("access_token")
                }
            }

            console.log("PUT request", "http://offerfans.ngrok.com/api/v1/redeem/"+code);
            console.log(options);

            $scope.$apply(function() {
                // put access_token in header
                $http.put("http://offerfans.ngrok.com/api/v1/redeem/"+result.text, {}, options)
                     .success(function(data, status, headers, config) {
                        console.log(data);
                     })
                     .error(function(data, status, headers, config) {
                        console.log(data);
                     });
            });

        }
    }])
    .controller('EmployeeListCtrl', ['$scope', 'Employee', function ($scope, Employee) {
        $scope.employees = Employee.query();
    }])
    .controller('EmployeeDetailCtrl', ['$scope', '$routeParams', 'Employee', function ($scope, $routeParams, Employee) {
        $scope.employee = Employee.get({employeeId: $routeParams.employeeId});
    }])
    .controller('ReportListCtrl', ['$scope', '$routeParams', 'Report', function ($scope, $routeParams, Report) {
        $scope.employees = Report.query({employeeId: $routeParams.employeeId});
    }]);
<commit_msg>Moving back in to redeemCode function<commit_after>'use strict';

angular.module('myApp.controllers', [])
    .controller('MainCtrl', ['$scope', '$rootScope', '$window', '$location', function ($scope, $rootScope, $window, $location) {
        $scope.slide = '';
        $rootScope.back = function() {
          $scope.slide = 'slide-right';
          $window.history.back();
        }
        $rootScope.go = function(path){
          $scope.slide = 'slide-left';
          $location.url(path);
        }
        $rootScope.logout = function() {
            window.localStorage.clear();
            window.location = "#/login";
            return false;
        }
    }])
    .controller('LoginCtrl', ['$scope', 'Employee', '$http', function ($scope, Employee, $http) {
        // $scope.employees = Employee.query();
        $scope.doLogin = function() {
            $scope.error = {};

            if ( $scope.user === undefined || !$scope.user.username || !$scope.user.password) {
                $scope.error.message = 'Invalid login details';
                return;
            }

            $http.post("http://offerfans.ngrok.com/api/v1/auth/login", $scope.user)
                 .success(function(data, status, headers, config) {
                    window.localStorage.setItem("access_token", data.token);
                    window.localStorage.setItem("username", $scope.user.username);
                    window.location = "#/scan";
                    return true;
                 })
                 .error(function(data, status, headers, config) {
                    $scope.error.message = data.error;
                    window.localStorage.clear();
                    return;
                 });
        }
    }])
    .controller('ScanCtrl', ['$scope', 'Scanner', function ($scope, Scanner) {

        if (!window.localStorage.getItem("access_token")) {
            window.location = "#/login";
            return false;
        }

        $scope.user  = { username: window.localStorage.getItem("username") };

        $scope.scan = function() {
           $scope.error = {};
           Scanner.scan(onSuccess, onFail);
        }

        var onSuccess = function (result) {
           console.log("Scanner result: \n" +
                "text: " + result.text + "\n" +
                "format: " + result.format + "\n" +
                "cancelled: " + result.cancelled + "\n");

            if (result.cancelled) {
                $scope.error.message = "Cancelled";
            } else if (result.format != "QR_CODE") {
                $scope.error.message = "Unknown barcode format";
            } else {
                if (result.text) {
                    redeemCode(result.text);
                } else {
                    $scope.error.message = "Can not read barcode";
                }
            }

            $scope.$apply();
        }

        var onFail = function (error) {
            $scope.error.message = "Scanning failed: " + error;
            $scope.$apply();
        }

        var redeemCode = function(code) {
            // $scope.code = code;
            // $scope.$apply();
            var options = {
                headers: {
                    'Access-Token' : window.localStorage.getItem("access_token")
                }
            }

            console.log("PUT request", "http://offerfans.ngrok.com/api/v1/redeem/"+code);
            console.log(options);
            console.log($scope);
            console.log($rootScope);

            // $scope.$apply(function() {
            //     // put access_token in header
            //     $http.put("http://offerfans.ngrok.com/api/v1/redeem/"+result.text, {}, options)
            //          .success(function(data, status, headers, config) {
            //             console.log(data);
            //          })
            //          .error(function(data, status, headers, config) {
            //             console.log(data);
            //          });
            // });

        }
    }])
    .controller('EmployeeListCtrl', ['$scope', 'Employee', function ($scope, Employee) {
        $scope.employees = Employee.query();
    }])
    .controller('EmployeeDetailCtrl', ['$scope', '$routeParams', 'Employee', function ($scope, $routeParams, Employee) {
        $scope.employee = Employee.get({employeeId: $routeParams.employeeId});
    }])
    .controller('ReportListCtrl', ['$scope', '$routeParams', 'Report', function ($scope, $routeParams, Report) {
        $scope.employees = Report.query({employeeId: $routeParams.employeeId});
    }]);
<|endoftext|>


<commit_before>var rusha = new (require('rusha'))()
var metadataReader = require('music-metadata')
var fs = require('file-system')(['audio/mp3', 'audio/wav', 'audio/ogg'])
var coversActions = require('./covers.js')

var actions = {

  // Add a file as a song. This hashes the file, adds it to the filesystem,
  // gets the metadata and the duration and dispatches the result metadata.
  // To add multiple files just dispatch this action multiple times.
  ADD_SONG: (file) => {
    return (dispatch, getState) => {
      // Extract the file ending
      var file_ending = file.name.replace(/^.*(\.[A-Za-z0-9]{3})$/, '$1')

      // Read the file as an data url
      var reader = new window.FileReader()
      reader.readAsDataURL(file)
      reader.onloadend = function () {
        // Hash the file contents and set the filename based on that
        var hash = rusha.digestFromString(this.result)
        var hashName = hash + file_ending

        // Get the metadata off the file
        metadataReader(file, meta => {
          // Add the song to the file system
          fs.add({filename: hashName, file: file}, (err) => {
            if (err) throw new Error('Error adding file: ' + err)

            // Read the file as an url from the filesystem
            fs.get(hashName, (err, url) => {
              if (err) throw new Error('Error getting file: ' + err)

              // Create an audio element to check on the duration
              var audio = document.createElement('audio')
              audio.src = url
              audio.addEventListener('loadedmetadata', () => {
                var duration = audio.duration

                // Dispatch an action to update the view and save
                // the song data in local storage
                var song = {
                  id: hash,
                  filename: url,
                  ...meta,
                  addedAt: (new Date()).toString(),
                  length: duration,
                  favorited: false,
                  coverId: getCoverId(meta),
                  availability: 0,
                  hashName: hashName,
                  originalFilename: file.name
                }

                // Dispatch an action to get the cover from the scraping server
                coversActions.GET_COVER(song.album, song.artist, song.coverId)(dispatch, getState)

                dispatch({
                  type: 'ADD_SONG',
                  song: song
                })
              })
            })
          })
        })
      }
    }
  },

  // Remove a song
  REMOVE_SONG: (id) => {
    return (dispatch, getState) => {
      var state = getState()
      const filename = state.songs.filter(x => x.id === id)[0].hashName
      fs.delete(filename, (err) => {
        if (err) throw new Error('Error removing song: ' + err)
        dispatch({
          type: 'REMOVE_SONG',
          id
        })
      })
    }
  },

  // Toggle the favorite status of a song
  TOGGLE_SONG_FAVORITE: (id) => {
    return {
      type: 'TOGGLE_SONG_FAVORITE',
      id
    }
  },

  // Remove all songs
  CLEAR_DATA: () => {
    return (dispatch) => {
      fs.clear((err) => {
        if (err) throw new Error('Error clearing filesystem: ' + err)
        dispatch({
          type: 'CLEAR_DATA'
        })
      })
    }
  }

}

// Get the cover id from metadata
function getCoverId (meta) {
  const cleanup = s => (s || '').toLowerCase().replace(/[^a-zA-Z0-9]/g, '')
  return rusha.digestFromString(cleanup(meta.album) + cleanup(meta.artist))
}

module.exports = actions
<commit_msg>Allow for empty file types (android...)<commit_after>var rusha = new (require('rusha'))()
var metadataReader = require('music-metadata')
var fs = require('file-system')(['', 'audio/mp3', 'audio/wav', 'audio/ogg'])
var coversActions = require('./covers.js')

var actions = {

  // Add a file as a song. This hashes the file, adds it to the filesystem,
  // gets the metadata and the duration and dispatches the result metadata.
  // To add multiple files just dispatch this action multiple times.
  ADD_SONG: (file) => {
    return (dispatch, getState) => {
      // Extract the file ending
      var file_ending = 'mp3'

      if (file.name.match(/^.*(\.[A-Za-z0-9]{3})$/)) {
        file_ending = file.name.replace(/^.*(\.[A-Za-z0-9]{3})$/, '$1')
      }

      // Read the file as an data url
      var reader = new window.FileReader()
      reader.readAsDataURL(file)
      reader.onloadend = function () {
        // Hash the file contents and set the filename based on that
        var hash = rusha.digestFromString(this.result)
        var hashName = hash + file_ending

        // Get the metadata off the file
        metadataReader(file, meta => {
          // Add the song to the file system
          fs.add({filename: hashName, file: file}, (err) => {
            if (err) throw new Error('Error adding file: ' + err)

            // Read the file as an url from the filesystem
            fs.get(hashName, (err, url) => {
              if (err) throw new Error('Error getting file: ' + err)

              // Create an audio element to check on the duration
              var audio = document.createElement('audio')
              audio.src = url
              audio.addEventListener('loadedmetadata', () => {
                var duration = audio.duration

                // Dispatch an action to update the view and save
                // the song data in local storage
                var song = {
                  id: hash,
                  filename: url,
                  ...meta,
                  addedAt: (new Date()).toString(),
                  length: duration,
                  favorited: false,
                  coverId: getCoverId(meta),
                  availability: 0,
                  hashName: hashName,
                  originalFilename: file.name
                }

                // Dispatch an action to get the cover from the scraping server
                coversActions.GET_COVER(song.album, song.artist, song.coverId)(dispatch, getState)

                dispatch({
                  type: 'ADD_SONG',
                  song: song
                })
              })
            })
          })
        })
      }
    }
  },

  // Remove a song
  REMOVE_SONG: (id) => {
    return (dispatch, getState) => {
      var state = getState()
      const filename = state.songs.filter(x => x.id === id)[0].hashName
      fs.delete(filename, (err) => {
        if (err) throw new Error('Error removing song: ' + err)
        dispatch({
          type: 'REMOVE_SONG',
          id
        })
      })
    }
  },

  // Toggle the favorite status of a song
  TOGGLE_SONG_FAVORITE: (id) => {
    return {
      type: 'TOGGLE_SONG_FAVORITE',
      id
    }
  },

  // Remove all songs
  CLEAR_DATA: () => {
    return (dispatch) => {
      fs.clear((err) => {
        if (err) throw new Error('Error clearing filesystem: ' + err)
        dispatch({
          type: 'CLEAR_DATA'
        })
      })
    }
  }

}

// Get the cover id from metadata
function getCoverId (meta) {
  const cleanup = s => (s || '').toLowerCase().replace(/[^a-zA-Z0-9]/g, '')
  return rusha.digestFromString(cleanup(meta.album) + cleanup(meta.artist))
}

module.exports = actions
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2011 by Christopher Johnson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

var XjsStream = require('../lib/XjsStream'),
    StringStream = require('../lib/StringStream');

var tests = [

  {
    name: 'test typical stream behavior',
    expect : 'Good morning\ngood afternoon\nand good night!',
    render : function(stream) {
      stream.write('Good morning\n');
      stream.write('good afternoon\n');
      stream.end('and good night!');
    }
  },

  {
    name : 'test writing various objects to the stream',
    expect : '[Function]barfood!fubar',
    render : function(stream) {
      // these should never register on the stream
      stream.write(null);
      stream.write(undefined);

      // functions should always show as '[Function]'
      stream.write(function() {});

      // first try an object's render method
      stream.write({
        render: function(stream, arg1, arg2) {
          stream.write(arg2);
          stream.write(arg1);
        },
        toString: function() {
          return 'nothing to see here';
        }
      }, 'food!', 'bar');

      // objects lacking render use toString()
      stream.write({
        toString: function() { return 'fubar'; }
      });

      stream.end();
    }
  },

  {
    name : 'test escape',
    expect : '<>&" "&<>',
    render : function(stream) {
      stream.write('<>&" "&<>');
      stream.end();
    }
  },

  {
    name : 'test tag writing',
    expect : '
<fb:name uid="4"/>
',
    render : function(stream) {
      stream.writeTag(null, 'div', { id : 'name', 'class' : 'user' },
        function(stream) {
          stream.writeTag('fb', 'name', { uid : 4 });
        }
      );
      stream.end();
    }
  },

  {
    name : 'test async substream',
    expect : '
monkey in the middle
',
    render : function(stream) {
      var async1;

      stream.writeTag(null, 'div', null, function(stream) {
        // the async substream is bookmarked between the parent tags
        async1 = stream.async();
        stream.async(function(async2) {
          async2.write(' in ');
          async2.end('the middle'); //
[async1] in the middle
        });
      }); //
[async1] in the middle

      stream.end();

      // ending the async substream can take arbitrarily long
      setTimeout(function() {
        async1.end('monkey'); //
monkey in the middle

      }, 10);
    }
  },

  {
    name : 'test kill async stream',
    expect : 'twothree',
    render : function(stream, assert) {
      stream.async(function(stream) {
        setTimeout(function() {
          assert['throws'](function() {
            stream.end('one');
          });
        }, 20);
      });
      stream.async(function(stream) {
        setTimeout(function() {
          stream.end('two');
        }, 5);
      });
      stream.async(function(stream) {
        stream.end('three');
      });
      stream.end();

      // after 10ms, signal the stream to finish
      setTimeout(function() {
        stream.kill();
      }, 10);
    }
  }

];

tests.forEach(function(test) {

  exports[test.name] = function(assert) {
    var stream = new XjsStream(function(result) {
      assert.equal(test.expect, result);
      assert.equal(false, stream.writable);
      assert['throws'](function() {
        stream.write('this should throw');
      });
      assert.done();
    });

    assert.equal(true, stream.writable);
    test.render(stream, assert);
  };

});
<commit_msg>StringStream no longer used directly in these tests<commit_after>/**
 * Copyright (C) 2011 by Christopher Johnson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

var XjsStream = require('../lib/XjsStream');

var tests = [

  {
    name: 'test typical stream behavior',
    expect : 'Good morning\ngood afternoon\nand good night!',
    render : function(stream) {
      stream.write('Good morning\n');
      stream.write('good afternoon\n');
      stream.end('and good night!');
    }
  },

  {
    name : 'test writing various objects to the stream',
    expect : '[Function]barfood!fubar',
    render : function(stream) {
      // these should never register on the stream
      stream.write(null);
      stream.write(undefined);

      // functions should always show as '[Function]'
      stream.write(function() {});

      // first try an object's render method
      stream.write({
        render: function(stream, arg1, arg2) {
          stream.write(arg2);
          stream.write(arg1);
        },
        toString: function() {
          return 'nothing to see here';
        }
      }, 'food!', 'bar');

      // objects lacking render use toString()
      stream.write({
        toString: function() { return 'fubar'; }
      });

      stream.end();
    }
  },

  {
    name : 'test escape',
    expect : '<>&" "&<>',
    render : function(stream) {
      stream.write('<>&" "&<>');
      stream.end();
    }
  },

  {
    name : 'test tag writing',
    expect : '
<fb:name uid="4"/>
',
    render : function(stream) {
      stream.writeTag(null, 'div', { id : 'name', 'class' : 'user' },
        function(stream) {
          stream.writeTag('fb', 'name', { uid : 4 });
        }
      );
      stream.end();
    }
  },

  {
    name : 'test async substream',
    expect : '
monkey in the middle
',
    render : function(stream) {
      var async1;

      stream.writeTag(null, 'div', null, function(stream) {
        // the async substream is bookmarked between the parent tags
        async1 = stream.async();
        stream.async(function(async2) {
          async2.write(' in ');
          async2.end('the middle'); //
[async1] in the middle
        });
      }); //
[async1] in the middle

      stream.end();

      // ending the async substream can take arbitrarily long
      setTimeout(function() {
        async1.end('monkey'); //
monkey in the middle

      }, 10);
    }
  },

  {
    name : 'test kill async stream',
    expect : 'twothree',
    render : function(stream, assert) {
      stream.async(function(stream) {
        setTimeout(function() {
          assert['throws'](function() {
            stream.end('one');
          });
        }, 20);
      });
      stream.async(function(stream) {
        setTimeout(function() {
          stream.end('two');
        }, 5);
      });
      stream.async(function(stream) {
        stream.end('three');
      });
      stream.end();

      // after 10ms, signal the stream to finish
      setTimeout(function() {
        stream.kill();
      }, 10);
    }
  }

];

tests.forEach(function(test) {

  exports[test.name] = function(assert) {
    var stream = new XjsStream(function(result) {
      assert.equal(test.expect, result);
      assert.equal(false, stream.writable);
      assert['throws'](function() {
        stream.write('this should throw');
      });
      assert.done();
    });

    assert.equal(true, stream.writable);
    test.render(stream, assert);
  };

});
<|endoftext|>


<commit_before>var nconf = require('nconf'),
    mongo = require('mongodb'),
    path = require('path'),
    fs = require('fs'),
    utils = require('../../lib/utils');

nconf.file({ file: 'gebo.json' });
var TEST_DB = utils.getMongoDbName(nconf.get('testDb'));

exports.onLoad = {

    'Load and initialize every file in the actions folder': function(test) {
        test.expect(15);
        // Note: actions, not action, as above
        var actions = require('../../actions')(TEST_DB);
        test.equal(typeof actions.dbExists, 'function');
        test.equal(typeof actions.getCollection, 'function');
        test.equal(typeof actions.save, 'function');
        test.equal(typeof actions.cp, 'function');
        test.equal(typeof actions.rm, 'function');
        test.equal(typeof actions.rmdir, 'function');
        test.equal(typeof actions.ls, 'function');
        test.equal(typeof actions.createDatabase, 'function');
        test.equal(typeof actions.dropDatabase, 'function');
        test.equal(typeof actions.registerAgent, 'function');
        test.equal(typeof actions.deregisterAgent, 'function');
        test.equal(typeof actions.friend, 'function');
        test.equal(typeof actions.defriend, 'function');
        test.equal(typeof actions.grantAccess, 'function');
        test.equal(typeof actions.certificate, 'function');
        test.done();
    },
};

exports.add = {

    tearDown: function(callback) {
        var files = fs.readdirSync(__dirname + '/../../actions');

        files.forEach(function(file) {
            if (require.cache[path.resolve(__dirname + '/../../actions/' + file)]) {
              delete require.cache[path.resolve(__dirname + '/../../actions/' + file)]
            }
        });
        callback();
    },

    'Add a single action function': function(test) {
        test.expect(3);

        var actions = require('../../actions')(TEST_DB);
        test.equal(actions.testAction, undefined);

        // Create a new action
        function testAction() {
                return 'testAction, yeah yeah!';
              };

        actions.add(testAction);

        test.equal(typeof actions.testAction, 'function');
        test.equal(actions.testAction(), 'testAction, yeah yeah!');

        test.done();
    },

    'Add a single action from function assigned to variable': function(test) {
        test.expect(3);

        var actions = require('../../actions')(TEST_DB);
        test.equal(actions.testAction, undefined);

        // Create a new action
        var testAction = function() {
                return 'testAction, yeah yeah!';
              };

        actions.add('testAction', testAction);

        test.equal(typeof actions.testAction, 'function');
        test.equal(actions.testAction(), 'testAction, yeah yeah!');

        test.done();
    },

    'Throw an error if function provided has no name': function(test) {
        test.expect(2);

        var actions = require('../../actions')(TEST_DB);
        test.equal(actions.testAction, undefined);

        // Create a new action
        var testAction = function() {
                return 'testAction, yeah yeah!';
              };

        try {
            actions.add(testAction);
            test.ok(false, 'This should throw an error');
        }
        catch(err) {
            test.equal(err.message, 'This action needs a name');
        }

        test.done();
    },

    'Add a module with actions': function(test) {
        test.expect(6);

        var actions = require('../../actions')(TEST_DB);
        test.equal(actions.testAction1, undefined);
        test.equal(actions.testAction2, undefined);

        var mod = require('./mocks/testActions')('some@email.com');
        actions.add(mod);

        test.equal(typeof actions.testAction1, 'function');
        test.equal(actions.testAction1(), 'testAction1, yeah yeah!');
        test.equal(typeof actions.testAction2, 'function');
        test.equal(actions.testAction2(), 'testAction2, yeah yeah!');

        test.done();
    },
};

exports.remove = {
    'Remove a single action': function(test) {
        test.expect(6);

        var actions = require('../../actions')(TEST_DB);
        test.equal(actions.testAction1, undefined);
        test.equal(actions.testAction2, undefined);

        var mod = require('./mocks/testActions')('some@email.com');
        actions.add(mod);

        test.equal(typeof actions.testAction1, 'function');
        test.equal(typeof actions.testAction2, 'function');

        actions.remove('testAction1');
        test.equal(actions.testAction1, undefined);
        test.equal(typeof actions.testAction2, 'function');

        test.done();
    },
};

<commit_msg>Remove unused requirement<commit_after>var nconf = require('nconf'),
    path = require('path'),
    fs = require('fs'),
    utils = require('../../lib/utils');

nconf.file({ file: 'gebo.json' });
var TEST_DB = utils.getMongoDbName(nconf.get('testDb'));

exports.onLoad = {

    'Load and initialize every file in the actions folder': function(test) {
        test.expect(15);
        // Note: actions, not action, as above
        var actions = require('../../actions')(TEST_DB);
        test.equal(typeof actions.dbExists, 'function');
        test.equal(typeof actions.getCollection, 'function');
        test.equal(typeof actions.save, 'function');
        test.equal(typeof actions.cp, 'function');
        test.equal(typeof actions.rm, 'function');
        test.equal(typeof actions.rmdir, 'function');
        test.equal(typeof actions.ls, 'function');
        test.equal(typeof actions.createDatabase, 'function');
        test.equal(typeof actions.dropDatabase, 'function');
        test.equal(typeof actions.registerAgent, 'function');
        test.equal(typeof actions.deregisterAgent, 'function');
        test.equal(typeof actions.friend, 'function');
        test.equal(typeof actions.defriend, 'function');
        test.equal(typeof actions.grantAccess, 'function');
        test.equal(typeof actions.certificate, 'function');
        test.done();
    },
};

exports.add = {

    tearDown: function(callback) {
        var files = fs.readdirSync(__dirname + '/../../actions');

        files.forEach(function(file) {
            if (require.cache[path.resolve(__dirname + '/../../actions/' + file)]) {
              delete require.cache[path.resolve(__dirname + '/../../actions/' + file)]
            }
        });
        callback();
    },

    'Add a single action function': function(test) {
        test.expect(3);

        var actions = require('../../actions')(TEST_DB);
        test.equal(actions.testAction, undefined);

        // Create a new action
        function testAction() {
                return 'testAction, yeah yeah!';
              };

        actions.add(testAction);

        test.equal(typeof actions.testAction, 'function');
        test.equal(actions.testAction(), 'testAction, yeah yeah!');

        test.done();
    },

    'Add a single action from function assigned to variable': function(test) {
        test.expect(3);

        var actions = require('../../actions')(TEST_DB);
        test.equal(actions.testAction, undefined);

        // Create a new action
        var testAction = function() {
                return 'testAction, yeah yeah!';
              };

        actions.add('testAction', testAction);

        test.equal(typeof actions.testAction, 'function');
        test.equal(actions.testAction(), 'testAction, yeah yeah!');

        test.done();
    },

    'Throw an error if function provided has no name': function(test) {
        test.expect(2);

        var actions = require('../../actions')(TEST_DB);
        test.equal(actions.testAction, undefined);

        // Create a new action
        var testAction = function() {
                return 'testAction, yeah yeah!';
              };

        try {
            actions.add(testAction);
            test.ok(false, 'This should throw an error');
        }
        catch(err) {
            test.equal(err.message, 'This action needs a name');
        }

        test.done();
    },

    'Add a module with actions': function(test) {
        test.expect(6);

        var actions = require('../../actions')(TEST_DB);
        test.equal(actions.testAction1, undefined);
        test.equal(actions.testAction2, undefined);

        var mod = require('./mocks/testActions')('some@email.com');
        actions.add(mod);

        test.equal(typeof actions.testAction1, 'function');
        test.equal(actions.testAction1(), 'testAction1, yeah yeah!');
        test.equal(typeof actions.testAction2, 'function');
        test.equal(actions.testAction2(), 'testAction2, yeah yeah!');

        test.done();
    },
};

exports.remove = {
    'Remove a single action': function(test) {
        test.expect(6);

        var actions = require('../../actions')(TEST_DB);
        test.equal(actions.testAction1, undefined);
        test.equal(actions.testAction2, undefined);

        var mod = require('./mocks/testActions')('some@email.com');
        actions.add(mod);

        test.equal(typeof actions.testAction1, 'function');
        test.equal(typeof actions.testAction2, 'function');

        actions.remove('testAction1');
        test.equal(actions.testAction1, undefined);
        test.equal(typeof actions.testAction2, 'function');

        test.done();
    },
};

<|endoftext|>


<commit_before>Parse.initialize("iXDvlSh7XJjt7J5a0vB6kgWSljEjtIICxAWTQnrF", "twvM3T7jNdbEB2jlJUSk7iXKjb24xv0IOjpJYUtA");
let _ = require('lodash')
let ParseFetcher = {
	getAllCandidates: () => {
		// Get candidates from Parse
		return new Promise((resolve, reject) => {
			var query = new Parse.Query('Candidates');
			query.limit = 10;

			query.find().then(function(results) {
				var arrCandidates = [];
				var arrKeys = ["first_name", "last_name", "party", "objectId"];
				for (var j = results.length - 1; j >= 0; j--) {
					console.log("inside for loop")
					var candidate = {}
					for (var i = 0; i < 4; i++) {
						switch(arrKeys[i]) {
							case "first_name":
								candidate["first_name"] = results[j].get("first_name");
								console.log("inside switch: first_name", results[j].get("first_name"))
								break;
							case "last_name":
								candidate["last_name"] = results[j].get("last_name");
								console.log("inside switch: last_name", results[j].get("last_name"))
								break;
							case "party":
								candidate["party"] = results[j].get("party");
								console.log("inside switch: party", results[j].get("party"))
								break;
							case "objectId":
								candidate["id"] = results[j].id;
								console.log("inside switch: id", results[j].id)
								break;
						}
					}
					console.log("CANDIDATE MAP", candidate);
					arrCandidates.push(candidate);
				};
				resolve(arrCandidates)
			}, function(error) {
				reject(error)
			});
		})
	},
	getAllIssues: () => {
		// Get candidates from Parse
		return new Promise((resolve, reject) => {
			var query = new Parse.Query('')

			setTimeout(() => {
				let issues = [{id:"c", "name": "Climate Change"}, {"id":"d", "name": "Economy"}]
				resolve(issues)
			}, 200)
		})
	},
	getVideos: (issueIDs, candidateIDs, offset, limit) => {
		// issueID: array, issue ids to filter videos by, don't filter if empty array
		// candidateIDs: array, candidate ids to filter videos by, don't filter if empty array
		// offset: int, skip the first offset # of elements
		// limit: int, only return limit # of elements
		console.log("GET VIDEOS", issueIDs, candidateIDs)
		return new Promise((resolve, reject) => {
			setTimeout(() => {
				let videos = [{"id": "e", "issue_id":"c", "candidate_id":"a", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "f", "issue_id":"c", "candidate_id":"b", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "g", "issue_id":"a", "candidate_id":"c", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "h", "issue_id":"a", "candidate_id":"c", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "i", "issue_id":"a", "candidate_id":"c", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "j", "issue_id":"a", "candidate_id":"c", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "k", "issue_id":"a", "candidate_id":"c", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "l", "issue_id":"a", "candidate_id":"c", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "m", "issue_id":"a", "candidate_id":"c", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "n", "issue_id":"a", "candidate_id":"c", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "o", "issue_id":"a", "candidate_id":"c", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "p", "issue_id":"a", "candidate_id":"c", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}]
				let retVideos = _.filter(videos, (video) => {
					if (issueIDs.length > 0) {
						let foundIssue = false
						for (let issueID of issueIDs) {
							if (video.issue_id == issueID) {
								foundIssue = true
								break
							}
						}
						if (!foundIssue)
							return false
					}
					if (candidateIDs.length > 0) {
						let foundCandidate = false
						for (let candidateID of candidateIDs) {
							if (video.candidate_id == candidateID) {
								foundCandidate = true
								break
							}
						}
						if (!foundCandidate)
							return false
					}
					return true
				})
				let result = retVideos.slice(offset, offset + limit)
				resolve(result)
			}, 200)
		})
	}
}

module.exports = ParseFetcher<commit_msg>Clean up logs<commit_after>Parse.initialize("iXDvlSh7XJjt7J5a0vB6kgWSljEjtIICxAWTQnrF", "twvM3T7jNdbEB2jlJUSk7iXKjb24xv0IOjpJYUtA");
let _ = require('lodash')
let ParseFetcher = {
	getAllCandidates: () => {
		// Get candidates from Parse
		return new Promise((resolve, reject) => {
			var query = new Parse.Query('Candidates');
			query.limit = 10;

			query.find().then(function(results) {
				var arrCandidates = [];
				var arrKeys = ["first_name", "last_name", "party", "objectId"];
				for (var j = results.length - 1; j >= 0; j--) {
					var candidate = {}
					for (var i = 0; i < 4; i++) {
						switch(arrKeys[i]) {
							case "first_name":
								candidate["first_name"] = results[j].get("first_name");
								break;
							case "last_name":
								candidate["last_name"] = results[j].get("last_name");
								break;
							case "party":
								candidate["party"] = results[j].get("party");
								break;
							case "objectId":
								candidate["id"] = results[j].id;
								break;
						}
					}
					arrCandidates.push(candidate);
				};
				resolve(arrCandidates)
			}, function(error) {
				reject(error)
			});
		})
	},
	getAllIssues: () => {
		// Get candidates from Parse
		return new Promise((resolve, reject) => {
			var query = new Parse.Query('')

			setTimeout(() => {
				let issues = [{id:"c", "name": "Climate Change"}, {"id":"d", "name": "Economy"}]
				resolve(issues)
			}, 200)
		})
	},
	getVideos: (issueIDs, candidateIDs, offset, limit) => {
		// issueID: array, issue ids to filter videos by, don't filter if empty array
		// candidateIDs: array, candidate ids to filter videos by, don't filter if empty array
		// offset: int, skip the first offset # of elements
		// limit: int, only return limit # of elements
		return new Promise((resolve, reject) => {
			setTimeout(() => {
				let videos = [{"id": "e", "issue_id":"c", "candidate_id":"a", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "f", "issue_id":"c", "candidate_id":"b", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "g", "issue_id":"a", "candidate_id":"c", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "h", "issue_id":"a", "candidate_id":"c", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "i", "issue_id":"a", "candidate_id":"c", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "j", "issue_id":"a", "candidate_id":"c", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "k", "issue_id":"a", "candidate_id":"c", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "l", "issue_id":"a", "candidate_id":"c", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "m", "issue_id":"a", "candidate_id":"c", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "n", "issue_id":"a", "candidate_id":"c", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "o", "issue_id":"a", "candidate_id":"c", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, {"id": "p", "issue_id":"a", "candidate_id":"c", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}]
				let retVideos = _.filter(videos, (video) => {
					if (issueIDs.length > 0) {
						let foundIssue = false
						for (let issueID of issueIDs) {
							if (video.issue_id == issueID) {
								foundIssue = true
								break
							}
						}
						if (!foundIssue)
							return false
					}
					if (candidateIDs.length > 0) {
						let foundCandidate = false
						for (let candidateID of candidateIDs) {
							if (video.candidate_id == candidateID) {
								foundCandidate = true
								break
							}
						}
						if (!foundCandidate)
							return false
					}
					return true
				})
				let result = retVideos.slice(offset, offset + limit)
				resolve(result)
			}, 200)
		})
	}
}

module.exports = ParseFetcher<|endoftext|>