<commit_before>import testUsers from '@ciscospark/test-helper-test-users';

import {moveMouse} from '../../../lib/test-helpers';
import {elements} from '../../../lib/test-helpers/space-widget/main.js';
import {answer, hangup, elements as meetElements} from '../../../lib/test-helpers/space-widget/meet.js';

describe('Widget Space: One on One: Data API Settings', () => {
  const browserLocal = browser.select('browserLocal');
  const browserRemote = browser.select('browserRemote');
  let mccoy, spock;

  before('load browsers', () => {
    browser.url('/data-api/space.html');
  });

  before('create spock', () => testUsers.create({count: 1, config: {displayName: 'Mr Spock'}})
    .then((users) => {
      [spock] = users;
    }));

  before('create mccoy', () => testUsers.create({count: 1, config: {displayName: 'Bones Mccoy'}})
    .then((users) => {
      [mccoy] = users;
    }));

  before('pause to let test users establish', () => browser.pause(5000));

  describe('initial activity setting: meet', () => {
    before('inject token', () => {
      browserLocal.execute((localAccessToken, localToUserEmail) => {
        const csmmDom = document.createElement('div');
        csmmDom.setAttribute('class', 'ciscospark-widget');
        csmmDom.setAttribute('data-toggle', 'ciscospark-space');
        csmmDom.setAttribute('data-access-token', localAccessToken);
        csmmDom.setAttribute('data-to-person-email', localToUserEmail);
        csmmDom.setAttribute('data-initial-activity', 'meet');
        document.getElementById('ciscospark-widget').appendChild(csmmDom);
        window.loadBundle('/dist-space/bundle.js');
      }, spock.token.access_token, mccoy.email);
      browserLocal.waitForVisible(elements.meetWidget);
    });

    it('opens meet widget', () => {
      browserLocal.waitForVisible(elements.meetButton);
      browserLocal.refresh();
    });
  });

  describe('initial activity setting: message', () => {
    before('inject token', () => {
      browserLocal.execute((localAccessToken, localToUserEmail) => {
        const csmmDom = document.createElement('div');
        csmmDom.setAttribute('class', 'ciscospark-widget');
        csmmDom.setAttribute('data-toggle', 'ciscospark-space');
        csmmDom.setAttribute('data-access-token', localAccessToken);
        csmmDom.setAttribute('data-to-person-email', localToUserEmail);
        csmmDom.setAttribute('data-initial-activity', 'message');
        document.getElementById('ciscospark-widget').appendChild(csmmDom);
        window.loadBundle('/dist-space/bundle.js');
      }, spock.token.access_token, mccoy.email);
    });

    it('opens message widget', () => {
      browserLocal.waitForVisible(elements.messageWidget);
      browserLocal.refresh();
    });
  });

  describe('start call setting', () => {
    before('inject token', () => {
      browserRemote.execute((localAccessToken, localToUserEmail) => {
        const csmmDom = document.createElement('div');
        csmmDom.setAttribute('class', 'ciscospark-widget');
        csmmDom.setAttribute('data-toggle', 'ciscospark-space');
        csmmDom.setAttribute('data-access-token', localAccessToken);
        csmmDom.setAttribute('data-to-person-email', localToUserEmail);
        csmmDom.setAttribute('data-initial-activity', 'meet');
        document.getElementById('ciscospark-widget').appendChild(csmmDom);
        window.loadBundle('/dist-space/bundle.js');
      }, mccoy.token.access_token, spock.email);
      browserRemote.waitForVisible(elements.meetWidget);
    });

    before('inject token', () => {
      browserLocal.execute((localAccessToken, localToUserEmail) => {
        const csmmDom = document.createElement('div');
        csmmDom.setAttribute('class', 'ciscospark-widget');
        csmmDom.setAttribute('data-toggle', 'ciscospark-space');
        csmmDom.setAttribute('data-access-token', localAccessToken);
        csmmDom.setAttribute('data-to-person-email', localToUserEmail);
        csmmDom.setAttribute('data-initial-activity', 'meet');
        csmmDom.setAttribute('data-start-call', true);
        document.getElementById('ciscospark-widget').appendChild(csmmDom);
        window.loadBundle('/dist-space/bundle.js');
      }, spock.token.access_token, mccoy.email);
      browserLocal.waitForVisible(elements.meetWidget);
    });

    it('starts call when set to true', () => {
      answer(browserRemote);
      moveMouse(browserLocal, meetElements.callContainer);
      hangup(browserLocal);
    });
  });
});
<commit_msg>fix(journeys): create conversation before start call test and add wait<commit_after>import testUsers from '@ciscospark/test-helper-test-users';
import CiscoSpark from '@ciscospark/spark-core';
import '@ciscospark/internal-plugin-conversation';

import {moveMouse} from '../../../lib/test-helpers';
import {elements} from '../../../lib/test-helpers/space-widget/main.js';
import {answer, hangup, elements as meetElements} from '../../../lib/test-helpers/space-widget/meet.js';

describe('Widget Space: One on One: Data API Settings', () => {
  const browserLocal = browser.select('browserLocal');
  const browserRemote = browser.select('browserRemote');
  let mccoy, spock, conversation;

  before('load browsers', () => {
    browser.url('/data-api/space.html');
  });

  before('create spock', () => testUsers.create({count: 1, config: {displayName: 'Mr Spock'}})
    .then((users) => {
      [spock] = users;
      spock.spark = new CiscoSpark({
        credentials: {
          authorization: spock.token
        },
        config: {
          logger: {
            level: 'error'
          }
        }
      });
      return spock.spark.internal.mercury.connect();
    }));

  before('create mccoy', () => testUsers.create({count: 1, config: {displayName: 'Bones Mccoy'}})
    .then((users) => {
      [mccoy] = users;
      mccoy.spark = new CiscoSpark({
        credentials: {
          authorization: mccoy.token
        },
        config: {
          logger: {
            level: 'error'
          }
        }
      });
      return mccoy.spark.internal.mercury.connect();
    }));

  before('pause to let test users establish', () => browser.pause(5000));

  before('create space', () => mccoy.spark.internal.conversation.create({
    participants: [mccoy, spock]
  }).then((c) => {
    conversation = c;
    return conversation;
  }));

  describe('initial activity setting: meet', () => {
    before('inject token', () => {
      browserLocal.execute((localAccessToken, localToUserEmail) => {
        const csmmDom = document.createElement('div');
        csmmDom.setAttribute('class', 'ciscospark-widget');
        csmmDom.setAttribute('data-toggle', 'ciscospark-space');
        csmmDom.setAttribute('data-access-token', localAccessToken);
        csmmDom.setAttribute('data-to-person-email', localToUserEmail);
        csmmDom.setAttribute('data-initial-activity', 'meet');
        document.getElementById('ciscospark-widget').appendChild(csmmDom);
        window.loadBundle('/dist-space/bundle.js');
      }, spock.token.access_token, mccoy.email);
      browserLocal.waitForVisible(elements.meetWidget);
    });

    it('opens meet widget', () => {
      browserLocal.waitForVisible(elements.meetButton);
      browserLocal.refresh();
    });
  });

  describe('initial activity setting: message', () => {
    before('inject token', () => {
      browserLocal.execute((localAccessToken, localToUserEmail) => {
        const csmmDom = document.createElement('div');
        csmmDom.setAttribute('class', 'ciscospark-widget');
        csmmDom.setAttribute('data-toggle', 'ciscospark-space');
        csmmDom.setAttribute('data-access-token', localAccessToken);
        csmmDom.setAttribute('data-to-person-email', localToUserEmail);
        csmmDom.setAttribute('data-initial-activity', 'message');
        document.getElementById('ciscospark-widget').appendChild(csmmDom);
        window.loadBundle('/dist-space/bundle.js');
      }, spock.token.access_token, mccoy.email);
    });

    it('opens message widget', () => {
      browserLocal.waitForVisible(elements.messageWidget);
      browserLocal.waitForVisible(`[placeholder="Send a message to ${mccoy.displayName}"]`);
      browserLocal.refresh();
    });
  });

  describe('start call setting', () => {
    before('inject token', () => {
      browserRemote.execute((localAccessToken, localToUserEmail) => {
        const csmmDom = document.createElement('div');
        csmmDom.setAttribute('class', 'ciscospark-widget');
        csmmDom.setAttribute('data-toggle', 'ciscospark-space');
        csmmDom.setAttribute('data-access-token', localAccessToken);
        csmmDom.setAttribute('data-to-person-email', localToUserEmail);
        csmmDom.setAttribute('data-initial-activity', 'message');
        document.getElementById('ciscospark-widget').appendChild(csmmDom);
        window.loadBundle('/dist-space/bundle.js');
      }, mccoy.token.access_token, spock.email);
      browserRemote.waitForVisible(elements.messageWidget);
      browserRemote.waitForVisible(`[placeholder="Send a message to ${spock.displayName}"]`);
    });

    before('inject token', () => {
      browserLocal.execute((localAccessToken, localToUserEmail) => {
        const csmmDom = document.createElement('div');
        csmmDom.setAttribute('class', 'ciscospark-widget');
        csmmDom.setAttribute('data-toggle', 'ciscospark-space');
        csmmDom.setAttribute('data-access-token', localAccessToken);
        csmmDom.setAttribute('data-to-person-email', localToUserEmail);
        csmmDom.setAttribute('data-initial-activity', 'meet');
        csmmDom.setAttribute('data-start-call', true);
        document.getElementById('ciscospark-widget').appendChild(csmmDom);
        window.loadBundle('/dist-space/bundle.js');
      }, spock.token.access_token, mccoy.email);
      browserLocal.waitForVisible(elements.meetWidget);
    });

    it('starts call when set to true', () => {
      browser.pause(5000);
      answer(browserRemote);
      moveMouse(browserLocal, meetElements.callContainer);
      hangup(browserLocal);
    });
  });
});
<|endoftext|>


<commit_before>// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
<commit_msg>JC: added 2 datepickers.<commit_after>// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
$(function() {
   $("#task_start_date").datepicker({dateFormat: 'yy-mm-dd'});
});
$(function() {
   $("#task_finish_date").datepicker({dateFormat: 'yy-mm-dd'});
});<|endoftext|>


<commit_before>#!/usr/bin/env node
/*
 * Copyright (c) 2016, Two Sigma Open Source
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * * Neither the name of git-meta nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * This module contains the entrypoint for the `git-meta` program.  All
 * significant functionality is deferred to the sub-commands.
 */

const ArgumentParser = require("argparse").ArgumentParser;
const NodeGit = require("nodegit");

const add          = require("./cmd/add");
const addSubmodule = require("./cmd/add_submodule");
const checkout     = require("./cmd/checkout");
const cherryPick   = require("./cmd/cherry_pick");
const close        = require("./cmd/close");
const commit       = require("./cmd/commit");
const Forward      = require("./cmd/forward");
const include      = require("./cmd/include");
const listFiles    = require("./cmd/list_files");
const merge        = require("./cmd/merge");
const open         = require("./cmd/open");
const pull         = require("./cmd/pull");
const push         = require("./cmd/push");
const rebase       = require("./cmd/rebase");
const reset        = require("./cmd/reset");
const rm           = require("./cmd/rm");
const root         = require("./cmd/root");
const commitShadow = require("./cmd/commit-shadow");
const stash        = require("./cmd/stash");
const status       = require("./cmd/status");
const syncrefs     = require("./cmd/syncrefs");
const submodule    = require("./cmd/submodule");
const UserError    = require("./util/user_error");
const version      = require("./cmd/version");

// see https://github.com/nodegit/nodegit/issues/827 -- this is required
// to prevent random hard crashes with e.g. parallelism in index operations.
// Eventually, this will be nodegit's default.
NodeGit.setThreadSafetyStatus(NodeGit.THREAD_SAFETY.ENABLED_FOR_ASYNC_ONLY);

/**
 * Configure the specified `parser` to include the command having the specified
 * `commandName` implemented in the specified `module`.
 *
 * @param {ArgumentParser} parser
 * @param {String}         commandName
 * @param {Object}         module
 * @param {Function}       module.configureParser
 * @param {Function}       module.executeableSubcommand
 * @param {String}         module.helpText
 */
function configureSubcommand(parser, commandName, module) {
    const subParser = parser.addParser(commandName, {
        help: module.helpText,
        description: module.description,
    });
    module.configureParser(subParser);
    subParser.setDefaults({
        func: function (args) {
            module.executeableSubcommand(args)
            .catch(function (error) {

                // If it's a 'UserError', don't print the stack, just the
                // diagnostic message because the stack is irrelevant.

                if (error instanceof UserError) {
                    console.error(error.message);
                }
                else {
                    console.error(error.stack);
                }
                process.exit(-1);
            });
        }
    });
}

const description = `These commands are intended to make Git submodules more
powerful and easier to use.  Commands with the same name as regular Git
commands will generally perform that same operation, but across a *meta*
repository and the *sub* repositories that are locally *opened*.  These
commands work on any Git repository (even one without configured submodules);
we do not provide duplicate commands for Git functionality that does not need
to be applied across sub-modules such as 'clone' and 'init'.  Note that
git-meta will forward any subcommand that it does not implement to Git,
as if run with 'git -C $(git meta root) ...'.`;

const parser = new ArgumentParser({
    addHelp:true,
    description: description
});

const subParser = parser.addSubparsers({});

const commands = {
    "add": add,
    "checkout": checkout,
    "cherry-pick": cherryPick,
    "close": close,
    "commit": commit,
    "include": include,
    "ls-files": listFiles,
    "merge": merge,
    "add-submodule": addSubmodule,
    "open": open,
    "pull": pull,
    "push": push,
    "rebase": rebase,
    "reset": reset,
    "rm": rm,
    "root": root,
    "commit-shadow": commitShadow,
    "stash": stash,
    "submodule": submodule,
    "status": status,
    "sync-refs": syncrefs,
    "version": version,
};

// Configure the parser with commands in alphabetical order.

Object.keys(commands).sort().forEach(name => {
    const cmd = commands[name];
    configureSubcommand(subParser, name, cmd);
});

const blacklist = new Set([
    "--help",
    "--version",
    "-h",
    "am",
    "annotate",
    "archimport",
    "archive",
    "blame",
    "clean",
    "cvsexportcommit",
    "cvsimport",
    "cvsserver",
    "fast-export",
    "fast-import",
    "filter-branch",
    "grep",
    "merge-file",
    "merge-index",
    "merge-tree",
    "mv",
    "p4",
    "quiltimport",
    "revert",
    "rm",
    "shell",
    "stage",
    "svn",
    "worktree",
]);

// If the first argument matches a forwarded sub-command, handle it manually.
// I was not able to get ArgParse to allow unknown flags, e.g.
// `git meta branch -r` to be passed to the REMAINDER positional argument on a
// sub-parser level.

if (2 < process.argv.length &&
    !blacklist.has(process.argv[2]) &&
    !(process.argv[2] in commands)) {
    const name = process.argv[2];
    const args = process.argv.slice(3);
    Forward.execute(name, args).catch(() => {
        process.exit(-1);
    });
}
else {
    const args = parser.parseArgs();
    args.func(args);
}
<commit_msg>Wait until completion of argparse to load NodeGit.<commit_after>#!/usr/bin/env node
/*
 * Copyright (c) 2016, Two Sigma Open Source
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * * Neither the name of git-meta nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * This module contains the entrypoint for the `git-meta` program.  All
 * significant functionality is deferred to the sub-commands.
 */

const ArgumentParser = require("argparse").ArgumentParser;

const add          = require("./cmd/add");
const addSubmodule = require("./cmd/add_submodule");
const checkout     = require("./cmd/checkout");
const cherryPick   = require("./cmd/cherry_pick");
const close        = require("./cmd/close");
const commit       = require("./cmd/commit");
const Forward      = require("./cmd/forward");
const include      = require("./cmd/include");
const listFiles    = require("./cmd/list_files");
const merge        = require("./cmd/merge");
const open         = require("./cmd/open");
const pull         = require("./cmd/pull");
const push         = require("./cmd/push");
const rebase       = require("./cmd/rebase");
const reset        = require("./cmd/reset");
const rm           = require("./cmd/rm");
const root         = require("./cmd/root");
const commitShadow = require("./cmd/commit-shadow");
const stash        = require("./cmd/stash");
const status       = require("./cmd/status");
const syncrefs     = require("./cmd/syncrefs");
const submodule    = require("./cmd/submodule");
const UserError    = require("./util/user_error");
const version      = require("./cmd/version");

/**
 * Configure the specified `parser` to include the command having the specified
 * `commandName` implemented in the specified `module`.
 *
 * @param {ArgumentParser} parser
 * @param {String}         commandName
 * @param {Object}         module
 * @param {Function}       module.configureParser
 * @param {Function}       module.executeableSubcommand
 * @param {String}         module.helpText
 */
function configureSubcommand(parser, commandName, module) {
    const subParser = parser.addParser(commandName, {
        help: module.helpText,
        description: module.description,
    });
    module.configureParser(subParser);
    subParser.setDefaults({
        func: function (args) {
            const NodeGit = require("nodegit");
            // see https://github.com/nodegit/nodegit/issues/827 -- this is required
            // to prevent random hard crashes with e.g. parallelism in index operations.
            // Eventually, this will be nodegit's default.
            NodeGit.setThreadSafetyStatus(NodeGit.THREAD_SAFETY.ENABLED_FOR_ASYNC_ONLY);

            module.executeableSubcommand(args)
            .catch(function (error) {

                // If it's a 'UserError', don't print the stack, just the
                // diagnostic message because the stack is irrelevant.

                if (error instanceof UserError) {
                    console.error(error.message);
                }
                else {
                    console.error(error.stack);
                }
                process.exit(-1);
            });
        }
    });
}

const description = `These commands are intended to make Git submodules more
powerful and easier to use.  Commands with the same name as regular Git
commands will generally perform that same operation, but across a *meta*
repository and the *sub* repositories that are locally *opened*.  These
commands work on any Git repository (even one without configured submodules);
we do not provide duplicate commands for Git functionality that does not need
to be applied across sub-modules such as 'clone' and 'init'.  Note that
git-meta will forward any subcommand that it does not implement to Git,
as if run with 'git -C $(git meta root) ...'.`;

const parser = new ArgumentParser({
    addHelp:true,
    description: description
});

const subParser = parser.addSubparsers({});

const commands = {
    "add": add,
    "checkout": checkout,
    "cherry-pick": cherryPick,
    "close": close,
    "commit": commit,
    "include": include,
    "ls-files": listFiles,
    "merge": merge,
    "add-submodule": addSubmodule,
    "open": open,
    "pull": pull,
    "push": push,
    "rebase": rebase,
    "reset": reset,
    "rm": rm,
    "root": root,
    "commit-shadow": commitShadow,
    "stash": stash,
    "submodule": submodule,
    "status": status,
    "sync-refs": syncrefs,
    "version": version,
};

// Configure the parser with commands in alphabetical order.

Object.keys(commands).sort().forEach(name => {
    const cmd = commands[name];
    configureSubcommand(subParser, name, cmd);
});

const blacklist = new Set([
    "--help",
    "--version",
    "-h",
    "am",
    "annotate",
    "archimport",
    "archive",
    "blame",
    "clean",
    "cvsexportcommit",
    "cvsimport",
    "cvsserver",
    "fast-export",
    "fast-import",
    "filter-branch",
    "grep",
    "merge-file",
    "merge-index",
    "merge-tree",
    "mv",
    "p4",
    "quiltimport",
    "revert",
    "rm",
    "shell",
    "stage",
    "svn",
    "worktree",
]);

// If the first argument matches a forwarded sub-command, handle it manually.
// I was not able to get ArgParse to allow unknown flags, e.g.
// `git meta branch -r` to be passed to the REMAINDER positional argument on a
// sub-parser level.

if (2 < process.argv.length &&
    !blacklist.has(process.argv[2]) &&
    !(process.argv[2] in commands)) {
    const name = process.argv[2];
    const args = process.argv.slice(3);
    Forward.execute(name, args).catch(() => {
        process.exit(-1);
    });
}
else {
    const args = parser.parseArgs();
    args.func(args);
}
<|endoftext|>


<commit_before>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace poisson
*/
var poisson = {};

/**
* @name cdf
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/cdf}
*/
setReadOnly( poisson, 'cdf', require( '@stdlib/math/base/dist/poisson/cdf' ) );

/**
* @name kurtosis
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/kurtosis}
*/
setReadOnly( poisson, 'kurtosis', require( '@stdlib/math/base/dist/poisson/kurtosis' ) );

/**
* @name mean
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/mean}
*/
setReadOnly( poisson, 'mean', require( '@stdlib/math/base/dist/poisson/mean' ) );

/**
* @name median
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/median}
*/
setReadOnly( poisson, 'median', require( '@stdlib/math/base/dist/poisson/median' ) );

/**
* @name mgf
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/mgf}
*/
setReadOnly( poisson, 'mgf', require( '@stdlib/math/base/dist/poisson/mgf' ) );

/**
* @name mode
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/mode}
*/
setReadOnly( poisson, 'mode', require( '@stdlib/math/base/dist/poisson/mode' ) );

/**
* @name pmf
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/pmf}
*/
setReadOnly( poisson, 'pmf', require( '@stdlib/math/base/dist/poisson/pmf' ) );

/**
* @name Poisson
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/ctor}
*/
setReadOnly( poisson, 'Poisson', require( '@stdlib/math/base/dist/poisson/ctor' ) );

/**
* @name quantile
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/quantile}
*/
setReadOnly( poisson, 'quantile', require( '@stdlib/math/base/dist/poisson/quantile' ) );

/**
* @name skewness
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/skewness}
*/
setReadOnly( poisson, 'skewness', require( '@stdlib/math/base/dist/poisson/skewness' ) );

/**
* @name variance
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/variance}
*/
setReadOnly( poisson, 'variance', require( '@stdlib/math/base/dist/poisson/variance' ) );

// EXPORTS //

module.exports = poisson;
<commit_msg>Add stdev to Poisson namespace<commit_after>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace poisson
*/
var poisson = {};

/**
* @name cdf
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/cdf}
*/
setReadOnly( poisson, 'cdf', require( '@stdlib/math/base/dist/poisson/cdf' ) );

/**
* @name kurtosis
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/kurtosis}
*/
setReadOnly( poisson, 'kurtosis', require( '@stdlib/math/base/dist/poisson/kurtosis' ) );

/**
* @name mean
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/mean}
*/
setReadOnly( poisson, 'mean', require( '@stdlib/math/base/dist/poisson/mean' ) );

/**
* @name median
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/median}
*/
setReadOnly( poisson, 'median', require( '@stdlib/math/base/dist/poisson/median' ) );

/**
* @name mgf
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/mgf}
*/
setReadOnly( poisson, 'mgf', require( '@stdlib/math/base/dist/poisson/mgf' ) );

/**
* @name mode
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/mode}
*/
setReadOnly( poisson, 'mode', require( '@stdlib/math/base/dist/poisson/mode' ) );

/**
* @name pmf
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/pmf}
*/
setReadOnly( poisson, 'pmf', require( '@stdlib/math/base/dist/poisson/pmf' ) );

/**
* @name Poisson
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/ctor}
*/
setReadOnly( poisson, 'Poisson', require( '@stdlib/math/base/dist/poisson/ctor' ) );

/**
* @name quantile
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/quantile}
*/
setReadOnly( poisson, 'quantile', require( '@stdlib/math/base/dist/poisson/quantile' ) );

/**
* @name skewness
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/skewness}
*/
setReadOnly( poisson, 'skewness', require( '@stdlib/math/base/dist/poisson/skewness' ) );

/**
* @name stdev
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/stdev}
*/
setReadOnly( poisson, 'stdev', require( '@stdlib/math/base/dist/poisson/stdev' ) );

/**
* @name variance
* @memberof poisson
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/poisson/variance}
*/
setReadOnly( poisson, 'variance', require( '@stdlib/math/base/dist/poisson/variance' ) );

// EXPORTS //

module.exports = poisson;
<|endoftext|>


<commit_before>import { takeEvery, select, call, put, fork, cancel } from 'redux-saga/effects';
import {
    INIT,
    TOGGLE_PAUSE,
    onPlayerPaused,
    onPlayerPlaying,
    SET_CURRENT_TRACK_INDEX,
    onPlayerEnd,
    onPlayerPrematureEnd,
    GO_TO_NEXT_TRACK,
    GO_TO_PREV_TRACK,
    STEP_BACK,
    STEP_FORWARD,
    onPlayerCurrentTimeChanged
} from '../ducks/tracks';
import { MPlayer } from 'mplayer-as-promised';
import { retryIfBusy, ignoreWhatever } from '../lib/asyncHelpers';
import sleep from 'sleep-promise';

function* playerSaga() {
    let player, playerItem;

    yield takeEvery(INIT, function() {
        player = new MPlayer();
    });

    yield takeEvery(TOGGLE_PAUSE, function*() {
        const isPaused = (yield select()).tracks.isPaused;
        if (isPaused) {
            yield call(retryIfBusy, ::playerItem.pause);
            yield put(onPlayerPaused());
        } else {
            yield call(retryIfBusy, ::playerItem.play);
            yield put(onPlayerPlaying());
        }
    });

    yield takeEvery(
        [SET_CURRENT_TRACK_INDEX, GO_TO_NEXT_TRACK, GO_TO_PREV_TRACK],
        function*() {
            const state = yield select();
            const tracks = state.tracks.tracks;
            const track = tracks[state.tracks.current];
            if (playerItem) {
                yield call(retryIfBusy, ::playerItem.stop); //TODO: is needed?
            }
            playerItem = yield call(retryIfBusy, () =>
                player.openFile(track.url)
            );

            yield put(onPlayerPlaying());
            const positionPollerTask = yield fork(
                createPositionPoller(playerItem)
            );
            try {
                yield call(::playerItem.listen);
                playerItem = null;
                yield put(onPlayerEnd());
            } catch (e) {
                yield put(onPlayerPrematureEnd());
            } finally {
                yield cancel(positionPollerTask);
            }
        }
    );

    yield takeEvery(STEP_BACK, function*() {
        yield call(ignoreWhatever, () => playerItem.seekBy(-10));
    });

    yield takeEvery(STEP_FORWARD, function*() {
        yield call(ignoreWhatever, () => playerItem.seekBy(10));
    });
}

const createPositionPoller = playerItem =>
    function* positionPoller() {
        try {
            while (true) {
                const timeSeconds = yield call(ignoreWhatever, () =>
                    playerItem.getCurrentPercent()
                );
                yield put(onPlayerCurrentTimeChanged(timeSeconds));
                yield call(sleep, 1000);
            }
        } finally {
        }
    };

export default playerSaga;
<commit_msg>fix: fork<commit_after>import { takeEvery, select, call, put, fork, cancel } from 'redux-saga/effects';
import {
    INIT,
    TOGGLE_PAUSE,
    onPlayerPaused,
    onPlayerPlaying,
    SET_CURRENT_TRACK_INDEX,
    onPlayerEnd,
    onPlayerPrematureEnd,
    GO_TO_NEXT_TRACK,
    GO_TO_PREV_TRACK,
    STEP_BACK,
    STEP_FORWARD,
    onPlayerCurrentTimeChanged
} from '../ducks/tracks';
import { MPlayer } from 'mplayer-as-promised';
import { retryIfBusy, ignoreWhatever } from '../lib/asyncHelpers';
import sleep from 'sleep-promise';

function* playerSaga() {
    let player, playerItem;

    yield takeEvery(INIT, function() {
        player = new MPlayer();
    });

    yield takeEvery(TOGGLE_PAUSE, function*() {
        const isPaused = (yield select()).tracks.isPaused;
        if (isPaused) {
            yield call(retryIfBusy, ::playerItem.pause);
            yield put(onPlayerPaused());
        } else {
            yield call(retryIfBusy, ::playerItem.play);
            yield put(onPlayerPlaying());
        }
    });

    yield takeEvery(
        [SET_CURRENT_TRACK_INDEX, GO_TO_NEXT_TRACK, GO_TO_PREV_TRACK],
        function*() {
            const state = yield select();
            const tracks = state.tracks.tracks;
            const track = tracks[state.tracks.current];
            if (playerItem) {
                yield call(retryIfBusy, ::playerItem.stop); //TODO: is needed?
            }
            playerItem = yield call(retryIfBusy, () =>
                player.openFile(track.url)
            );

            yield put(onPlayerPlaying());
            const positionPollerTask = yield fork(positionPoller, playerItem);
            try {
                yield call(::playerItem.listen);
                playerItem = null;
                yield put(onPlayerEnd());
            } catch (e) {
                yield put(onPlayerPrematureEnd());
            } finally {
                yield cancel(positionPollerTask);
            }
        }
    );

    yield takeEvery(STEP_BACK, function*() {
        yield call(ignoreWhatever, () => playerItem.seekBy(-10));
    });

    yield takeEvery(STEP_FORWARD, function*() {
        yield call(ignoreWhatever, () => playerItem.seekBy(10));
    });
}

function* positionPoller(playerItem) {
    try {
        yield put(onPlayerCurrentTimeChanged(0));
        while (true) {
            const percent = yield call(ignoreWhatever, () =>
                playerItem.getCurrentPercent()
            );
            yield put(onPlayerCurrentTimeChanged(percent));
            yield call(sleep, 1000);
        }
    } finally {
        yield put(onPlayerCurrentTimeChanged(0));
    }
}

export default playerSaga;
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2017 Edward Shen
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import BaseProcessor from './baseProcessor';

class addPreRequisiteFor extends BaseProcessor.BaseProcessor {
  go(termDump) {
    for (const aClass of termDump.classes) {
      this.parsePreReqs(aClass.prereqs);
    }

    return termDump;
  }

  // Prerequisite -> null
  // Parses the Prerequisite and calls the respective function to deal with
  // each one
  parsePreReqs(prereqs) {
    if (prereqs.type === 'and') {
      this.parseAndPreReqs(prereqs.values);
    } else {
      this.parseOrPreReqs(prereqs.values);
    }
  }

  // Prerequisite -> null
  // Parses a prerequisite that
  parseAndPreReqs(prereq) {
    if (Array.isArray(prereq)) {
      prereq.forEach((req) => { this.parsePreReqs(req); });
    } else {

    }
  }

  parseOrPreReqs(prereq) {
    if (Array.isArray) {
      prereq.forEach((req) => { this.parsePreReqs(req); });
    } else {

    }
  }
}

export default addPreRequisiteFor;
<commit_msg>Simplify and reduce parsePreReqs<commit_after>/*
 * Copyright (c) 2017 Edward Shen
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import BaseProcessor from './baseProcessor';

class addPreRequisiteFor extends BaseProcessor.BaseProcessor {
  go(termDump) {
    for (const aClass of termDump.classes) {
      this.parsePreReqs(aClass.prereqs);
    }

    return termDump;
  }
  // Recursively traverse the prerequsite structure
  outputParsePreReqs(prereqs) {
    return `${prereqs.values.reduce((sum, aclass) => {
      if (!aclass.missing) {
        return `${sum} ${aclass.classUid}`;
      }
      return `${sum} 00000`;
    }, `(${prereqs.type}`)} )`;
  }

  // Recursively traverse the prerequsite structure
  parsePreReqs(prereqs) {
    return prereqs.values.map((obj) => {
      // If there's a type, then it's not a class but rather a structure obj.
      if (obj.type) {
        return this.parsePreReqs(obj);
      }

      // Deal with the class
      return this.parseClass(obj);
    });
  }

  parseClass(aclass) {
    return aclass.classUid;
  }
}

export default addPreRequisiteFor;
<|endoftext|>


<commit_before>define(["config",
        "app/app",
        "ember",
        "lodash",
        "components/Pagination"], function(config, App, Ember, _) {
  "use strict";

  // "Abstract" generic controller for timelines
  App.TimelineGenericController = Ember.Controller.extend(App.Pagination, {
    selectFeedsOnCreate: true,
    attachFilesOnCreate: true,

    // NOTE: this code doesn't work reliably, see
    // https://github.com/emberjs/ember.js/issues/10343
    //postSortProperties: ['createdAt:desc'],
    //posts: Ember.computed.sort('model.posts', 'postSortProperties'),

    posts: function() {
      return Ember.ArrayProxy.createWithMixins(Ember.SortableMixin, {
        sortProperties: ['updatedAt'],
        sortAscending: false,
        content: this.get('model.posts')
      })
    }.property('model.posts'),

    // 'attachments' should be an instance property (set on init), not a prototype property
    setupAttachments: function() {
      this.set('attachments', []);
    }.on('init'),

    didRequestRange: function(options) {
      this.transitionToRoute({ queryParams: { offset: options.offset } })
    },

    myFeed: function() {
      return (this.get('model.user.id') == this.get('session.currentUser.id')
              && this.get('model.user.isUser'))
        || (_.contains(this.get('model.subscribers'), this.get('session.currentUser.id'))
            && this.get('model.user.isGroup'))
    }.property('model.user.id', 'session.currentUser.id'),

    isSubscribed: function() {
      var currentUser = this.get('session.currentUser')
      if (!currentUser) { return false }

      return currentUser.get('subscriptions').isAny('id', this.get('model.id'))
    }.property('session.currentUser.id', 'session.currentUser.subscriptions.@each', 'model.id'),

    isAdmin: function() {
      var adminIds = this.get('model.user.administratorIds')
      var currentUserId = this.get('session.currentUser.id')

      return adminIds && adminIds.indexOf(currentUserId) !== -1
    }.property('session.currentUser.id'),

    isAttachmentsVisible: false,

    actions: {
      showAttachments: function() {
        this.toggleProperty('isAttachmentsVisible')
      },

      subscribe: function() {
        var user = this.get('model.user')
        Ember.$.ajax({
          url: config.host + '/v1/users/' + user.get('username') + '/subscribe',
          type: 'post',
          context: this
        })
          .then(function(response) {
            var user = this.store.recordForId('user', response.users.id)
            this.store.unloadRecord(user)
            this.store.pushPayload('user', response)
            this.get('session').set('currentUser', this.store.getById('user', response.users.id))
          })
      },

      unsubscribe: function() {
        var user = this.get('model.user')
        Ember.$.ajax({
          url: config.host + '/v1/users/' + user.get('username') + '/unsubscribe',
          type: 'post',
          context: this
        })
          .then(function(response) {
            var user = this.store.recordForId('user', response.users.id)
            this.store.unloadRecord(user)
            this.store.pushPayload('user', response)
            this.get('session').set('currentUser', this.store.getById('user', response.users.id))
          })
      },

      addAttachment: function(file) {
        // Create an attachment record
        var attachment = this.store.createRecord('attachment', {
          file: file
        })

        // Add a throbber (placeholder object, to show uploading progress)
        var attachmentList = this.get('attachments')
        var throbber = this.store.createRecord('attachment', { thumbnailUrl: '/img/throbber-100.gif' })
        var throbberIndex = attachmentList.length
        attachmentList.pushObject(throbber)

        // Save the attachment record to the backend
        attachment.save()
          .then(function(attachment) {
            // Replace the throbber with a real record
            attachmentList.replace(throbberIndex, 1, [ attachment ])
          })
      },

      create: function() {
        // Allow/disallow selecting feeds
        var feeds;
        if (this.get('selectFeedsOnCreate')) {
          feeds = Ember.$('#sendToSelect').val()
        } else {
          feeds = this.get('model.user.username')
        }

        // Create a post record
        var post = this.store.createRecord('post', {
          body: this.get('body'),
          feeds: feeds
        })

        // Attach the attachments (without throbbers, if any)
        var attachmentList = this.get('attachments')
          .filter(function(item) {
            return !!item.id
          })
        post.get('attachments').pushObjects(attachmentList)

        // Clear the form
        this.set('body', '')
        this.set('attachments', [])
        this.set('isAttachmentsVisible', false)

        // Save it to the backend
        post.save()
      }
    }
  })
})
<commit_msg>Makes post creation more reliable<commit_after>define(["config",
        "app/app",
        "ember",
        "lodash",
        "components/Pagination"], function(config, App, Ember, _) {
  "use strict";

  // "Abstract" generic controller for timelines
  App.TimelineGenericController = Ember.Controller.extend(App.Pagination, {
    selectFeedsOnCreate: true,
    attachFilesOnCreate: true,

    // NOTE: this code doesn't work reliably, see
    // https://github.com/emberjs/ember.js/issues/10343
    //postSortProperties: ['createdAt:desc'],
    //posts: Ember.computed.sort('model.posts', 'postSortProperties'),

    posts: function() {
      return Ember.ArrayProxy.createWithMixins(Ember.SortableMixin, {
        sortProperties: ['updatedAt'],
        sortAscending: false,
        content: this.get('model.posts')
      })
    }.property('model.posts.[]'),

    // 'attachments' should be an instance property (set on init), not a prototype property
    setupAttachments: function() {
      this.set('attachments', []);
    }.on('init'),

    didRequestRange: function(options) {
      this.transitionToRoute({ queryParams: { offset: options.offset } })
    },

    myFeed: function() {
      return (this.get('model.user.id') == this.get('session.currentUser.id')
              && this.get('model.user.isUser'))
        || (_.contains(this.get('model.subscribers'), this.get('session.currentUser.id'))
            && this.get('model.user.isGroup'))
    }.property('model.user.id', 'session.currentUser.id'),

    isSubscribed: function() {
      var currentUser = this.get('session.currentUser')
      if (!currentUser) { return false }

      return currentUser.get('subscriptions').isAny('id', this.get('model.id'))
    }.property('session.currentUser.id', 'session.currentUser.subscriptions.@each', 'model.id'),

    isAdmin: function() {
      var adminIds = this.get('model.user.administratorIds')
      var currentUserId = this.get('session.currentUser.id')

      return adminIds && adminIds.indexOf(currentUserId) !== -1
    }.property('session.currentUser.id'),

    isAttachmentsVisible: false,

    actions: {
      showAttachments: function() {
        this.toggleProperty('isAttachmentsVisible')
      },

      subscribe: function() {
        var user = this.get('model.user')
        Ember.$.ajax({
          url: config.host + '/v1/users/' + user.get('username') + '/subscribe',
          type: 'post',
          context: this
        })
          .then(function(response) {
            var user = this.store.recordForId('user', response.users.id)
            this.store.unloadRecord(user)
            this.store.pushPayload('user', response)
            this.get('session').set('currentUser', this.store.getById('user', response.users.id))
          })
      },

      unsubscribe: function() {
        var user = this.get('model.user')
        Ember.$.ajax({
          url: config.host + '/v1/users/' + user.get('username') + '/unsubscribe',
          type: 'post',
          context: this
        })
          .then(function(response) {
            var user = this.store.recordForId('user', response.users.id)
            this.store.unloadRecord(user)
            this.store.pushPayload('user', response)
            this.get('session').set('currentUser', this.store.getById('user', response.users.id))
          })
      },

      addAttachment: function(file) {
        // Create an attachment record
        var attachment = this.store.createRecord('attachment', {
          file: file
        })

        // Add a throbber (placeholder object, to show uploading progress)
        var attachmentList = this.get('attachments')
        var throbber = this.store.createRecord('attachment', { thumbnailUrl: '/img/throbber-100.gif' })
        var throbberIndex = attachmentList.length
        attachmentList.pushObject(throbber)

        // Save the attachment record to the backend
        attachment.save()
          .then(function(attachment) {
            // Replace the throbber with a real record
            attachmentList.replace(throbberIndex, 1, [ attachment ])
          })
      },

      create: function() {
        // Allow/disallow selecting feeds
        var feeds
        if (this.get('selectFeedsOnCreate')) {
          feeds = Ember.$('#sendToSelect').val()
        } else {
          feeds = this.get('model.user.username')
        }

        // Create a post record
        var post = this.store.createRecord('post', {
          body: this.get('body'),
          feeds: feeds
        })

        // Attach the attachments (without throbbers, if any)
        var attachmentList = this.get('attachments')
          .filter(function(item) {
            return !!item.id
          })
        post.get('attachments').pushObjects(attachmentList)

        // Clear the form
        this.set('body', '')
        this.set('attachments', [])
        this.set('isAttachmentsVisible', false)

        // Save it to the backend
        var that = this
        post.save()
          .then(function(post) {
            var object = that.get('model.posts').findProperty('id', post.get('id'))
            console.log(object)
            if (!object) {
              that.get('model.posts').addObject(post)
            }
          })
      }
    }
  })
})
<|endoftext|>


<commit_before>////////
// INGREDIENTS
//////

var testIngredient1 = {
    changed: true,
    name: 'beef fillets',                 //name of ingredient
    type: null,                 //type of ingredient (dairy, meat, vegetable, etc)
    position: 1,             //Order of ingredients
    amount: 400,               //OPTIONAL: Amount of ingredient
    unit: 'g',                 //OPTIONAL: Unit of ingredient (cups, tbsp, etc)
    prep: '',                 //OPTIONAL: Preperation of ingredient (chopped, diced)
    substitutes: null,         //Optional: Substitute ingredients for that ingredient
    optional: null             //Whether ingredient is necessary
  }

var testIngredient2 = {
    changed: true,
    name: 'wild mushrooms',
    type: null,
    position: 2,
    amount: 500,
    unit: 'g',
    prep: 'cleaned',
    substitutes: null,
    optional: null
  }

var testIngredient3 = {
  changed: true,
  name: 'puff pastry',
  type: null,
  position: 3,
  amount: 500,
  unit: 'g',
  prep: null,
  substitutes: null,
  optional: null
}

var testIngredient4 = {
  changed: true,
  name: 'egg yolks',
  type: null,
  position: 4,
  amount: 2,
  unit: 'whole',
  prep: 'beaten with a pinch of salt',
  substitutes: null,
  optional: null
}

var testIngredient5 = {
  changed: true,
  name: 'shallots',
  type: null,
  position: 5,
  amount: 4,
  unit: 'whole',
  prep: 'peeled and sliced',
  substitutes: null,
  optional: null
}

var testIngredient6 = {
  changed: true,
  name: 'bottle red wine',
  type: null,
  position: 6,
  amount: 1,
  unit: 'whole',
  prep: 'not for drinking',
  substitutes: null,
  optional: null
}

var wellingtonIngredients = [testIngredient1, testIngredient2, testIngredient3, testIngredient4, testIngredient5, testIngredient6];

////////
// STEPS
//////

var testStep1 = {
  changed: true,
  position: 1,
  description: "Wrap each piece of beef tightly in a triple layer of cling film to set its shape, then chill overnight.",
  time: null,                 //OPTIONAL: Time to complete step
  ingredients: ['beef fillets']
}

var testStep2 = {
  changed: true,
  position: 2,
  description: "Remove the cling film, then quickly sear the beef fillets in a hot pan with a little olive oil for 30-60 seconds until browned all over and rare in the middle. Remove from the pan and leave to cool.",
  time: 1,                 //OPTIONAL: Time to complete step
  ingredients: ['olive oil', 'beef fillets']
}

var testStep3 = {
  changed: true,
  position: 3,
  description: "Finely chop the mushrooms and fry in a hot pan with a little olive oil, the thyme leaves and some seasoning. When the mushrooms begin to release their juices, continue to cook over a high heat for about 10 minutes until all the excess moisture has evaporated and you are left with a mushroom paste (known as a duxelle).",
  ingredients: ['wild mushrooms', 'olive oil','thyme leaves']
}

var testStep4 = {
  changed: true,
  position: 4,
  description: "Cut the pastry in half, place on a lightly floured surface and roll each piece into a rectangle large enough to envelop one of the beef fillets. Chill in the refrigerator.",
  ingredients: ['puff pastry']
}

var testStep5 = {
  changed: true,
  position: 4,
  description: "Season the beef fillets, then place them on top of the mushroom-covered ham. Using the cling film, roll the Parma ham over the beef, then roll and tie the cling film to get a nice, evenly thick log. Repeat this step with the other beef fillet, then chill for at least 30 minutes.",
  ingredients: ['beef fillets', 'wild mushrooms', 'Parma ham']
}

var testStep6 = {
  changed: true,
  position: 4,
  description: "Prepare the red wine sauce. Heat the oil in a large pan, then fry the beef trimmings for a few minutes until browned on all sides. Stir in the shallots with the peppercorns, bay and thyme and continue to cook for about 5 minutes, stirring frequently, until the shallots turn golden brown.",
  ingredients: ['bottle red wine', 'beef trimmings', 'shallots', 'peppercorns']
}

var wellingtonRecipe = {
  name: {
    changed: true,
    value: 'Beef Wellington'
  },
  picture: {
    changed: true,
    value: "https://gordonramsay-2938.kxcdn.com/assets/Recipes/_resampled/CroppedFocusedImage108081050-50-APPROVED-Gordons-Wellington2.jpg"
  },
  description: {
      changed: true,
      value: "Beef Wellington is a preparation of filet steak coated with pâté (often pâté de foie gras) and duxelles, which is then wrapped in puff pastry and baked. Some recipes include wrapping the coated meat in a crêpe to retain the moisture and prevent it from making the pastry soggy."
  },
  servings: {
    changed: true,
    value: 'Serves 4 to 6'
  },
  cookTime: {
    changed: true,
    value: '2 hours',  //Cook time in minutes
  },
  skillLevel: {                             //Recipe difficulty [easy, medium, hard]
    changed: true,
    value: 'Scrum Master'
  },
  dependencies: [],
  ingredients: wellingtonIngredients,
  steps: [testStep1, testStep2, testStep3, testStep4, testStep5, testStep6],
  tags: [],
  issues: []
};

module.exports = wellingtonRecipe; <commit_msg>Modify recipes test data directory<commit_after>////////
// INGREDIENTS
//////

var testIngredient1 = {
    changed: true,
    name: 'beef fillets',                 //name of ingredient
    type: null,                 //type of ingredient (dairy, meat, vegetable, etc)
    position: 1,             //Order of ingredients
    amount: 400,               //OPTIONAL: Amount of ingredient
    unit: 'g',                 //OPTIONAL: Unit of ingredient (cups, tbsp, etc)
    prep: '',                 //OPTIONAL: Preperation of ingredient (chopped, diced)
    substitutes: null,         //Optional: Substitute ingredients for that ingredient
    optional: null             //Whether ingredient is necessary
  }

var testIngredient2 = {
    changed: true,
    name: 'wild mushrooms',
    type: null,
    position: 2,
    amount: 500,
    unit: 'g',
    prep: 'cleaned',
    substitutes: null,
    optional: null
  }

var testIngredient3 = {
  changed: true,
  name: 'puff pastry',
  type: null,
  position: 3,
  amount: 500,
  unit: 'g',
  prep: null,
  substitutes: null,
  optional: null
}

var testIngredient4 = {
  changed: true,
  name: 'egg yolks',
  type: null,
  position: 4,
  amount: 2,
  unit: 'whole',
  prep: 'beaten with a pinch of salt',
  substitutes: null,
  optional: null
}

var testIngredient5 = {
  changed: true,
  name: 'shallots',
  type: null,
  position: 5,
  amount: 4,
  unit: 'whole',
  prep: 'peeled and sliced',
  substitutes: null,
  optional: null
}

var testIngredient6 = {
  changed: true,
  name: 'bottle red wine',
  type: null,
  position: 6,
  amount: 1,
  unit: 'whole',
  prep: 'not for drinking',
  substitutes: null,
  optional: null
}

var wellingtonIngredients = [testIngredient1, testIngredient2, testIngredient3, testIngredient4, testIngredient5, testIngredient6];

////////
// STEPS
//////

var testStep1 = {
  changed: true,
  position: 1,
  description: "Wrap each piece of beef tightly in a triple layer of cling film to set its shape, then chill overnight.",
  time: null,                 //OPTIONAL: Time to complete step
  ingredients: ['beef fillets']
}

var testStep2 = {
  changed: true,
  position: 2,
  description: "Remove the cling film, then quickly sear the beef fillets in a hot pan with a little olive oil for 30-60 seconds until browned all over and rare in the middle. Remove from the pan and leave to cool.",
  time: 1,                 //OPTIONAL: Time to complete step
  ingredients: ['olive oil', 'beef fillets']
}

var testStep3 = {
  changed: true,
  position: 3,
  description: "Finely chop the mushrooms and fry in a hot pan with a little olive oil, the thyme leaves and some seasoning. When the mushrooms begin to release their juices, continue to cook over a high heat for about 10 minutes until all the excess moisture has evaporated and you are left with a mushroom paste (known as a duxelle).",
  ingredients: ['wild mushrooms', 'olive oil','thyme leaves']
}

var testStep4 = {
  changed: true,
  position: 4,
  description: "Cut the pastry in half, place on a lightly floured surface and roll each piece into a rectangle large enough to envelop one of the beef fillets. Chill in the refrigerator.",
  ingredients: ['puff pastry']
}

var testStep5 = {
  changed: true,
  position: 5,
  description: "Season the beef fillets, then place them on top of the mushroom-covered ham. Using the cling film, roll the Parma ham over the beef, then roll and tie the cling film to get a nice, evenly thick log. Repeat this step with the other beef fillet, then chill for at least 30 minutes.",
  ingredients: ['beef fillets', 'wild mushrooms', 'Parma ham']
}

var testStep6 = {
  changed: true,
  position: 6,
  description: "Prepare the red wine sauce. Heat the oil in a large pan, then fry the beef trimmings for a few minutes until browned on all sides. Stir in the shallots with the peppercorns, bay and thyme and continue to cook for about 5 minutes, stirring frequently, until the shallots turn golden brown.",
  ingredients: ['bottle red wine', 'beef trimmings', 'shallots', 'peppercorns']
}

var wellingtonRecipe = {
  name: {
    changed: true,
    value: 'Beef Wellington'
  },
  picture: {
    changed: true,
    value: "https://gordonramsay-2938.kxcdn.com/assets/Recipes/_resampled/CroppedFocusedImage108081050-50-APPROVED-Gordons-Wellington2.jpg"
  },
  description: {
      changed: true,
      value: "Beef Wellington is a preparation of filet steak coated with pâté (often pâté de foie gras) and duxelles, which is then wrapped in puff pastry and baked. Some recipes include wrapping the coated meat in a crêpe to retain the moisture and prevent it from making the pastry soggy."
  },
  servings: {
    changed: true,
    value: 'Serves 4 to 6'
  },
  cookTime: {
    changed: true,
    value: 120  //Cook time in minutes
  },
  skillLevel: {                             //Recipe difficulty [easy, medium, hard]
    changed: true,
    value: 'Scrum Master'
  },
  dependencies: [],
  ingredients: wellingtonIngredients,
  steps: [testStep1, testStep2, testStep3, testStep4, testStep5, testStep6],
  tags: [],
  issues: []
};

module.exports = wellingtonRecipe; <|endoftext|>


<commit_before>import reload from '@/util/wechatShareForIOS.js'
import directives from '@/directives'

export default {
  data () {
    return {
      scrollable: true,
      windowScrollTop: 0,
      isCurrentView: false,
    }
  },
  directives,
  computed: {
    currentUser () {
      return this.$store.state.CURRENTUSER || {}
    },
    currencyUnit () {
      return this.$store.state.currency.unit
    },
    isIosWechat () {
      const ua = navigator.userAgent
      const wechatUA = ua.toLowerCase().match(/MicroMessenger/i)
      const isIos = ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
      const isWechat =
        wechatUA !== null && wechatUA.toString() === 'micromessenger'
      return isIos && isWechat && this.$route.query.jxytime === undefined
    },
  },
  watch: {
    scrollable (val) {
      const el = document.scrollingElement
      if (val) {
        document.body.style.top = ''
        document.body.classList.remove('m-pop-open')
        el && (el.scrollTop = this.windowScrollTop)
      } else {
        document.body.classList.add('m-pop-open')
        this.windowScrollTop = el ? el.scrollTop : 0
        document.body.style.top = -this.windowScrollTop + 'px'
      }
    },
  },
  methods: {
    goBack () {
      const fallIndex = this.isIosWechat ? 2 : 1
      window.history.length <= fallIndex
        ? this.$router.replace('/')
        : this.$router.back()
    },
    /**
     * 定位到锚点
     * @param {string} selector
     */
    goAnchor (selector) {
      const anchor = this.$el.querySelector(selector)
      try {
        const rect = anchor.getBoundingClientRect()
        const scrollTop = document.documentElement.scrollTop
        document.scrollingElement.scrollTop = rect.top + scrollTop
      } catch (error) {
        // eslint-disable-next-line no-console
        console.warn('锚点定位失败: ', { selector, anchor, error })
      }
    },
    reload: reload,
    popupBuyTS () {
      this.$bus.$emit('popupDialog', {
        title: this.$t('tips'),
        content: this.$t('popup_buy_ts'),
      })
    },
  },
}
<commit_msg>fix(SPA): IOS 下分享出去有时不正确的问题<commit_after>import reload from '@/util/wechatShareForIOS.js'
import directives from '@/directives'

export default {
  data () {
    return {
      scrollable: true,
      windowScrollTop: 0,
      isCurrentView: false,
    }
  },
  directives,
  computed: {
    currentUser () {
      return this.$store.state.CURRENTUSER || {}
    },
    currencyUnit () {
      return this.$store.state.currency.unit
    },
    isIosWechat () {
      const ua = navigator.userAgent
      const wechatUA = ua.toLowerCase().match(/MicroMessenger/i)
      const isIos = ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
      const isWechat =
        wechatUA !== null && wechatUA.toString() === 'micromessenger'
      return isIos && isWechat
      // && this.$route.query.jxytime === undefined
    },
  },
  watch: {
    scrollable (val) {
      const el = document.scrollingElement
      if (val) {
        document.body.style.top = ''
        document.body.classList.remove('m-pop-open')
        el && (el.scrollTop = this.windowScrollTop)
      } else {
        document.body.classList.add('m-pop-open')
        this.windowScrollTop = el ? el.scrollTop : 0
        document.body.style.top = -this.windowScrollTop + 'px'
      }
    },
  },
  methods: {
    goBack () {
      const fallIndex = this.isIosWechat ? 2 : 1
      window.history.length <= fallIndex
        ? this.$router.replace('/')
        : this.$router.back()
    },
    /**
     * 定位到锚点
     * @param {string} selector
     */
    goAnchor (selector) {
      const anchor = this.$el.querySelector(selector)
      try {
        const rect = anchor.getBoundingClientRect()
        const scrollTop = document.documentElement.scrollTop
        document.scrollingElement.scrollTop = rect.top + scrollTop
      } catch (error) {
        // eslint-disable-next-line no-console
        console.warn('锚点定位失败: ', { selector, anchor, error })
      }
    },
    reload: reload,
    popupBuyTS () {
      this.$bus.$emit('popupDialog', {
        title: this.$t('tips'),
        content: this.$t('popup_buy_ts'),
      })
    },
  },
}
<|endoftext|>


<commit_before>import React    from 'react';
import { Link } from 'react-router-dom';

const HomePage = () => (

Atomic React Components

Welcome to Compounds SDK! This SDK is mean to be an
            Open Source, Accessible (a11y), Unified Brand that
            is International Ready (i18n, l10n).

React Components:

<Link className="link_homepage" to={`buttons`}>Buttons</Link>

<Link className="link_homepage" to={`icons`}>Icons</Link>

<Link className="link_homepage" to={`inputs`}>Inputs</Link>

Contributions: FAQ

Pearson Elements SDK: http://pearson-higher-ed.github.io/elements/

Design Site: http://pearson-higher-ed.github.io/design/

Unit Test Coverage: http://localhost:8081/coverage/lcov-report/

HipChat Room: PDA-Help

Email: pearson-design-accelerator@pearson.com

      )

export default HomePage;
<commit_msg>fix: correction on the homepage<commit_after>import React    from 'react';
import { Link } from 'react-router-dom';

const HomePage = () => (

Atomic React Components

Welcome to Compounds SDK! This SDK is mean to be an
            Open Source, Accessible (a11y), Unified Brand that
            is International Ready (i18n, l10n).

React Components:

<Link className="link_homepage" to={`buttons`}>Buttons</Link>

<Link className="link_homepage" to={`icons`}>Icons</Link>

<Link className="link_homepage" to={`inputs`}>Inputs</Link>

Contributions: FAQ

Pearson Elements SDK: http://pearson-higher-ed.github.io/elements/

Design Site: http://pearson-higher-ed.github.io/design/

Unit Test Coverage: https://pearson-higher-ed.github.io/compounds/coverage/lcov-report/

HipChat Room: PDA-Help

Email: pearson-design-accelerator@pearson.com

      )

export default HomePage;
<|endoftext|>


<commit_before>exports.conf = {
  enabled: true,
  spamProtection: false,
  priority: 7,
};

exports.run = (client, msg, cmd) => {
  let missing = [];
  if (msg.channel.type === "text") {
    missing = msg.channel.permissionsFor(client.user).missing(cmd.conf.botPerms);
  } else {
    const impliedPermissions = client.funcs.impliedPermissions();
    cmd.conf.botPerms.forEach((perm) => {
      if (!impliedPermissions[perm]) { missing.push(perm); }
    });
  }
  if (missing.length > 0) {
    const embed = new client.methods.Embed()
    .setColor("#FF0000")
    .setTimestamp()
    .setTitle("❌ ERROR: MISSING PERMISSIONS! ❌")
    .setDescription("I do not have the correct permission level for this command!")
    .addField("Missing permissions:", `**${client.funcs.toTitleCase(missing.join(", ").split("_").join(" "))}**`)
    return msg.channel.send({embed});
  }
  return false;
};
<commit_msg>Delete missingBotPermissions.js<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*jslint sub: true */
/**
 * @description The storage service implementation
 * @constructor
 * @param {Object} config The configuration describing the characteristics of the storage to be created.
 */
var AuraStorage = function AuraStorage(config) {
    this.name = config["name"];
    this.adapter = config["adapter"];
    this.maxSize = config["maxSize"];
    this.defaultExpiration = config["defaultExpiration"] * 1000;
    this.defaultAutoRefreshInterval = config["defaultAutoRefreshInterval"] * 1000;
    this.debugLoggingEnabled = config["debugLoggingEnabled"];
    this.lastSweep = new Date().getTime();
    this.setVersion(config["version"]);

    var clearStorageOnInit = config["clearStorageOnInit"];

    this.log("initializing storage adapter using { name: \"" + config["name"] + "\", implementation: \""
        + this.adapter.getName() + "\", maxSize: " + this.maxSize + ", defaultExpiration: " + this.defaultExpiration
        + ", defaultAutoRefreshInterval: " + this.defaultAutoRefreshInterval + ", clearStorageOnInit: " + clearStorageOnInit + ", debugLoggingEnabled: " + this.debugLoggingEnabled + " }");

    if (clearStorageOnInit === true) {
        this.log("clearing " + this.getName() + " storage on init");
        this.adapter.clear();
    }

    // work around the obfuscation logic to allow external Adapters to properly plug in
    this.adapter.clear = this.adapter.clear || this.adapter["clear"];
    this.adapter.getExpired = this.adapter.getExpired || this.adapter["getExpired"];
    this.adapter.getItem = this.adapter.getItem || this.adapter["getItem"];
    this.adapter.getName = this.adapter.getName || this.adapter["getName"];
    this.adapter.getSize = this.adapter.getSize || this.adapter["getSize"];
    this.adapter.removeItem = this.adapter.removeItem || this.adapter["removeItem"];
    this.adapter.setItem = this.adapter.setItem || this.adapter["setItem"];
    this.adapter.getAll = this.adapter.getAll || this.adapter["getAll"];

    var adapterConfig = $A.storageService.getAdapterConfig(this.adapter.getName());
    this.persistent = !$A.util.isUndefinedOrNull(adapterConfig["persistent"]) && adapterConfig["persistent"];
    this.secure = !$A.util.isUndefinedOrNull(adapterConfig["secure"]) && adapterConfig["secure"];

    //#if {"excludeModes" : ["PRODUCTION", "PRODUCTIONDEBUG"]}
    this.adapter["getItem"] = this.adapter.getItem;
    this["adapter"] = this.adapter;
    //#end
};

/**
 * Returns the name of the storage type. For example, "smartStore", "websql", or "memory".
 * @returns {String} The storage type.
 */
AuraStorage.prototype.getName = function() {
    return this.adapter.getName();
};

/**
 * Asynchronously gets the current storage size in KB.
 * @returns {Promise} A Promise that will get the current storage size in KB.
 */
AuraStorage.prototype.getSize = function() {
    return this.adapter.getSize()
        .then(function(size) { return size / 1024.0; } );
};

/**
 * Returns the maximum storage size in KB.
 * @returns {number} The maximum storage size in KB.
 */
AuraStorage.prototype.getMaxSize = function() {
    return this.maxSize / 1024.0;
};

/**
 * Returns the default auto-refresh interval in seconds.
 * @returns {number} The default auto-refresh interval.
 */
AuraStorage.prototype.getDefaultAutoRefreshInterval = function() {
    return this.defaultAutoRefreshInterval;
};

/**
 * Returns a promise that clears the storage.
 * @returns {Promise} A Promise that will clear storage.
 */
AuraStorage.prototype.clear = function() {
    return this.adapter.clear();
};

/**
 * Asynchronously gets an item from storage corresponding to the specified key.
 * @param {String} key The item key. This is the key used when the item was added to storage using put().
 * @returns {Promise} A Promise that will fetch an item from storage.
 */
AuraStorage.prototype.get = function(key) {
    // This needs to also be asynchronous to map to IndexedDB, WebSQL, SmartStore that are all async worlds
    var that = this;
    var promise = this.adapter.getItem(this.version + key).then(function(item) {

        that.log("get() - key: " + key + ", item: " + item);

        if (!item) {
            return undefined;
        }

        return { "value" : item.value, "isExpired" : (new Date().getTime() > item.expires) };
    });

    this.sweep();

    return promise;
};

/**
 * Asynchronously gets all items from storage
 * @returns {Promise} A Promise that will fetch all items from storage.
 */
AuraStorage.prototype.getAll = function() {
    var that = this;
    return this.adapter.getAll().then(function(items) {
        that.log("getAll() - found " + items.length + " items");
        return $A.util.map(items, function(item) {
            var realKey = item["key"],
                key = realKey;
            if (realKey.indexOf(that.version) === 0) {
                // in case version string is part of the actual key
                // then only replace first occurrence
                key = item["key"].replace(that.version, "");
            }
            return { "key": key, "value": item["value"], "isExpired": (new Date().getTime() > item.expires) };
        });
    });
};

/**
 * Asynchronously stores the value in storage using the specified key.
 * @param {String} key The key of the item to store.
 * @param {Object} value The value of the item to store.
 * @returns {Promise} A Promise that will put the value in storage.
 */
AuraStorage.prototype.put = function(key, value) {
    var now = new Date().getTime();

    var item = {
        "value": value,
        "created": now,
        "expires": now + this.defaultExpiration
    };

    var that = this;
    var promise = this.adapter.setItem(this.version + key, item)
        .then(function () {
            that.log("put() - key: " + key + ", item: " + item);
            $A.storageService.fireModified();
        });

    this.sweep();

    return promise;
};

/**
 * @description Asynchronously removes the item indicated by key.
 * @param {String} key The key of the item to remove.
 * @param {Boolean} doNotFireModified A bool indicating whether or not to fire the modified event on item removal.
 * @returns {Promise} A Promise that will remove the item from storage.
 * @private
 */
AuraStorage.prototype.remove = function(key, doNotFireModified) {
    return this.adapter.removeItem(this.version + key)
        .then(function(){
            if (!doNotFireModified) {
                $A.storageService.fireModified();
            }
        });
};

/**
 * @description Asynchronously removes all expired items.
 * @private
 */
AuraStorage.prototype.sweep = function() {

    // Do not sweep if we have lost our connection, we'll ignore expiration until sweeping resumes
    // OR if we've recently swept
    if (this._sweepingSuspended || ((new Date().getTime() - this.lastSweep) < (this.defaultExpiration / 60))) {
        this.log("sweep() - skipping sweep");
        return;
    }

    var that = this;

    // Check simple expirations
    this.adapter.getExpired().then(function (expired) {

        if (expired.length === 0) {
            return;
        }

        var promiseSet = [];
        var key;
        for (var n = 0; n < expired.length; n++) {
            key = expired[n];
            that.log("sweep() - expiring item with key: " + key);
            promiseSet.push(that.remove(key, true));
        }

        // When all of the remove promises have completed...
        Promise.all(promiseSet).then(
            function () {
                that.log("sweep() - complete");
                that.lastSweep = new Date().getTime();
                $A.storageService.fireModified();
            },
            function (err) {
                that.log("Error while sweep() was removing items: " + err);
            }
        );
    });
};

/**
 * Suspends sweeping. The storage adapter is removed if it is expired but sweeping can be suspended if the
 * connection goes offline.
 */
AuraStorage.prototype.suspendSweeping = function() {
    this.log("suspendSweeping()");

    this._sweepingSuspended = true;
};

/**
 * Resumes sweeping to remove expired storage adapters.
 */
AuraStorage.prototype.resumeSweeping = function() {
    this.log("resumeSweeping()");

    this._sweepingSuspended = false;
    this.sweep();
};

/**
 * @private
 */
AuraStorage.prototype.log = function() {
    if (this.debugLoggingEnabled) {
        var msg = Array.prototype.join.call(arguments, " ");
        $A.log("AuraStorage '" + this.name + "' [" + this.getName() + "] : " + msg);
    }
};

/**
 * Whether current storage implementation is persistent
 * @returns {boolean} true if persistent
 */
AuraStorage.prototype.isPersistent = function() {
    return this.persistent;
};

/**
 * Whether current storage implementation is secure
 * @returns {boolean} true if secure
 */
AuraStorage.prototype.isSecure = function() {
    return this.secure;
};

/**
 * Sets the storage version. Cannot be set unless never set.
 */
AuraStorage.prototype.setVersion  = function(version) {
    // ensure string
    this.version = (version || "") + "";
};

/**
 * Returns the storage version.
 * @returns {String} storage version.
 */
AuraStorage.prototype.getVersion  = function() {
    return this.version;
};

//#include aura.storage.Storage_export
<commit_msg>Make Storage log lines explicit about HIT vs MISS<commit_after>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*jslint sub: true */
/**
 * @description The storage service implementation
 * @constructor
 * @param {Object} config The configuration describing the characteristics of the storage to be created.
 */
var AuraStorage = function AuraStorage(config) {
    this.name = config["name"];
    this.adapter = config["adapter"];
    this.maxSize = config["maxSize"];
    this.defaultExpiration = config["defaultExpiration"] * 1000;
    this.defaultAutoRefreshInterval = config["defaultAutoRefreshInterval"] * 1000;
    this.debugLoggingEnabled = config["debugLoggingEnabled"];
    this.lastSweep = new Date().getTime();
    this.setVersion(config["version"]);

    var clearStorageOnInit = config["clearStorageOnInit"];

    this.log("initializing storage adapter using { name: \"" + config["name"] + "\", implementation: \""
        + this.adapter.getName() + "\", maxSize: " + this.maxSize + ", defaultExpiration: " + this.defaultExpiration
        + ", defaultAutoRefreshInterval: " + this.defaultAutoRefreshInterval + ", clearStorageOnInit: " + clearStorageOnInit + ", debugLoggingEnabled: " + this.debugLoggingEnabled + " }");

    if (clearStorageOnInit === true) {
        this.log("clearing " + this.getName() + " storage on init");
        this.adapter.clear();
    }

    // work around the obfuscation logic to allow external Adapters to properly plug in
    this.adapter.clear = this.adapter.clear || this.adapter["clear"];
    this.adapter.getExpired = this.adapter.getExpired || this.adapter["getExpired"];
    this.adapter.getItem = this.adapter.getItem || this.adapter["getItem"];
    this.adapter.getName = this.adapter.getName || this.adapter["getName"];
    this.adapter.getSize = this.adapter.getSize || this.adapter["getSize"];
    this.adapter.removeItem = this.adapter.removeItem || this.adapter["removeItem"];
    this.adapter.setItem = this.adapter.setItem || this.adapter["setItem"];
    this.adapter.getAll = this.adapter.getAll || this.adapter["getAll"];

    var adapterConfig = $A.storageService.getAdapterConfig(this.adapter.getName());
    this.persistent = !$A.util.isUndefinedOrNull(adapterConfig["persistent"]) && adapterConfig["persistent"];
    this.secure = !$A.util.isUndefinedOrNull(adapterConfig["secure"]) && adapterConfig["secure"];

    //#if {"excludeModes" : ["PRODUCTION", "PRODUCTIONDEBUG"]}
    this.adapter["getItem"] = this.adapter.getItem;
    this["adapter"] = this.adapter;
    //#end
};

/**
 * Returns the name of the storage type. For example, "smartStore", "websql", or "memory".
 * @returns {String} The storage type.
 */
AuraStorage.prototype.getName = function() {
    return this.adapter.getName();
};

/**
 * Asynchronously gets the current storage size in KB.
 * @returns {Promise} A Promise that will get the current storage size in KB.
 */
AuraStorage.prototype.getSize = function() {
    return this.adapter.getSize()
        .then(function(size) { return size / 1024.0; } );
};

/**
 * Returns the maximum storage size in KB.
 * @returns {number} The maximum storage size in KB.
 */
AuraStorage.prototype.getMaxSize = function() {
    return this.maxSize / 1024.0;
};

/**
 * Returns the default auto-refresh interval in seconds.
 * @returns {number} The default auto-refresh interval.
 */
AuraStorage.prototype.getDefaultAutoRefreshInterval = function() {
    return this.defaultAutoRefreshInterval;
};

/**
 * Returns a promise that clears the storage.
 * @returns {Promise} A Promise that will clear storage.
 */
AuraStorage.prototype.clear = function() {
    return this.adapter.clear();
};

/**
 * Asynchronously gets an item from storage corresponding to the specified key.
 * @param {String} key The item key. This is the key used when the item was added to storage using put().
 * @returns {Promise} A Promise that will fetch an item from storage.
 */
AuraStorage.prototype.get = function(key) {
    // This needs to also be asynchronous to map to IndexedDB, WebSQL, SmartStore that are all async worlds
    var that = this;
    var promise = this.adapter.getItem(this.version + key).then(function(item) {
        var hit = item && (new Date().getTime() <= item["expires"]);
        that.log("get() " + (hit ? "HIT" : "MISS") + " - key: " + key + ", value: " + item);

        if (!item) {
            return undefined;
        }
        return { "value" : item.value, "isExpired" : !!hit };
    });

    this.sweep();

    return promise;
};

/**
 * Asynchronously gets all items from storage
 * @returns {Promise} A Promise that will fetch all items from storage.
 */
AuraStorage.prototype.getAll = function() {
    var that = this;
    return this.adapter.getAll().then(function(items) {
        that.log("getAll() - found " + items.length + " items");
        return $A.util.map(items, function(item) {
            var realKey = item["key"],
                key = realKey;
            if (realKey.indexOf(that.version) === 0) {
                // in case version string is part of the actual key
                // then only replace first occurrence
                key = item["key"].replace(that.version, "");
            }
            return { "key": key, "value": item["value"], "isExpired": (new Date().getTime() > item.expires) };
        });
    });
};

/**
 * Asynchronously stores the value in storage using the specified key.
 * @param {String} key The key of the item to store.
 * @param {Object} value The value of the item to store.
 * @returns {Promise} A Promise that will put the value in storage.
 */
AuraStorage.prototype.put = function(key, value) {
    var now = new Date().getTime();

    var item = {
        "value": value,
        "created": now,
        "expires": now + this.defaultExpiration
    };

    var that = this;
    var promise = this.adapter.setItem(this.version + key, item)
        .then(function () {
            that.log("put() - key: " + key + ", value: " + item);
            $A.storageService.fireModified();
        });

    this.sweep();

    return promise;
};

/**
 * @description Asynchronously removes the item indicated by key.
 * @param {String} key The key of the item to remove.
 * @param {Boolean} doNotFireModified A bool indicating whether or not to fire the modified event on item removal.
 * @returns {Promise} A Promise that will remove the item from storage.
 * @private
 */
AuraStorage.prototype.remove = function(key, doNotFireModified) {
    return this.adapter.removeItem(this.version + key)
        .then(function(){
            if (!doNotFireModified) {
                $A.storageService.fireModified();
            }
        });
};

/**
 * @description Asynchronously removes all expired items.
 * @private
 */
AuraStorage.prototype.sweep = function() {

    // Do not sweep if we have lost our connection, we'll ignore expiration until sweeping resumes
    // OR if we've recently swept
    if (this._sweepingSuspended || ((new Date().getTime() - this.lastSweep) < (this.defaultExpiration / 60))) {
        this.log("sweep() - skipping sweep");
        return;
    }

    var that = this;

    // Check simple expirations
    this.adapter.getExpired().then(function (expired) {

        if (expired.length === 0) {
            return;
        }

        var promiseSet = [];
        var key;
        for (var n = 0; n < expired.length; n++) {
            key = expired[n];
            that.log("sweep() - expiring item with key: " + key);
            promiseSet.push(that.remove(key, true));
        }

        // When all of the remove promises have completed...
        Promise.all(promiseSet).then(
            function () {
                that.log("sweep() - complete");
                that.lastSweep = new Date().getTime();
                $A.storageService.fireModified();
            },
            function (err) {
                that.log("Error while sweep() was removing items: " + err);
            }
        );
    });
};

/**
 * Suspends sweeping. The storage adapter is removed if it is expired but sweeping can be suspended if the
 * connection goes offline.
 */
AuraStorage.prototype.suspendSweeping = function() {
    this.log("suspendSweeping()");

    this._sweepingSuspended = true;
};

/**
 * Resumes sweeping to remove expired storage adapters.
 */
AuraStorage.prototype.resumeSweeping = function() {
    this.log("resumeSweeping()");

    this._sweepingSuspended = false;
    this.sweep();
};

/**
 * @private
 */
AuraStorage.prototype.log = function() {
    if (this.debugLoggingEnabled) {
        var msg = Array.prototype.join.call(arguments, " ");
        $A.log("AuraStorage '" + this.name + "' [" + this.getName() + "] : " + msg);
    }
};

/**
 * Whether current storage implementation is persistent
 * @returns {boolean} true if persistent
 */
AuraStorage.prototype.isPersistent = function() {
    return this.persistent;
};

/**
 * Whether current storage implementation is secure
 * @returns {boolean} true if secure
 */
AuraStorage.prototype.isSecure = function() {
    return this.secure;
};

/**
 * Sets the storage version. Cannot be set unless never set.
 */
AuraStorage.prototype.setVersion  = function(version) {
    // ensure string
    this.version = (version || "") + "";
};

/**
 * Returns the storage version.
 * @returns {String} storage version.
 */
AuraStorage.prototype.getVersion  = function() {
    return this.version;
};

//#include aura.storage.Storage_export
<|endoftext|>


<commit_before>'use strict';

const expect = require('chai').expect;
const fs = require('fs-extra');

describe('Main Installer', function () {
  it('should copy conf.yml to the root directory', function () {
    expect(fs.existsSync('conf.yml')).to.equal(true);
  });

  it('should copy patternlab-config.json to the root directory', function () {
    expect(fs.existsSync('patternlab-config.json')).to.equal(true);
  });

  it('should copy pref.yml to the root directory', function () {
    expect(fs.existsSync('pref.yml')).to.equal(true);
  });

  it('should copy source to the root directory', function () {
    expect(fs.existsSync('source')).to.equal(true);
  });

  it('should copy extend to the root directory', function () {
    expect(fs.existsSync('extend')).to.equal(true);
  });

  it('should install npms in the extend directory', function () {
    expect(fs.existsSync('extend/node_modules')).to.equal(true);
  });

  it('should install npms in the public directory', function () {
    expect(fs.existsSync('public/node_modules')).to.equal(true);
  });

  it('should compile styleguide.html to public/node_modules/fepper-ui/', function () {
    expect(fs.existsSync('public/node_modules/fepper-ui/styleguide.html')).to.equal(true);
  });
});
<commit_msg>updating wording of unit tests to make them extensible to other implementations<commit_after>'use strict';

const expect = require('chai').expect;
const fs = require('fs-extra');

describe('Main Installer', function () {
  it('should copy conf.yml to the root directory', function () {
    expect(fs.existsSync('conf.yml')).to.equal(true);
  });

  it('should copy patternlab-config.json to the root directory', function () {
    expect(fs.existsSync('patternlab-config.json')).to.equal(true);
  });

  it('should complete with pref.yml in the root directory', function () {
    expect(fs.existsSync('pref.yml')).to.equal(true);
  });

  it('should complete with source in the root directory', function () {
    expect(fs.existsSync('source')).to.equal(true);
  });

  it('should copy extend to the root directory', function () {
    expect(fs.existsSync('extend')).to.equal(true);
  });

  it('should install npms in the extend directory', function () {
    expect(fs.existsSync('extend/node_modules')).to.equal(true);
  });

  it('should install npms in the public directory', function () {
    expect(fs.existsSync('public/node_modules')).to.equal(true);
  });

  it('should compile styleguide.html to public/node_modules/fepper-ui/', function () {
    expect(fs.existsSync('public/node_modules/fepper-ui/styleguide.html')).to.equal(true);
  });
});
<|endoftext|>


<commit_before>'use strict';

/* App Module */

var phonecatApp = angular.module('phonecatApp', [
  'ngRoute',
  'phonecatAnimations',

  'phonecatControllers',
  'phonecatFilters',
  'phonecatServices'
]);

phonecatApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/phones', {
        templateUrl: 'partials/phone-list.html',
        controller: 'PhoneListCtrl'
      }).
      when('/phones/:phoneId', {
        templateUrl: 'partials/phone-detail.html',
        controller: 'PhoneDetailCtrl'
      }).
      when('/modification', {
          templateUrl: 'partials/modification.html',
          controller: 'PhoneDetailCtrl'
      }).
      otherwise({
        redirectTo: '/phones'
      });
  }]);
<commit_msg>test cgt commentaire<commit_after>'use strict';

/* un truc */

var phonecatApp = angular.module('phonecatApp', [
  'ngRoute',
  'phonecatAnimations',

  'phonecatControllers',
  'phonecatFilters',
  'phonecatServices'
]);

phonecatApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/phones', {
        templateUrl: 'partials/phone-list.html',
        controller: 'PhoneListCtrl'
      }).
      when('/phones/:phoneId', {
        templateUrl: 'partials/phone-detail.html',
        controller: 'PhoneDetailCtrl'
      }).
      when('/modification', {
          templateUrl: 'partials/modification.html',
          controller: 'PhoneDetailCtrl'
      }).
      otherwise({
        redirectTo: '/phones'
      });
  }]);
<|endoftext|>


<commit_before>/* jshint node: true, esnext: true */

const elasticsearch = require('elasticsearch');
const http = require('http');
const url = require('url');
const htmlEncode = require('js-htmlencode');

const server_port = 9615;

var client = new elasticsearch.Client({
  host: 'localhost:9201',
  log: 'trace'
});

function query(q, page, page_size) {
  var body = {
      "query": {
          "query_string": {
              "query": q,
              "default_operator": "AND"
          }
      },
      "highlight": {
          "order" : "score",
          "require_field_match": false,
          "encoder": "html",
          "fields": {
              "*": {
                  "number_of_fragments" : 1
              }
          }
      },
      "_source": [
        "metadata.title", "metadata.name", "metadata.description",
        "references"
      ]
  };

  return client.search({
    index: 'ipfs',
    body: body,
    size: page_size,
    from: page*page_size
  });
}

function error_response(response, code, error) {
  console.trace(code+": "+error.message);

  response.writeHead(code, {"Content-Type": "application/json"});
  response.write(JSON.stringify({
    "error": error
  }));
  response.end();
}

function get_title(result) {
  // Get title from result

  // Highlights take preference
  var hl = result.highlight;

  if (hl) {
    const highlight_priority = [
      "metadata.title", "references.name"
    ];

    // Return the first one from the priority list
    for (var i=0; i<highlight_priority.length; i++) {
      if (hl[highlight_priority[i]]) {
        return hl[highlight_priority[i]][0];
      }
    }
  }

  // Try metadata
  var src = result._source;
  var titles = [];

  if ("metadata" in src) {
    const metadata_priority = [
      "title", "name"
    ];

    metadata_priority.forEach(function (item) {
      if (src.metadata[item]) {
        titles.push(src.metadata[item][0]);
      }
    });
  }

  // Try references
  src.references.forEach(function (item) {
    if (item.name) {
      titles.push(item.name[0]);
    }
  });

  // Pick longest title
  if (titles.length > 0) {
    titles.sort(function (a, b) { return b.length - a.length; });

    return htmlEncode.htmlEncode(titles[0]);
  } else {
    // Fallback to id
    return htmlEncode.htmlEncode(result._id);
  }
}

function get_description(result) {
  // Use highlights, if available
  if (result.highlight) {
    if (result.highlight.content) {
      return result.highlight.content[0];
    }

    if (result.highlight["links.Name"]) {
      // Reference name matching
      return "Links to “"+result.highlight["links.Name"][0]+"”";
    }

    if (result.highlight["links.Hash"]) {
      // Reference name matching
      return "Links to “"+result.highlight["links.Hash"][0]+"”";
    }
  }

  var metadata = result._source.metadata;
  if (metadata) {
    // Description, if available
    if (metadata.description) {
      return htmlEncode.htmlEncode(metadata.description[0]);
    }

  }

  // Default to nothing
  return null;
}

function transform_results(results) {
  var hits = [];

  results.hits.forEach(function (item) {
    hits.push({
      "hash": item._id,
      "title": get_title(item),
      "description": get_description(item),
      "type": item._type
    });
  });

  // Overwrite existing list of hits
  results.hits = hits;
}

console.info("Starting server on http://localhost:"+server_port+"/");

http.createServer(function(request, response) {
  const page_size = 15;
  var parsed_url;

  try {
    console.log(request.url);

    try {
      parsed_url = url.parse(request.url, true);
    } catch(err) {
      error_response(response, 400, err.message);
    }

    if (parsed_url.pathname === "/search") {
      if (!"q" in parsed_url.query) {
        error_response(response, 422, "query argument missing");
      }

      var page = 0;
      const max_page = 100;

      if ("page" in parsed_url.query) {
        page = parseInt(parsed_url.query.page, 10);

        // For performance reasons, don't allow paging too far down
        if (page > 100) {
          error_response(422, "paging not allowed beyond 100");
        }
      }

      query(parsed_url.query.q, page, page_size).then(function (body) {
        console.info("200: Returning "+body.hits.hits.length+" results");

        transform_results(body.hits);

        response.writeHead(200, {"Content-Type": "application/json"});
        response.write(JSON.stringify(body.hits));
        response.end();
      }, function (error) {
        throw(error);
      });

    } else {
        error_response(response, 404, "file not found");
    }

  } catch(err) {
    // Catch generic errors
    error_response(response, 500, err.message);
  } finally {

  }
}).listen(server_port);

<commit_msg>Proper port for API.<commit_after>/* jshint node: true, esnext: true */

const elasticsearch = require('elasticsearch');
const http = require('http');
const url = require('url');
const htmlEncode = require('js-htmlencode');

const server_port = 9615;

var client = new elasticsearch.Client({
  host: 'localhost:9200',
  log: 'trace'
});

function query(q, page, page_size) {
  var body = {
      "query": {
          "query_string": {
              "query": q,
              "default_operator": "AND"
          }
      },
      "highlight": {
          "order" : "score",
          "require_field_match": false,
          "encoder": "html",
          "fields": {
              "*": {
                  "number_of_fragments" : 1
              }
          }
      },
      "_source": [
        "metadata.title", "metadata.name", "metadata.description",
        "references"
      ]
  };

  return client.search({
    index: 'ipfs',
    body: body,
    size: page_size,
    from: page*page_size
  });
}

function error_response(response, code, error) {
  console.trace(code+": "+error.message);

  response.writeHead(code, {"Content-Type": "application/json"});
  response.write(JSON.stringify({
    "error": error
  }));
  response.end();
}

function get_title(result) {
  // Get title from result

  // Highlights take preference
  var hl = result.highlight;

  if (hl) {
    const highlight_priority = [
      "metadata.title", "references.name"
    ];

    // Return the first one from the priority list
    for (var i=0; i<highlight_priority.length; i++) {
      if (hl[highlight_priority[i]]) {
        return hl[highlight_priority[i]][0];
      }
    }
  }

  // Try metadata
  var src = result._source;
  var titles = [];

  if ("metadata" in src) {
    const metadata_priority = [
      "title", "name"
    ];

    metadata_priority.forEach(function (item) {
      if (src.metadata[item]) {
        titles.push(src.metadata[item][0]);
      }
    });
  }

  // Try references
  src.references.forEach(function (item) {
    if (item.name) {
      titles.push(item.name[0]);
    }
  });

  // Pick longest title
  if (titles.length > 0) {
    titles.sort(function (a, b) { return b.length - a.length; });

    return htmlEncode.htmlEncode(titles[0]);
  } else {
    // Fallback to id
    return htmlEncode.htmlEncode(result._id);
  }
}

function get_description(result) {
  // Use highlights, if available
  if (result.highlight) {
    if (result.highlight.content) {
      return result.highlight.content[0];
    }

    if (result.highlight["links.Name"]) {
      // Reference name matching
      return "Links to “"+result.highlight["links.Name"][0]+"”";
    }

    if (result.highlight["links.Hash"]) {
      // Reference name matching
      return "Links to “"+result.highlight["links.Hash"][0]+"”";
    }
  }

  var metadata = result._source.metadata;
  if (metadata) {
    // Description, if available
    if (metadata.description) {
      return htmlEncode.htmlEncode(metadata.description[0]);
    }

  }

  // Default to nothing
  return null;
}

function transform_results(results) {
  var hits = [];

  results.hits.forEach(function (item) {
    hits.push({
      "hash": item._id,
      "title": get_title(item),
      "description": get_description(item),
      "type": item._type
    });
  });

  // Overwrite existing list of hits
  results.hits = hits;
}

console.info("Starting server on http://localhost:"+server_port+"/");

http.createServer(function(request, response) {
  const page_size = 15;
  var parsed_url;

  try {
    console.log(request.url);

    try {
      parsed_url = url.parse(request.url, true);
    } catch(err) {
      error_response(response, 400, err.message);
    }

    if (parsed_url.pathname === "/search") {
      if (!"q" in parsed_url.query) {
        error_response(response, 422, "query argument missing");
      }

      var page = 0;
      const max_page = 100;

      if ("page" in parsed_url.query) {
        page = parseInt(parsed_url.query.page, 10);

        // For performance reasons, don't allow paging too far down
        if (page > 100) {
          error_response(422, "paging not allowed beyond 100");
        }
      }

      query(parsed_url.query.q, page, page_size).then(function (body) {
        console.info("200: Returning "+body.hits.hits.length+" results");

        transform_results(body.hits);

        response.writeHead(200, {"Content-Type": "application/json"});
        response.write(JSON.stringify(body.hits));
        response.end();
      }, function (error) {
        throw(error);
      });

    } else {
        error_response(response, 404, "file not found");
    }

  } catch(err) {
    // Catch generic errors
    error_response(response, 500, err.message);
  } finally {

  }
}).listen(server_port);

<|endoftext|>