<commit_before>/* ************************************************************************

   qooxdoo - the new era of web development

   http://qooxdoo.org

   Copyright:
     2017 Christian Boulanger

   License:
     MIT: https://opensource.org/licenses/MIT
     See the LICENSE file in the project's top-level directory for details.

   Authors:
     * Christian Boulanger (info@bibliograph.org, @cboulanger)

************************************************************************ */
require("../Contrib");

require("qooxdoo");
const fs = require("fs");
const process = require("process");
const octokit = require("@octokit/rest")();
const semver = require("semver");
const inquirer = require("inquirer");

/**
 * Publishes a release on GitHub
 */
qx.Class.define("qx.tool.cli.commands.contrib.Publish", {
  extend: qx.tool.cli.commands.Contrib,

  statics: {
    getYargsCommand: function() {
      return {
        command: "publish",
        describe: "publishes a new release of the contrib on GitHub. Requires a GitHub access token. By default, makes a patch release.",
        builder: {
          "type": {
            alias : "t",
            describe: "Set the release type",
            nargs: 1,
            requiresArg: true,
            choices: "major,premajor,minor,preminor,patch,prepatch,prerelease".split(/,/),
            type: "string",
            default : "patch"
          },
          "noninteractive":{
            alias: "I",
            describe: "Do not prompt user"
          },
          "version": {
            alias: "V",
            describe: "Use given version number"
          },
          "quiet": {
            alias: "q",
            describe: "No output"
          },
          "message":{
            alias: "m",
            describe: "Set commit/release message"
          },
          "dryrun":{
            describe: "Show result only, do not publish to GitHub"
          },
          "verbose": {
            alias: "v",
            describe: "Verbose logging"
          },
          "force": {
            alias: "f",
            describe: "overrun demo check"
          }
        },
        handler: function(argv) {
          return new qx.tool.cli.commands.contrib.Publish(argv)
            .process()
            .catch(e => {
              console.error(e.stack || e.message);
              process.exit(1);
            });
        }
      };
    }
  },

  members: {

    /**
     * Publishes a new release of the contrib on GitHub, by executing the following steps:
     *
     * 1. In Manifest.json, update the qooxdoo-range value to include the version of the qooxdoo
     *    framework (As per version.txt).
     * 2. In Manifest.json, based the given options, increment the version number (patch,
     *    feature, breaking).
     * 3. Create a release with the tag vX.Y.Z according to the current version.
     * 4. Add "qooxdoo-contrib" to the list of GitHub topics.
     *
     */
    process: async function() {
      // init
      const argv = this.argv;

      // qooxdoo version
      let qooxdoo_version = await this.getUserQxVersion();
      if (argv.verbose) {
        console.log(`>>> qooxdoo version:  ${qooxdoo_version}`);
      }

      // check git status
      let status = await this.exec("git status --porcelain");
      if (status.trim() !=="") {
        throw new qx.tool.cli.Utils.UserError("Please commit or stash all remaining changes first.");
      }
      status = await this.exec("git status --porcelain --branch");
      if (status.includes("ahead")) {
        throw new qx.tool.cli.Utils.UserError("Please push all local commits to GitHub first.");
      }

      // token
      let cfg = await qx.tool.cli.ConfigDb.getInstance();
      let github = cfg.db("github", {});
      if (!github.token) {
        let response = await inquirer.prompt([
          {
            type: "input",
            name: "token",
            message: "Publishing to GitHub requires an API token - visit https://github.com/settings/tokens to obtain one " +
                "(you must assign permission to publish);\nWhat is your GitHub API Token ? "
          }
        ]
        );
        if (!response.token) {
          console.error("You have not provided a GitHub token.");
          return;
        }
        github.token = response.token;
        cfg.save();
      }
      let token = github.token;
      if (!token) {
        throw new qx.tool.cli.Utils.UserError(`GitHub access token required.`);
      }
      octokit.authenticate({
        type: "token",
        token
      });

      // read Manifest.json
      let manifest_path = process.cwd() + "/Manifest.json";
      if (!fs.existsSync(manifest_path)) {
        throw new qx.tool.cli.Utils.UserError("Cannot find Manifest.json - are you in the project directory?");
      }
      let manifest = qx.tool.compiler.utils.Json.parseJson(fs.readFileSync(manifest_path, "utf-8"));

      // prevent accidental publication of demo manifest.
      if (!argv.force && manifest.provides.namespace.includes(".demo")) {
        throw new qx.tool.cli.Utils.UserError("This seems to be the contrib demo. Please go into the library directory to publish the library.");
      }

      // version
      let new_version;
      if (argv.version) {
        // use user-supplied value
        new_version = argv.version;
        if (!semver.valid(new_version)) {
          throw new qx.tool.cli.Utils.UserError(`${new_version} is not a valid version number.`);
        }
      } else {
        // use version number from manifest and increment it
        let old_version = manifest.info.version;
        if (!semver.valid(old_version)) {
          throw new qx.tool.cli.Utils.UserError("Invalid version number in Manifest. Must be a valid semver version (x.y.z).");
        }
        new_version = semver.inc(old_version, argv.type);
      }

      // tag and repo name
      let tag = `v${new_version}`;
      let url;
      try {
        url = (await this.exec("git config --get remote.origin.url")).trim();
      } catch (e) {
        throw new qx.tool.cli.Utils.UserError("Cannot determine remote repository.");
      }
      let repo_name = url.replace(/(https:\/\/github.com\/|git@github.com:)/, "").replace(/\.git/, "");
      let [owner, repo] = repo_name.split(/\//);
      if (argv.verbose) {
        console.log(`>>> Repository:  ${repo_name}`);
      }
      let repoExists = false;
      try {
        repoExists = true;
      } catch (e) {}
      if (repoExists) {
        throw new qx.tool.cli.Utils.UserError(`A release with tag '${tag} already exists.'`);
      }

      // get topics, this will also check credentials
      let result;
      let topics;
      try {
        result = await octokit.repos.listTopics({owner, repo});
        topics = result.data.names;
      } catch (e) {
        if (e.message.includes("Bad credentials")) {
          throw new qx.tool.cli.Utils.UserError(`Your token is invalid.`);
        }
        throw e;
      }

      // prompt user to confirm
      let doRelease = true;
      if (!argv.noninteractive) {
        let question = {
          type: "confirm",
          name: "doRelease",
          message: `This will ${argv.version?"set":"increment"} the version to ${new_version} and create a release of the current master on GitHub. Do you want to proceed?`,
          default: "y"
        };
        let answer = await inquirer.prompt(question);
        doRelease = answer.doRelease;
      }
      if (!doRelease) {
        process.exit(0);
      }

      // update Manifest.json
      manifest.info.version = new_version;
      // qooxdoo-versions @deprecated
      let qooxdoo_versions = manifest.info["qooxdoo-versions"];
      if (qooxdoo_versions instanceof Array) {
        if (!qooxdoo_versions.includes(qooxdoo_version)) {
          manifest.info["qooxdoo-versions"].push(qooxdoo_version);
        }
      }
      // qooxdoo-range @deprecated
      let semver_range;
      if (manifest.info["qooxdoo-range"]) {
        if (!argv.quiet) {
          console.info(`Deprecated key "manifest.info.qooxdoo-range" found, will be changed to manifest.requires.qooxdoo-sdk`);
        }
        semver_range = manifest.info["qooxdoo-range"];
        delete manifest.info["qooxdoo-range"];
      }
      semver_range = manifest.requires["qooxdoo-sdk"] || semver_range;

      if (!semver.satisfies(qooxdoo_version, semver_range, {loose: true})) {
        semver_range += (semver_range ? " || " : "") + qooxdoo_version;
        manifest.requires["qooxdoo-sdk"] = semver_range;
      }
      let manifest_content = JSON.stringify(manifest, null, 2);
      if (!argv.dryrun) {
        fs.writeFileSync(manifest_path, manifest_content, "utf-8");
      }

      if (argv.dryrun) {
        if (!argv.quiet) {
          console.info(`Dry run: not creating tag and release '${tag}' of ${repo_name}...`);
        }
        console.info("Here is the Manifest.json that would have been committed: ");
        console.info(manifest_content);
        process.exit(0);
      }

      // commit message
      let message;
      if (argv.message) {
        message = argv.message.replace(/"/g, "\\\"");
      } else if (!argv.noninteractive) {
        let question = {
          type: "input",
          name: "message",
          message: `Please enter a commit message:`
        };
        let answer = await inquirer.prompt([question]);
        message = answer.message;
      }
      if (!message) {
        message = `Release v${new_version}`;
      }

      if (!argv.quiet) {
        console.info(`Creating tag and release '${tag}' of ${repo_name}...`);
      }

      // commit and push
      try {
        await this.run("git", ["add", "Manifest.json"]);
        await this.run("git", ["commit", `-m "${message}"`]);
        await this.run("git", ["push"]);
        let release_data = {
          owner,
          repo,
          tag_name: tag,
          target_commitish: "master",
          name: tag,
          body: message,
          draft: false,
          prerelease: (argv.type.indexOf("pre")>=0)
        };
        await octokit.repos.createRelease(release_data);
        if (!argv.quiet) {
          console.info(`Published new version '${tag}'.`);
        }
      } catch (e) {
        throw new qx.tool.cli.Utils.UserError(e.message);
      }
      // add GitHub topic
      const topic = "qooxdoo-contrib";
      if (!topics.includes(topic)) {
        topics.push(topic);
        await octokit.repos.replaceTopics({owner, repo, names:topics});
        if (!argv.quiet) {
          console.info(`Added GitHub topic '${topic}'.`);
        }
      }
    }
  }
});
<commit_msg>fix error if manifest.requires["qooxdoo-sdk"] is undefined<commit_after>/* ************************************************************************

   qooxdoo - the new era of web development

   http://qooxdoo.org

   Copyright:
     2017 Christian Boulanger

   License:
     MIT: https://opensource.org/licenses/MIT
     See the LICENSE file in the project's top-level directory for details.

   Authors:
     * Christian Boulanger (info@bibliograph.org, @cboulanger)

************************************************************************ */
require("../Contrib");

require("qooxdoo");
const fs = require("fs");
const process = require("process");
const octokit = require("@octokit/rest")();
const semver = require("semver");
const inquirer = require("inquirer");

/**
 * Publishes a release on GitHub
 */
qx.Class.define("qx.tool.cli.commands.contrib.Publish", {
  extend: qx.tool.cli.commands.Contrib,

  statics: {
    getYargsCommand: function() {
      return {
        command: "publish",
        describe: "publishes a new release of the contrib on GitHub. Requires a GitHub access token. By default, makes a patch release.",
        builder: {
          "type": {
            alias : "t",
            describe: "Set the release type",
            nargs: 1,
            requiresArg: true,
            choices: "major,premajor,minor,preminor,patch,prepatch,prerelease".split(/,/),
            type: "string",
            default : "patch"
          },
          "noninteractive":{
            alias: "I",
            describe: "Do not prompt user"
          },
          "version": {
            alias: "V",
            describe: "Use given version number"
          },
          "quiet": {
            alias: "q",
            describe: "No output"
          },
          "message":{
            alias: "m",
            describe: "Set commit/release message"
          },
          "dryrun":{
            describe: "Show result only, do not publish to GitHub"
          },
          "verbose": {
            alias: "v",
            describe: "Verbose logging"
          },
          "force": {
            alias: "f",
            describe: "overrun demo check"
          }
        },
        handler: function(argv) {
          return new qx.tool.cli.commands.contrib.Publish(argv)
            .process()
            .catch(e => {
              console.error(e.stack || e.message);
              process.exit(1);
            });
        }
      };
    }
  },

  members: {

    /**
     * Publishes a new release of the contrib on GitHub, by executing the following steps:
     *
     * 1. In Manifest.json, update the qooxdoo-range value to include the version of the qooxdoo
     *    framework (As per version.txt).
     * 2. In Manifest.json, based the given options, increment the version number (patch,
     *    feature, breaking).
     * 3. Create a release with the tag vX.Y.Z according to the current version.
     * 4. Add "qooxdoo-contrib" to the list of GitHub topics.
     *
     */
    process: async function() {
      // init
      const argv = this.argv;

      // qooxdoo version
      let qooxdoo_version = await this.getUserQxVersion();
      if (argv.verbose) {
        console.log(`>>> qooxdoo version:  ${qooxdoo_version}`);
      }

      // check git status
      let status = await this.exec("git status --porcelain");
      if (status.trim() !=="") {
        throw new qx.tool.cli.Utils.UserError("Please commit or stash all remaining changes first.");
      }
      status = await this.exec("git status --porcelain --branch");
      if (status.includes("ahead")) {
        throw new qx.tool.cli.Utils.UserError("Please push all local commits to GitHub first.");
      }

      // token
      let cfg = await qx.tool.cli.ConfigDb.getInstance();
      let github = cfg.db("github", {});
      if (!github.token) {
        let response = await inquirer.prompt([
          {
            type: "input",
            name: "token",
            message: "Publishing to GitHub requires an API token - visit https://github.com/settings/tokens to obtain one " +
                "(you must assign permission to publish);\nWhat is your GitHub API Token ? "
          }
        ]
        );
        if (!response.token) {
          console.error("You have not provided a GitHub token.");
          return;
        }
        github.token = response.token;
        cfg.save();
      }
      let token = github.token;
      if (!token) {
        throw new qx.tool.cli.Utils.UserError(`GitHub access token required.`);
      }
      octokit.authenticate({
        type: "token",
        token
      });

      // read Manifest.json
      let manifest_path = process.cwd() + "/Manifest.json";
      if (!fs.existsSync(manifest_path)) {
        throw new qx.tool.cli.Utils.UserError("Cannot find Manifest.json - are you in the project directory?");
      }
      let manifest = qx.tool.compiler.utils.Json.parseJson(fs.readFileSync(manifest_path, "utf-8"));

      // prevent accidental publication of demo manifest.
      if (!argv.force && manifest.provides.namespace.includes(".demo")) {
        throw new qx.tool.cli.Utils.UserError("This seems to be the contrib demo. Please go into the library directory to publish the library.");
      }

      // version
      let new_version;
      if (argv.version) {
        // use user-supplied value
        new_version = argv.version;
        if (!semver.valid(new_version)) {
          throw new qx.tool.cli.Utils.UserError(`${new_version} is not a valid version number.`);
        }
      } else {
        // use version number from manifest and increment it
        let old_version = manifest.info.version;
        if (!semver.valid(old_version)) {
          throw new qx.tool.cli.Utils.UserError("Invalid version number in Manifest. Must be a valid semver version (x.y.z).");
        }
        new_version = semver.inc(old_version, argv.type);
      }

      // tag and repo name
      let tag = `v${new_version}`;
      let url;
      try {
        url = (await this.exec("git config --get remote.origin.url")).trim();
      } catch (e) {
        throw new qx.tool.cli.Utils.UserError("Cannot determine remote repository.");
      }
      let repo_name = url.replace(/(https:\/\/github.com\/|git@github.com:)/, "").replace(/\.git/, "");
      let [owner, repo] = repo_name.split(/\//);
      if (argv.verbose) {
        console.log(`>>> Repository:  ${repo_name}`);
      }
      let repoExists = false;
      try {
        repoExists = true;
      } catch (e) {}
      if (repoExists) {
        throw new qx.tool.cli.Utils.UserError(`A release with tag '${tag} already exists.'`);
      }

      // get topics, this will also check credentials
      let result;
      let topics;
      try {
        result = await octokit.repos.listTopics({owner,
          repo});
        topics = result.data.names;
      } catch (e) {
        if (e.message.includes("Bad credentials")) {
          throw new qx.tool.cli.Utils.UserError(`Your token is invalid.`);
        }
        throw e;
      }

      // prompt user to confirm
      let doRelease = true;
      if (!argv.noninteractive) {
        let question = {
          type: "confirm",
          name: "doRelease",
          message: `This will ${argv.version?"set":"increment"} the version to ${new_version} and create a release of the current master on GitHub. Do you want to proceed?`,
          default: "y"
        };
        let answer = await inquirer.prompt(question);
        doRelease = answer.doRelease;
      }
      if (!doRelease) {
        process.exit(0);
      }

      // update Manifest.json
      manifest.info.version = new_version;
      // qooxdoo-versions @deprecated
      let qooxdoo_versions = manifest.info["qooxdoo-versions"];
      if (qooxdoo_versions instanceof Array) {
        if (!qooxdoo_versions.includes(qooxdoo_version)) {
          manifest.info["qooxdoo-versions"].push(qooxdoo_version);
        }
      }

      // qooxdoo-range @deprecated
      let needWrite = false;
      let semver_range;
      if (manifest.info["qooxdoo-range"]) {
        if (!argv.quiet) {
          console.info(`Deprecated key "manifest.info.qooxdoo-range" found, will be changed to manifest.requires.qooxdoo-sdk`);
        }
        semver_range = manifest.info["qooxdoo-range"];
        delete manifest.info["qooxdoo-range"];
        needWrite = true;
      }
      semver_range = (manifest.requires && manifest.requires["qooxdoo-sdk"]) || semver_range;

      if (!semver.satisfies(qooxdoo_version, semver_range, {loose: true})) {
        needWrite = true;
        semver_range += (semver_range ? " || " : "") + qooxdoo_version;
      }
      if (needWrite) {
        if (!manifest.requires) {
          manifest.requires = {};
        }
        manifest.requires["qooxdoo-sdk"] = semver_range;
      }

      let manifest_content = JSON.stringify(manifest, null, 2);
      if (!argv.dryrun) {
        fs.writeFileSync(manifest_path, manifest_content, "utf-8");
      }

      if (argv.dryrun) {
        if (!argv.quiet) {
          console.info(`Dry run: not creating tag and release '${tag}' of ${repo_name}...`);
        }
        console.info("Here is the Manifest.json that would have been committed: ");
        console.info(manifest_content);
        process.exit(0);
      }

      // commit message
      let message;
      if (argv.message) {
        message = argv.message.replace(/"/g, "\\\"");
      } else if (!argv.noninteractive) {
        let question = {
          type: "input",
          name: "message",
          message: `Please enter a commit message:`
        };
        let answer = await inquirer.prompt([question]);
        message = answer.message;
      }
      if (!message) {
        message = `Release v${new_version}`;
      }

      if (!argv.quiet) {
        console.info(`Creating tag and release '${tag}' of ${repo_name}...`);
      }

      // commit and push
      try {
        await this.run("git", ["add", "Manifest.json"]);
        await this.run("git", ["commit", `-m "${message}"`]);
        await this.run("git", ["push"]);
        let release_data = {
          owner,
          repo,
          tag_name: tag,
          target_commitish: "master",
          name: tag,
          body: message,
          draft: false,
          prerelease: (argv.type.indexOf("pre")>=0)
        };
        await octokit.repos.createRelease(release_data);
        if (!argv.quiet) {
          console.info(`Published new version '${tag}'.`);
        }
      } catch (e) {
        throw new qx.tool.cli.Utils.UserError(e.message);
      }
      // add GitHub topic
      const topic = "qooxdoo-contrib";
      if (!topics.includes(topic)) {
        topics.push(topic);
        await octokit.repos.replaceTopics({owner,
          repo,
          names:topics});
        if (!argv.quiet) {
          console.info(`Added GitHub topic '${topic}'.`);
        }
      }
    }
  }
});
<|endoftext|>


<commit_before>
$header		= $("#header");
$content	= $("#content");
$buttons	= $("#buttons");
$picture	= $("#picture");

var pages =
[
  {
    "header": "Pura Vida Mae Bienvenidos",
    "button": "Home",
    "path": "main.html"
  },

  {
    "header": "Who is Chris Elie?",
    "button": "About",
    "path": "about.html"
  },

  {
    "header": "Projects",
    "button": "Projects",
    "path": "projects.html"
  }

];

var currentpage = 0;

var setHeader = function setHeaderF(header){
	$header.html(header);
}
var setContent = function setContentF(path){
	$.get("pages/" + path, function(data){
		$content.html(data);
	})
}
var genButtons = function genButtonsF(){
    for(var i = 0; i < pages.length; i++){
        $buttons.append("
" + pages[i].button + "
" );
    }
}
var update = function updateF(number){
    setHeader(pages[number].header);
    setContent(pages[number].path);
}

// Personal Functions
var removeAll = function removeAllF(){
	$picture.remove();
	$buttons.remove();
	$header.remove();
	$content.remove();
}
var addGames = function addGamesF(){
	$('head').append('');
}

// Called immediately
update(0);
genButtons();
$('#0').addClass('active');

var path = window.location.pathname;

if(path === "/nopic"){
  $picture.remove();
}

// waiting
$("li").click(function(event){
    $('#' + currentpage).removeClass('active');
    $(this).addClass('active');
    update($(this)[0].id);
    currentpage = $(this)[0].id;
});
<commit_msg>huge errors happening<commit_after>
$header		= $("#header");
$content	= $("#content");
$buttons	= $("#buttons");
$picture	= $("#picture");

var pages =
[
  {
    "header": "Pura Vida Mae Bienvenidos",
    "button": "Home",
    "path": "main.html"
  },

  {
    "header": "Who is Chris Elie?",
    "button": "About",
    "path": "about.html"
  },

  {
    "header": "Projects",
    "button": "Projects",
    "path": "projects.html"
  }

];

var currentpage = 0;

var setHeader = function setHeaderF(header){
	$header.html(header);
}
var setContent = function setContentF(path){
	$.get("pages/" + path, function(data){
		$content.html(data);
	})
}
var genButtons = function genButtonsF(){
    for(var i = 0; i < pages.length; i++){
        $buttons.append("
" + pages[i].button + "
" );
    }
}
var update = function updateF(number){
    setHeader(pages[number].header);
    setContent(pages[number].path);
}

// Personal Functions
var removeAll = function removeAllF(){
	$picture.remove();
	$buttons.remove();
	$header.remove();
	$content.remove();
}
var addGames = function addGamesF(){
	$('head').append('');
}

// Called immediately
update(0);
genButtons();
$('#0').addClass('active');

var path = window.location.pathname.split('/');

if(path[path.length - 1] === "/nopic"){
  console.log(path[path.length-1]);
  $picture.remove();
}

// waiting
$("li").click(function(event){
    $('#' + currentpage).removeClass('active');
    $(this).addClass('active');
    update($(this)[0].id);
    currentpage = $(this)[0].id;
});
<|endoftext|>


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

/* jshint latedef: false */

(function () {
    "use strict";

    var DocumentManager = require("./lib/documentmanager"),
        StateManager = require("./lib/statemanager"),
        RenderManager = require("./lib/rendermanager"),
        AssetManager = require("./lib/assetmanager"),
        Headlights = require("./lib/headlights");

    var PLUGIN_ID = require("./package.json").name;

    var _generator,
        _config,
        _logger,
        _documentManager,
        _stateManager,
        _renderManager,
        _SONToCSSConverter;

    var _assetManagers = {};

    var _waitingDocuments = {},
        _canceledDocuments = {};

    /**
     * Disable asset generation for the given Document ID, halting any asset
     * rending in progress.
     *
     * @private
     * @param {!number} id The document ID for which asset generation should be disabled.
     */
    function _pauseAssetGeneration(id) {
        if (_waitingDocuments.hasOwnProperty(id)) {
            _canceledDocuments[id] = true;
        } else if (_assetManagers.hasOwnProperty(id)) {
            _assetManagers[id].stop();
        }
    }

    /**
     * Completely stop asset generation for the given Document ID and collect
     * its AssetManager instance.
     *
     * @private
     * @param {!number} id The document ID for which asset generation should be disabled.
     */
    function _stopAssetGeneration(id) {
        _pauseAssetGeneration(id);

        if (_assetManagers.hasOwnProperty(id)) {
            delete _assetManagers[id];
        }
    }

    /**
     * Handler for a the "file" change event fired by Document objects. Disables
     * asset generation after Save As is performed on an an already-saved file.
     *
     * @private
     * @param {number} id The ID of the Document that changed
     * @param {{previous: string=, previousSaved: boolean=}} change The file
     *      change event emitted by the Document
     */
    function _handleFileChange(id, change) {
        // If the filename changed but the saved state didn't change, then the file must have been renamed
        if (change.previous && !change.hasOwnProperty("previousSaved")) {
            _stopAssetGeneration(id);
            _stateManager.deactivate(id);
        }
    }

    /**
     * Extract generator settings from the "current" or "previous" property of a generatorSettings
     * change event. If the supplied value is not actually a settings object, returns null.
     *
     * @private
     * @param {object} settings Settings json object.
     * @return {object} Settings object from generator or null.
     */
    function _getChangedSettings(settings) {
        if (settings && typeof(settings) === "object") {
            return _generator.extractDocumentSettings({generatorSettings: settings}, PLUGIN_ID);
        }
        return null;
    }

    /**
     * Handler for a the "generatorSettings" change event fired by Document objects. Updates
     * the state manger based on the current doc setting if the enable settings actually
     * changed
     *
     * @private
     * @param {number} id The ID of the Document that changed
     * @param {{previous: settings=, current: settings=}} change The previous and current
     *      document settings
     */
    function _handleDocGeneratorSettingsChange(id, change) {
        var curSettings = _getChangedSettings(change.current),
            prevSettings = _getChangedSettings(change.previous),
            curEnabled = !!(curSettings && curSettings.enabled),
            prevEnabled = !!(prevSettings && prevSettings.enabled);

        if (prevEnabled !== curEnabled) {
            if (curEnabled) {
                _stateManager.activate(id);
            } else {
                _stateManager.deactivate(id);
            }
        }
    }

    /**
     * Handler for a the "openDocumentsChanged" event emitted by the DocumentManager.
     * Registers a generatorSettings change to update the StateManager appropiately
     *
     * @private
     * @param {Array.<number>} all The complete set of open document IDs
     * @param {Array.<number>=} opened The set of newly opened document IDs
     */
    function _handleOpenDocumentsChanged(all, opened) {
        var open = opened || all;

        open.forEach(function (id) {
            _documentManager.getDocument(id).done(function (document) {
                document.on("generatorSettings", _handleDocGeneratorSettingsChange.bind(undefined, id));
            }, function (error) {
                _logger.warning("Error getting document during a document changed event, " +
                    "document was likely closed.", error);
            });
        });
    }

    /**
     * Enable asset generation for the given Document ID, causing all annotated
     * assets in the given document to be regenerated.
     *
     * @private
     * @param {!number} id The document ID for which asset generation should be enabled.
     */
    function _startAssetGeneration(id) {
        if (_waitingDocuments.hasOwnProperty(id)) {
            return;
        }

        var documentPromise = _documentManager.getDocument(id);

        _waitingDocuments[id] = documentPromise;

        documentPromise.done(function (document) {
            delete _waitingDocuments[id];

            if (_canceledDocuments.hasOwnProperty(id)) {
                delete _canceledDocuments[id];
            } else {
                if (!_assetManagers.hasOwnProperty(id)) {
                    _assetManagers[id] = new AssetManager(_generator, _config, _logger, document, _renderManager);

                    document.on("closed", _stopAssetGeneration.bind(undefined, id));
                    document.on("end", _restartAssetGeneration.bind(undefined, id));
                    document.on("file", _handleFileChange.bind(undefined, id));
                }
                _assetManagers[id].start();
            }
        });
    }

    /**
     * Restart asset generation for the given Document ID. This is called when
     * a Document emits an "end" event, indicating that there was an error
     * updating its internal state as from Photoshop's change events.
     *
     * @private
     * @param {!number} id The document ID for which asset generation should be enabled.
     */
    function _restartAssetGeneration(id) {
        _stopAssetGeneration(id);
        _startAssetGeneration(id);
    }

    /**
     * Get a copy of the plugin's config object. For automated testing only.
     *
     * @private
     * @return {object}
     */
    function _getConfig() {
        var copy = {},
            property;

        for (property in _config) {
            if (_config.hasOwnProperty(property)) {
                copy[property] = _config[property];
            }
        }

        return copy;
    }

    /**
     * Set the plugin's config object. This mutates the referenced object, not the
     * reference. For automated testing only.
     *
     * @private
     * @param {object} config
     */
    function _setConfig(config) {
        var property;

        // clear out the existing properties
        for (property in _config) {
            if (_config.hasOwnProperty(property)) {
                delete _config[property];
            }
        }

        // add in the new properties
        for (property in config) {
            if (config.hasOwnProperty(property)) {
                _config[property] = config[property];
            }
        }
    }

    /**
     * Initialize the Assets plugin.
     *
     * @param {Generator} generator The Generator instance for this plugin.
     * @param {object} config Configuration options for this plugin.
     * @param {Logger} logger The Logger instance for this plugin.
     */
    function init(generator, config, logger) {
        _generator = generator;
        _config = config;
        _logger = logger;

        _documentManager = new DocumentManager(generator, config, logger);
        _stateManager = new StateManager(generator, config, logger, _documentManager);
        _renderManager = new RenderManager(generator, config, logger);

        if (!!_config["css-enabled"]) {
            var SONToCSS = require("./lib/css/sontocss.js");
            _SONToCSSConverter = new SONToCSS(generator, config, logger, _documentManager);
        }

        // For automated tests
        exports._renderManager = _renderManager;
        exports._stateManager = _stateManager;
        exports._assetManagers = _assetManagers;
        exports._layerNameParse = require("./lib/parser").parse;

        _stateManager.on("enabled", _startAssetGeneration);
        _stateManager.on("disabled", _pauseAssetGeneration);
        _documentManager.on("openDocumentsChanged", _handleOpenDocumentsChanged);

        Headlights.init(generator, logger, _stateManager, _renderManager);
    }

    exports.init = init;

    // For automated tests
    exports._getConfig = _getConfig;
    exports._setConfig = _setConfig;
}());
<commit_msg>Support g-a-a option to honor standard g-a configs during tests<commit_after>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/* jshint latedef: false */

(function () {
    "use strict";

    var DocumentManager = require("./lib/documentmanager"),
        StateManager = require("./lib/statemanager"),
        RenderManager = require("./lib/rendermanager"),
        AssetManager = require("./lib/assetmanager"),
        Headlights = require("./lib/headlights");

    var PLUGIN_ID = require("./package.json").name;

    var _generator,
        _config,
        _logger,
        _documentManager,
        _stateManager,
        _renderManager,
        _SONToCSSConverter;

    var _assetManagers = {};

    var _waitingDocuments = {},
        _canceledDocuments = {};

    /**
     * Disable asset generation for the given Document ID, halting any asset
     * rending in progress.
     *
     * @private
     * @param {!number} id The document ID for which asset generation should be disabled.
     */
    function _pauseAssetGeneration(id) {
        if (_waitingDocuments.hasOwnProperty(id)) {
            _canceledDocuments[id] = true;
        } else if (_assetManagers.hasOwnProperty(id)) {
            _assetManagers[id].stop();
        }
    }

    /**
     * Completely stop asset generation for the given Document ID and collect
     * its AssetManager instance.
     *
     * @private
     * @param {!number} id The document ID for which asset generation should be disabled.
     */
    function _stopAssetGeneration(id) {
        _pauseAssetGeneration(id);

        if (_assetManagers.hasOwnProperty(id)) {
            delete _assetManagers[id];
        }
    }

    /**
     * Handler for a the "file" change event fired by Document objects. Disables
     * asset generation after Save As is performed on an an already-saved file.
     *
     * @private
     * @param {number} id The ID of the Document that changed
     * @param {{previous: string=, previousSaved: boolean=}} change The file
     *      change event emitted by the Document
     */
    function _handleFileChange(id, change) {
        // If the filename changed but the saved state didn't change, then the file must have been renamed
        if (change.previous && !change.hasOwnProperty("previousSaved")) {
            _stopAssetGeneration(id);
            _stateManager.deactivate(id);
        }
    }

    /**
     * Extract generator settings from the "current" or "previous" property of a generatorSettings
     * change event. If the supplied value is not actually a settings object, returns null.
     *
     * @private
     * @param {object} settings Settings json object.
     * @return {object} Settings object from generator or null.
     */
    function _getChangedSettings(settings) {
        if (settings && typeof(settings) === "object") {
            return _generator.extractDocumentSettings({generatorSettings: settings}, PLUGIN_ID);
        }
        return null;
    }

    /**
     * Handler for a the "generatorSettings" change event fired by Document objects. Updates
     * the state manger based on the current doc setting if the enable settings actually
     * changed
     *
     * @private
     * @param {number} id The ID of the Document that changed
     * @param {{previous: settings=, current: settings=}} change The previous and current
     *      document settings
     */
    function _handleDocGeneratorSettingsChange(id, change) {
        var curSettings = _getChangedSettings(change.current),
            prevSettings = _getChangedSettings(change.previous),
            curEnabled = !!(curSettings && curSettings.enabled),
            prevEnabled = !!(prevSettings && prevSettings.enabled);

        if (prevEnabled !== curEnabled) {
            if (curEnabled) {
                _stateManager.activate(id);
            } else {
                _stateManager.deactivate(id);
            }
        }
    }

    /**
     * Handler for a the "openDocumentsChanged" event emitted by the DocumentManager.
     * Registers a generatorSettings change to update the StateManager appropiately
     *
     * @private
     * @param {Array.<number>} all The complete set of open document IDs
     * @param {Array.<number>=} opened The set of newly opened document IDs
     */
    function _handleOpenDocumentsChanged(all, opened) {
        var open = opened || all;

        open.forEach(function (id) {
            _documentManager.getDocument(id).done(function (document) {
                document.on("generatorSettings", _handleDocGeneratorSettingsChange.bind(undefined, id));
            }, function (error) {
                _logger.warning("Error getting document during a document changed event, " +
                    "document was likely closed.", error);
            });
        });
    }

    /**
     * Enable asset generation for the given Document ID, causing all annotated
     * assets in the given document to be regenerated.
     *
     * @private
     * @param {!number} id The document ID for which asset generation should be enabled.
     */
    function _startAssetGeneration(id) {
        if (_waitingDocuments.hasOwnProperty(id)) {
            return;
        }

        var documentPromise = _documentManager.getDocument(id);

        _waitingDocuments[id] = documentPromise;

        documentPromise.done(function (document) {
            delete _waitingDocuments[id];

            if (_canceledDocuments.hasOwnProperty(id)) {
                delete _canceledDocuments[id];
            } else {
                if (!_assetManagers.hasOwnProperty(id)) {
                    _assetManagers[id] = new AssetManager(_generator, _config, _logger, document, _renderManager);

                    document.on("closed", _stopAssetGeneration.bind(undefined, id));
                    document.on("end", _restartAssetGeneration.bind(undefined, id));
                    document.on("file", _handleFileChange.bind(undefined, id));
                }
                _assetManagers[id].start();
            }
        });
    }

    /**
     * Restart asset generation for the given Document ID. This is called when
     * a Document emits an "end" event, indicating that there was an error
     * updating its internal state as from Photoshop's change events.
     *
     * @private
     * @param {!number} id The document ID for which asset generation should be enabled.
     */
    function _restartAssetGeneration(id) {
        _stopAssetGeneration(id);
        _startAssetGeneration(id);
    }

    /**
     * Get a copy of the plugin's config object. For automated testing only.
     *
     * @private
     * @return {object}
     */
    function _getConfig() {
        var copy = {},
            property;

        for (property in _config) {
            if (_config.hasOwnProperty(property)) {
                copy[property] = _config[property];
            }
        }

        return copy;
    }

    /**
     * Set the plugin's config object. This mutates the referenced object, not the
     * reference. For automated testing only.
     *
     * @private
     * @param {object} config
     * @param {boolean=} keepExisting if true then don't delete previous configs first. default: false
     */
    function _setConfig(config, keepExisting) {
        var property;

        // optionally clean out the existing properties first
        if (!keepExisting) {
            for (property in _config) {
                if (_config.hasOwnProperty(property)) {
                    delete _config[property];
                }
            }
        }

        // add in the new properties
        for (property in config) {
            if (config.hasOwnProperty(property)) {
                _config[property] = config[property];
            }
        }
    }

    /**
     * Initialize the Assets plugin.
     *
     * @param {Generator} generator The Generator instance for this plugin.
     * @param {object} config Configuration options for this plugin.
     * @param {Logger} logger The Logger instance for this plugin.
     */
    function init(generator, config, logger) {
        _generator = generator;
        _config = config;
        _logger = logger;

        _documentManager = new DocumentManager(generator, config, logger);
        _stateManager = new StateManager(generator, config, logger, _documentManager);
        _renderManager = new RenderManager(generator, config, logger);

        if (!!_config["css-enabled"]) {
            var SONToCSS = require("./lib/css/sontocss.js");
            _SONToCSSConverter = new SONToCSS(generator, config, logger, _documentManager);
        }

        // For automated tests
        exports._renderManager = _renderManager;
        exports._stateManager = _stateManager;
        exports._assetManagers = _assetManagers;
        exports._layerNameParse = require("./lib/parser").parse;

        _stateManager.on("enabled", _startAssetGeneration);
        _stateManager.on("disabled", _pauseAssetGeneration);
        _documentManager.on("openDocumentsChanged", _handleOpenDocumentsChanged);

        Headlights.init(generator, logger, _stateManager, _renderManager);
    }

    exports.init = init;

    // For automated tests
    exports._getConfig = _getConfig;
    exports._setConfig = _setConfig;
}());
<|endoftext|>


<commit_before>var sprites = new Object();
var spritesArray = new Array();

//sprite object constructor
function Sprite(x, y, value){
    this.x = x;
    this.y = y;
    this.direction = 0;

    //updates both x and y
    this.updateLocation = function(){
        this.element.style.left = (originOffsetX + this.x)+"px";
        this.element.style.top = (originOffsetY - this.y)+"px";
    }

    //updates only x
    this.updateX = function(){
        this.element.style.left = (originOffsetX + this.x)+"px";
    }

    //updates only y
    this.updateY = function(){
        this.element.style.top = (originOffsetY - this.y)+"px";
    }

    this.updateRotation = function(){
        //by default turns clockwise, added "-" to make it turn counterclockwise like in geometry
        this.element.style.transform = "rotate("+(this.direction * -1)+"deg)";
    }

    //hack of a hack of a solution, but still works. Regex checks if value is an html tag
    var valueIsHtmlTag = (/<(br|basefont|hr|input|source|frame|param|area|meta|!--|col|link|option|base|img|wbr|!DOCTYPE).*?>|<(a|abbr|acronym|address|applet|article|aside|audio|b|bdi|bdo|big|blockquote|body|button|canvas|caption|center|cite|code|colgroup|command|datalist|dd|del|details|dfn|dialog|dir|div|dl|dt|em|embed|fieldset|figcaption|figure|font|footer|form|frameset|head|header|hgroup|h1|h2|h3|h4|h5|h6|html|i|iframe|ins|kbd|keygen|label|legend|li|map|mark|menu|meter|nav|noframes|noscript|object|ol|optgroup|output|p|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|span|strike|strong|style|sub|summary|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|track|tt|u|ul|var|video).*?<\/\2>/i.test(value))

    if(valueIsHtmlTag){
        //if value is an html tag name
        this.isCustom = false;
        var containingDiv = document.createElement("div");
        containingDiv.innerHTML = value;
        this.element = containingDiv.firstChild;
        this.updateLocation();
        document.body.appendChild(containingDiv);
    }else if(value === undefined){
        console.error("Please enter a value for the new sprite(3rd argument)")
    }else{
        //value is not html or error so custom sprite, use value as img src
        this.isCustom = true;
        this.element = document.createElement("img")
        this.element.src = value;
        this.updateLocation();
        document.body.appendChild(this.element);
    }

    //TODO: Add option to animate if time parameter passed to function when called
    this.goTo = function(x,y){
        var animationTime = arguments[2];
        if(animationTime){
            //Glide function: Animates the sprites movment -- Algorithm not yet complete
            console.error("Scratch-JS: Animation is not yet supported");
        }else{
            this.x = x;
            this.y = y;
            this.updateLocation();
        }
    }

    //sets the x of the sprite
    this.setXTo = function(newX){
        this.x = newX;
        this.updateX();
    }

    //sets the y of the sprite
    this.setYTo = function(newY){
        this.y = newY;
        this.updateY();
    }

    //changes the x of the sprite by an amount
    this.changeXBy = function(deltaX){
        this.x += deltaX;
        this.updateX();
    }

    //changes the x of the sprite by an amount
    this.changeYBy = function(deltaY){
        this.y += deltaY;
        this.updateY();
    }

    this.turn = function(degrees){
        this.direction += degrees;
        this.updateRotation();
    }

    this.pointInDirection = function(direction){
        this.direction = direction;
        this.updateRotation();
    }

    this.move = function(amount){
        var deltaX = Math.cos(this.direction * Math.PI / 180) * amount;
        var deltaY = Math.sin(this.direction * Math.PI / 180) * amount;
        this.x += deltaX;
        this.y += deltaY;
        console.log(deltaY);
        console.log(deltaX);
        this.updateLocation();
    }
}

function calculateDistance(x1,y1,x2, y2){
    //simple pythagorean theorm to find distance between points
    return Math.sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2)))
}

function repeat(times, callback){
    for(i = 0; i<times; i++){
        callback();
    }
}

function wait(seconds,callback){
    setTimeout(callback,seconds);
}

var whenPageLoads = function(){}

var originOffsetX;
var originOffsetY;
var maxX;
var maxY;
window.onload = function(){
    originOffsetX = window.innerWidth / 2;
    originOffsetY = window.innerHeight / 2;
    maxX = originOffsetX;
    maxY = originOffsetY;
    whenPageLoads();
}

window.onresize = function(){
    originOffsetX = window.innerWidth / 2;
    originOffsetY = window.innerHeight / 2;
    maxX = originOffsetX;
    maxY = originOffsetY;
    for(var sprite in sprites){
        sprites[sprite].updateLocation();
    }
}
<commit_msg>Added ask() method<commit_after>var sprites = new Object();
var spritesArray = new Array();

//sprite object constructor
function Sprite(x, y, value){
    this.x = x;
    this.y = y;
    this.direction = 0;

    //updates both x and y
    this.updateLocation = function(){
        this.element.style.left = (originOffsetX + this.x)+"px";
        this.element.style.top = (originOffsetY - this.y)+"px";
    }

    //updates only x
    this.updateX = function(){
        this.element.style.left = (originOffsetX + this.x)+"px";
    }

    //updates only y
    this.updateY = function(){
        this.element.style.top = (originOffsetY - this.y)+"px";
    }

    this.updateRotation = function(){
        //by default turns clockwise, added "-" to make it turn counterclockwise like in geometry
        this.element.style.transform = "rotate("+(this.direction * -1)+"deg)";
    }

    //hack of a hack of a solution, but still works. Regex checks if value is an html tag
    var valueIsHtmlTag = (/<(br|basefont|hr|input|source|frame|param|area|meta|!--|col|link|option|base|img|wbr|!DOCTYPE).*?>|<(a|abbr|acronym|address|applet|article|aside|audio|b|bdi|bdo|big|blockquote|body|button|canvas|caption|center|cite|code|colgroup|command|datalist|dd|del|details|dfn|dialog|dir|div|dl|dt|em|embed|fieldset|figcaption|figure|font|footer|form|frameset|head|header|hgroup|h1|h2|h3|h4|h5|h6|html|i|iframe|ins|kbd|keygen|label|legend|li|map|mark|menu|meter|nav|noframes|noscript|object|ol|optgroup|output|p|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|span|strike|strong|style|sub|summary|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|track|tt|u|ul|var|video).*?<\/\2>/i.test(value))

    if(valueIsHtmlTag){
        //if value is an html tag name
        this.isCustom = false;
        var containingDiv = document.createElement("div");
        containingDiv.innerHTML = value;
        this.element = containingDiv.firstChild;
        this.updateLocation();
        document.body.appendChild(containingDiv);
    }else if(value === undefined){
        console.error("Please enter a value for the new sprite(3rd argument)")
    }else{
        //value is not html or error so custom sprite, use value as img src
        this.isCustom = true;
        this.element = document.createElement("img")
        this.element.src = value;
        this.updateLocation();
        document.body.appendChild(this.element);
    }

    //TODO: Add option to animate if time parameter passed to function when called
    this.goTo = function(x,y){
        var animationTime = arguments[2];
        if(animationTime){
            //Glide function: Animates the sprites movment -- Algorithm not yet complete
            console.error("Scratch-JS: Animation is not yet supported");
        }else{
            this.x = x;
            this.y = y;
            this.updateLocation();
        }
    }

    //sets the x of the sprite
    this.setXTo = function(newX){
        this.x = newX;
        this.updateX();
    }

    //sets the y of the sprite
    this.setYTo = function(newY){
        this.y = newY;
        this.updateY();
    }

    //changes the x of the sprite by an amount
    this.changeXBy = function(deltaX){
        this.x += deltaX;
        this.updateX();
    }

    //changes the x of the sprite by an amount
    this.changeYBy = function(deltaY){
        this.y += deltaY;
        this.updateY();
    }

    this.turn = function(degrees){
        this.direction += degrees;
        this.updateRotation();
    }

    this.pointInDirection = function(direction){
        this.direction = direction;
        this.updateRotation();
    }

    this.move = function(amount){
        var deltaX = Math.cos(this.direction * Math.PI / 180) * amount;
        var deltaY = Math.sin(this.direction * Math.PI / 180) * amount;
        this.x += deltaX;
        this.y += deltaY;
        console.log(deltaY);
        console.log(deltaX);
        this.updateLocation();
    }
}

function calculateDistance(x1,y1,x2, y2){
    //simple pythagorean theorm to find distance between points
    return Math.sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2)))
}

function repeat(times, callback){
    for(i = 0; i<times; i++){
        callback();
    }
}

function wait(seconds,callback){
    setTimeout(callback,seconds);
}

function ask(text){
    return prompt(text);
}

var whenPageLoads = function(){}

var originOffsetX;
var originOffsetY;
var maxX;
var maxY;
window.onload = function(){
    originOffsetX = window.innerWidth / 2;
    originOffsetY = window.innerHeight / 2;
    maxX = originOffsetX;
    maxY = originOffsetY;
    whenPageLoads();
}

window.onresize = function(){
    originOffsetX = window.innerWidth / 2;
    originOffsetY = window.innerHeight / 2;
    maxX = originOffsetX;
    maxY = originOffsetY;
    for(var sprite in sprites){
        sprites[sprite].updateLocation();
    }
}
<|endoftext|>


<commit_before>// recordara 0.1
// WebSDR Automatic Recorder
// Licensed under MIT.

var config = require('./config');
var urlify = require('urlify').create();
var moment = require('moment');
var spawn = require('child_process').spawn;
var spawnSync = require('child_process').spawnSync;
var fs = require('fs');

var hasEvents = false;
var events = [];

var schedNext;
var schedAnnounce;

String.prototype.contains = function(it) { return this.indexOf(it) != -1; };

function main() {
    console.log('[i] Asking Google for data');

    var calanderUrl = "https://www.googleapis.com/calendar/v3/calendars/" + config.calendarId + "@group.calendar.google.com/events?orderBy=startTime&singleEvents=true&timeMin=" + new Date().toISOString() +
        "&fields=items(start%2Csummary)%2Csummary&key=" + config.apiKey + "&maxResults=" + config.maxResults;

    var https = require('https');

    https.get(calanderUrl, function (res) {
        console.log("[i] got statusCode: ", res.statusCode);

        var data = '';

        res.on('data', function(chunk) {
            data += chunk;
        });

        res.on('end', function () {
            var obj = JSON.parse(data);
            onHttpReturn(obj);
        });

    }).on('error', function (e) {
        console.log("[!] " + e.message);
        // it shouldn't cycle :>
        // yeah i know, it's stupid
        // why not fix it for me?
        main();
    });
}

function onHttpReturn(obj) {
    hasEvents = true;

    console.log("[i] Number of events found: " + obj.items.length);
    console.log("[i] Time of first event: " + obj.items[0].start.dateTime);

    for (var i = 0; i < obj.items.length; i++) {
        var title = obj.items[i].summary;
        var time = obj.items[i].start.dateTime;
        var eventDate = new Date(time);
        var frequency = extractFrequency(title);
        var theEvent = {
            "eventDate": eventDate,
            "title": title,
            "frequency": frequency
        };
        events.push(theEvent);
    }

    if (hasEvents) {
        onReady();
    }
}

function onReady() {
    console.log('[i] starting main system');
    schedAnnounce = setTimeout(nextAnnouncement, 1);
}

function nextAnnouncement() {
    var next = getNextEvent(false);

    if (next === -1) {
        console.log('[i] restarting');
        hasEvents = false;
        events = [];
        clearTimeout(schedNext);
        clearTimeout(schedAnnounce);
        main();
        return false;
    }

    var time = next.getTime() - (new Date()).getTime();
    schedNext = setTimeout(cmdNext, time - config.announceEarly);

    console.log('[i] scheduler event cmdNext added for ' + next.toISOString());
}

function cmdNext(recursion) {
    recursion = typeof recursion !== 'undefined' ? recursion : true;
    var next = getNextEvent();

    if (next === -1) {
        console.log('[i] restarting');
        hasEvents = false;
        events = [];
        clearTimeout(schedNext);
        clearTimeout(schedAnnounce);
        main();
        return false;
    }

    if (recursion) {
        var next = getNextEvent(false);
        var time = next.getTime() - (new Date()).getTime();
        schedAnnounce = setTimeout(nextAnnouncement, time + 1 * 60000);

        console.log('[i] scheduler event nextAnnouncement added for ' + next.toISOString());
    }
}

function extractFrequency(textToMatch) {
    var digitsRe = '([0-9]*k|[0-9]* k)';
    var exp = new RegExp(digitsRe);
    var expResult = exp.exec(textToMatch);

    if (expResult !== null) {
      expResult = expResult[0].substring(0, expResult[0].length - 1);
      return expResult;
    }
}

// Based on original events code written by foo (UTwente-Usability/events.js)
function getNextEvent(humanReadable) {
    humanReadable = typeof humanReadable !== 'undefined' ? humanReadable : true;

     var eventToCheck = events[0];
     while (eventToCheck != null && eventToCheck.eventDate < new Date()) {
        events.shift();
        eventToCheck = events[0];
     }

    var nextEvents = [];
    var prevEvent;

    for (i = 0; i < events.length; i++) {
        var thisEvent = events[i];
        if (prevEvent == null) {
            prevEvent = thisEvent;
            nextEvents.push(prevEvent);
            continue;
        }

        if (prevEvent.eventDate.toISOString() == thisEvent.eventDate.toISOString()) {
            nextEvents.push(thisEvent);
        } else {
            break;
        }
    }

    if (events.length < 3) {
        return -1;
    }

    var returnVal = "";

    if (humanReadable) {
        for (var eventId = 0; eventId < nextEvents.length; eventId++) {

            if (typeof nextEvents[eventId].frequency !== 'undefined' && nextEvents[eventId].frequency.length > 3) {

              var searchStr = nextEvents[eventId].title.toUpperCase();
              if (searchStr.contains("PACIFIC") || searchStr.contains("AMERICA")) {
                  continue;
              }

              if (searchStr.contains("M08A")) {
                  continue;
              }

              var next = moment(nextEvents[eventId].eventDate);

              var length = 15 * 1000 * 60; // 15min
              var convertedTitle = urlify(nextEvents[eventId].title);
              var freq = nextEvents[eventId].frequency;
              var hi, lo;

              if (searchStr.contains("LSB")) {
                lo = -3.7;
                hi = -0.15;
              } else if (searchStr.contains("CW")) {
                lo = 0.3;
                hi = 2.7;
                freq = freq - 1;
              } else {
                lo = 0.15;
                hi = 3.7;
              }

              if (searchStr.contains("RTTY")) {
                freq = freq - 1;
              }

              if (searchStr.contains("F01") || searchStr.contains("F06")) {
                  length = 5 * 1000 * 60; // 5min
              }

              if (searchStr.contains("F11")) {
                  length = 1 * 1000 * 60; // 1min
	      }

              if (searchStr.contains("XPA") || searchStr.contains("XPA2")) {
                  length = 5 * 1000 * 60; // 5min
              }

              if (searchStr.contains("HM01")) {
                  length = 25 * 1000 * 60; // 25min
		  continue;
              }

	      if (searchStr.contains("E11") || searchStr.contains("E11A") || searchStr.contains("S11A")) {
		  length = 13 * 1000 * 60; // 13min
	      }

	      if (searchStr.contains("S06") || searchStr.contains("E07")) {
		  length = 16 * 1000 * 60; // 16min
	      }

	      if (searchStr.contains("E06") || searchStr.contains("G06")) {
		  length = 25 * 1000 * 60; // 25min
	      }

              if (searchStr.contains("E07A")) {
                  length = 10 * 1000 * 60; // 10min
              }

              if (searchStr.contains("M01B")) {
                  length = 20 * 1000 * 60; // 20min
              }

              if (searchStr.contains("S06S") || searchStr.contains("E17Z")) {
                  length = 10 * 1000 * 60; // 10min
              }

              var storageDir = '/opt/recordara/output/' + next.utc().format('YYYY-MM-DD') + '/';

              spawn('mkdir', ['-p', storageDir], {
                detached: true
              });

              var uno = spawn('/usr/bin/nodejs', ['/opt/recordara/grab.js', freq, storageDir + next.utc().format('HH-mm') + '-' + convertedTitle, length, lo, hi], {
                detached: true
              });

              var dos = spawn('/usr/bin/nodejs', ['/opt/recordara/grab_finish.js', freq, storageDir + next.utc().format('HH-mm') + '-' + convertedTitle, length, lo, hi], {
                detached: true
              });

uno.on('close', (code) => {
//  console.log(`child process exited with code ${code}`);

});

dos.on('close', (code) => {
//  console.log(`child process exited with code ${code}`);

setTimeout(function() {

filename=next.utc().format('HH-mm') + '-' + convertedTitle;
iFilename = storageDir + next.utc().format('HH-mm') + '-' + convertedTitle;

    var duration = parseInt(spawnSync('soxi', ['-D', iFilename + '_sil.wav']).stdout.toString().split(".").slice(0,1));
    duration = duration+10;
    if (duration < 20) {

    fs.unlink(iFilename + '.wav');
    fs.unlink(iFilename + '_sil.wav');

    return false;
}

    if (duration < 100) {
      duration = 100;
    }

    spawnSync('ffmpeg', ['-i', iFilename + '.wav', '-ss', '0', '-t', duration, '-acodec', 'copy', iFilename + '_cut.wav'], {});

    spawnSync('sox', [iFilename + '_cut.wav', '-r', '16000', iFilename + '_r16_cut.wav'], {});

    spawnSync('fdkaac', ['-p5', '-b10', '-o', iFilename + '.m4a', iFilename + '_r16_cut.wav'], {});

    spawnSync('sox', [iFilename + '_cut.wav', '-n', 'spectrogram', '-o', iFilename + '.png', '-c', 'recordara.hetmer.net', '-t', filename, '-x', duration*5, '-z', '70'], {});

    fs.unlink(iFilename + '.wav');
    fs.unlink(iFilename + '_cut.wav');
    fs.unlink(iFilename + '_sil.wav');
    fs.unlink(iFilename + '_r16_cut.wav');

}, 600000);

});

            }

        }
    } else {
        // here we assume that only date parsing is needed
        returnVal = nextEvents[0].eventDate;
    }

    return returnVal;
}

main();
<commit_msg>sss upload<commit_after>// recordara 0.1
// WebSDR Automatic Recorder
// Licensed under MIT.

var config = require('./config');
var urlify = require('urlify').create();
var moment = require('moment');
var spawn = require('child_process').spawn;
var spawnSync = require('child_process').spawnSync;
var fs = require('fs');

var hasEvents = false;
var events = [];

var schedNext;
var schedAnnounce;

String.prototype.contains = function(it) { return this.indexOf(it) != -1; };

function main() {
    console.log('[i] Asking Google for data');

    var calanderUrl = "https://www.googleapis.com/calendar/v3/calendars/" + config.calendarId + "@group.calendar.google.com/events?orderBy=startTime&singleEvents=true&timeMin=" + new Date().toISOString() +
        "&fields=items(start%2Csummary)%2Csummary&key=" + config.apiKey + "&maxResults=" + config.maxResults;

    var https = require('https');

    https.get(calanderUrl, function (res) {
        console.log("[i] got statusCode: ", res.statusCode);

        var data = '';

        res.on('data', function(chunk) {
            data += chunk;
        });

        res.on('end', function () {
            var obj = JSON.parse(data);
            onHttpReturn(obj);
        });

    }).on('error', function (e) {
        console.log("[!] " + e.message);
        // it shouldn't cycle :>
        // yeah i know, it's stupid
        // why not fix it for me?
        main();
    });
}

function onHttpReturn(obj) {
    hasEvents = true;

    console.log("[i] Number of events found: " + obj.items.length);
    console.log("[i] Time of first event: " + obj.items[0].start.dateTime);

    for (var i = 0; i < obj.items.length; i++) {
        var title = obj.items[i].summary;
        var time = obj.items[i].start.dateTime;
        var eventDate = new Date(time);
        var frequency = extractFrequency(title);
        var theEvent = {
            "eventDate": eventDate,
            "title": title,
            "frequency": frequency
        };
        events.push(theEvent);
    }

    if (hasEvents) {
        onReady();
    }
}

function onReady() {
    console.log('[i] starting main system');
    schedAnnounce = setTimeout(nextAnnouncement, 1);
}

function nextAnnouncement() {
    var next = getNextEvent(false);

    if (next === -1) {
        console.log('[i] restarting');
        hasEvents = false;
        events = [];
        clearTimeout(schedNext);
        clearTimeout(schedAnnounce);
        main();
        return false;
    }

    var time = next.getTime() - (new Date()).getTime();
    schedNext = setTimeout(cmdNext, time - config.announceEarly);

    console.log('[i] scheduler event cmdNext added for ' + next.toISOString());
}

function cmdNext(recursion) {
    recursion = typeof recursion !== 'undefined' ? recursion : true;
    var next = getNextEvent();

    if (next === -1) {
        console.log('[i] restarting');
        hasEvents = false;
        events = [];
        clearTimeout(schedNext);
        clearTimeout(schedAnnounce);
        main();
        return false;
    }

    if (recursion) {
        var next = getNextEvent(false);
        var time = next.getTime() - (new Date()).getTime();
        schedAnnounce = setTimeout(nextAnnouncement, time + 1 * 60000);

        console.log('[i] scheduler event nextAnnouncement added for ' + next.toISOString());
    }
}

function extractFrequency(textToMatch) {
    var digitsRe = '([0-9]*k|[0-9]* k)';
    var exp = new RegExp(digitsRe);
    var expResult = exp.exec(textToMatch);

    if (expResult !== null) {
      expResult = expResult[0].substring(0, expResult[0].length - 1);
      return expResult;
    }
}

// Based on original events code written by foo (UTwente-Usability/events.js)
function getNextEvent(humanReadable) {
    humanReadable = typeof humanReadable !== 'undefined' ? humanReadable : true;

     var eventToCheck = events[0];
     while (eventToCheck != null && eventToCheck.eventDate < new Date()) {
        events.shift();
        eventToCheck = events[0];
     }

    var nextEvents = [];
    var prevEvent;

    for (i = 0; i < events.length; i++) {
        var thisEvent = events[i];
        if (prevEvent == null) {
            prevEvent = thisEvent;
            nextEvents.push(prevEvent);
            continue;
        }

        if (prevEvent.eventDate.toISOString() == thisEvent.eventDate.toISOString()) {
            nextEvents.push(thisEvent);
        } else {
            break;
        }
    }

    if (events.length < 3) {
        return -1;
    }

    var returnVal = "";

    if (humanReadable) {
        for (var eventId = 0; eventId < nextEvents.length; eventId++) {

            if (typeof nextEvents[eventId].frequency !== 'undefined' && nextEvents[eventId].frequency.length > 3) {

              var searchStr = nextEvents[eventId].title.toUpperCase();
              if (searchStr.contains("PACIFIC") || searchStr.contains("AMERICA")) {
                  continue;
              }

              if (searchStr.contains("M08A")) {
                  continue;
              }

              var next = moment(nextEvents[eventId].eventDate);

              var length = 15 * 1000 * 60; // 15min
              var convertedTitle = urlify(nextEvents[eventId].title);
              var freq = nextEvents[eventId].frequency;
              var hi, lo;

              if (searchStr.contains("LSB")) {
                lo = -3.7;
                hi = -0.15;
              } else if (searchStr.contains("CW")) {
                lo = 0.3;
                hi = 2.7;
                freq = freq - 1;
              } else {
                lo = 0.15;
                hi = 3.7;
              }

              if (searchStr.contains("RTTY")) {
                freq = freq - 1;
              }

              if (searchStr.contains("F01") || searchStr.contains("F06")) {
                  length = 10 * 1000 * 60; // 10min
              }

              if (searchStr.contains("F11")) {
                  length = 1 * 1000 * 60; // 1min
	      }

              if (searchStr.contains("XPA") || searchStr.contains("XPA2")) {
                  length = 5 * 1000 * 60; // 5min
              }

              if (searchStr.contains("HM01")) {
                  length = 25 * 1000 * 60; // 25min
		  continue;
              }

	      if (searchStr.contains("E11") || searchStr.contains("E11A") || searchStr.contains("S11A")) {
		  length = 13 * 1000 * 60; // 13min
	      }

	      if (searchStr.contains("S06") || searchStr.contains("E07")) {
		  length = 16 * 1000 * 60; // 16min
	      }

	      if (searchStr.contains("E06") || searchStr.contains("G06")) {
		  length = 25 * 1000 * 60; // 25min
	      }

              if (searchStr.contains("E07A")) {
                  length = 10 * 1000 * 60; // 10min
              }

              if (searchStr.contains("M01B")) {
                  length = 20 * 1000 * 60; // 20min
              }

              if (searchStr.contains("S06S") || searchStr.contains("E17Z")) {
                  length = 10 * 1000 * 60; // 10min
              }

              var storageDir = '/opt/recordara/output/' + next.utc().format('YYYY-MM-DD') + '/';

              spawn('mkdir', ['-p', storageDir], {
                detached: true
              });

              var uno = spawn('/usr/bin/nodejs', ['/opt/recordara/grab.js', freq, storageDir + next.utc().format('HH-mm') + '-' + convertedTitle, length, lo, hi], {
                detached: true
              });

              var dos = spawn('/usr/bin/nodejs', ['/opt/recordara/grab_finish.js', freq, storageDir + next.utc().format('HH-mm') + '-' + convertedTitle, length, lo, hi], {
                detached: true
              });

uno.on('close', (code) => {
//  console.log(`child process exited with code ${code}`);

});

dos.on('close', (code) => {
//  console.log(`child process exited with code ${code}`);

setTimeout(function() {

try {
filename=next.utc().format('YYYY-MM-DD') + '/' + next.utc().format('HH-mm') + '-' + convertedTitle;
iFilename = storageDir + next.utc().format('HH-mm') + '-' + convertedTitle;

    var duration_sil = parseInt(spawnSync('soxi', ['-D', iFilename + '_sil.wav']).stdout.toString().split(".").slice(0,1));
    var duration_full = parseInt(spawnSync('soxi', ['-D', iFilename + '.wav']).stdout.toString().split(".").slice(0,1));
    var diff = duration_full - duration_sil;
    var duration = duration_full - diff;

    if (duration < 20) {

    fs.unlinkSync(iFilename + '.wav');
    fs.unlinkSync(iFilename + '_sil.wav');

    return false;
}

    if (diff > 10) {
      duration = duration + 10;
    }

    spawnSync('ffmpeg', ['-i', iFilename + '.wav', '-ss', '0', '-t', duration, '-acodec', 'copy', iFilename + '_cut.wav'], {});

    if (duration < 100) {
      duration = 100;
    }

    spawnSync('sox', [iFilename + '_cut.wav', '-r', '16000', iFilename + '_r16_cut.wav'], {});

    spawnSync('fdkaac', ['-p5', '-m1', '-o', iFilename + '.m4a', iFilename + '_r16_cut.wav'], {});

    spawnSync('sox', [iFilename + '_cut.wav', '-n', 'spectrogram', '-o', iFilename + '.png', '-c', 'recordara.hetmer.net', '-t', filename, '-x', duration*5, '-z', '70'], {});

    fs.unlinkSync(iFilename + '.wav');
    fs.unlinkSync(iFilename + '_cut.wav');
    fs.unlinkSync(iFilename + '_sil.wav');
    fs.unlinkSync(iFilename + '_r16_cut.wav');

fs.appendFile('/opt/recordara/synclist', iFilename + '\n', function (err) {
  if (err) throw err;
  console.log('Saved!');
});

}
catch (e) {
  console.log("entering catch block");
  console.log(e);
  console.log("leaving catch block");
}

}, 600000);

});

            }

        }
    } else {
        // here we assume that only date parsing is needed
        returnVal = nextEvents[0].eventDate;
    }

    return returnVal;
}

main();
<|endoftext|>


<commit_before>
var brain =["hi",];

_mood = ['very good, thank you', 'not very good', 'fair', 'iffy', 'Awesome!', 'Good, thank you', 'Ready to Rock',];
mood = _mood[Math.floor(Math.random() * 7)];

//change this if we have longer commands.
annyang.start({continuous: true});

function save_data(){
    var input = document.getElementById("fname");
    localStorage.setItem("fname", input.value);
}
var firstname = localStorage.getItem("fname");

annyang.addCallback('resultNoMatch', function(){document.getElementById("#resultplace").innerHTML = "Say that again.";});
function speak (phrase) {
    var worte = new SpeechSynthesisUtterance(phrase);
    worte.lang = "en-GB";
    window.speechSynthesis.speak(worte);
};

// Just a list of functions that anyone can call
// you can call these in the console by typing actions.YourFunctioName()
var actions = {

    youtube: function (term) {
        if (mood == 'iffy' || mood == "not very good") {
            speak("no")
            document.getElementById('#resultplace').innerHTML = "no";
        }
        else {
            window.location.href = 'https://www.youtube.com/results?search_query='+term;
        }
    },
    //youtube: function (term) {
    //    speak(term)
    //},

    google: function (term) {
        if (mood == 'iffy' || mood == "not very good") {
            speak("no")
            document.getElementById('#resultplace').innerHTML = "no";
        }
        else {
            window.location.href = 'https://www.google.com/#q='+term;
        }
    },
    d20: function () {
        var d20 = Math.floor(Math.random() * 20);

        speak(d20);
        document.getElementById("#resultplace").innerHTML = d20;
    },
    testcode: function() {

        newcommand = prompt("Wanted code");
        if (newcommand.indexOf("document.getElementById") >= 0) {
            alert("Not allowed");

        }
        else if (newcommand.indexOf("document.getItem") >= 0) {
            alert("Not allowed");

        }

        else {
            eval(newcommand);
        }

    },
    reminder: function(term) {
        localStorage.setItem("reminder", term);
        speak('Saved to my memory')
        document.getElementById('#resultplace').innerHTML = "Saved to my memory";
        /*        function remindData(){
        var info = term;
        localStorage.setItem("Rinfo", info);
    }
    rememberThing = localStorage.getItem("Rinfo");
    speak('Saved to my memory')*/
},
remeberCommand: function() {
    rememberThing = localStorage.getItem("reminder");
    //speak("you asked me to remeber " + rememberThing)
    //document.getElementById('#resultplace').innerHTML = "you asked me to remeber " + rememberThing;
    for(var i=0, len=localStorage.length; i<len; i++) {
    var key = localStorage.key(i);
    var value = localStorage[key];
    speak("you asked me to remeber " value)
    document.getElementById('#resultplace').innerHTML = key + " => " + value
}
},
d6: function () {
    var d6 = Math.floor(Math.random() * 6);
    speak(d6);
    document.getElementById("#resultplace").innerHTML = d6;
},
diceroll1: function (term) {

    if (mood == 'iffy' || mood == "not very good") {
        speak("no")
        document.getElementById('#resultplace').innerHTML = "no";
    }
    else {
        var diceroll2 = Math.floor(Math.random() * term);
        speak(diceroll2);
        document.getElementById("#resultplace").innerHTML = diceroll2;
    }
},

wolfram: function(term) {
    $.get("https://api.wolframalpha.com/v2/query?input="+term+"&appid=THYQLJ-3K45Y2A7W5"), function(wolfram__) {
        speak(wolfram__);
    };
    //http://api.wolframalpha.com/v2/query?input=pi&appid=XXXX
    //var wolfram_ = "http://api.wolframalpha.com/v2/query?input="+term+"&appid=THYQLJ-3K45Y2A7W5";
    //speak(wolfram_);
},
weather: function (term) {
    $.get('https://api.openweathermap.org/data/2.5/weather?q='+term, function (theweather) {
        speak(theweather.temp);

    });

},
badAsk: function() {
    if (mood == 'not very good' || mood == 'iffy') {
        _askBad = ['its not about me', 'nothing'];
        askBad = _askBad[Math.floor(Math.random() * 2)];
        speak(askBad);
        document.getElementById("#resultplace").innerHTML = askBad;
    }
    else {}
},

mood: function() {
    _mood = ['very good, thank you', 'not very good', 'fair', 'iffy', 'Awesome!', 'Good, thank you', 'Ready to Rock',];
    mood = _mood[Math.floor(Math.random() * 7)];

},

howu: function () {

    speak(mood);
    document.getElementById("#resultplace").innerHTML = mood;

},

};

function on() {
    speak("now listening")
}

// bind all of our spoken commands to the actions
if (annyang) {
    annyang.setLanguage('en-GB');

    // Define the triggers for the commands
    var commands = {
        '(hello)(hi)(hey)': function() {
            speak('hello ');
            document.getElementById("#resultplace").innerHTML = "hello ";
        },

        '(Who made you)(Who created you) (who is your creator) ': function() {
            speak('sam bolton');
            document.getElementById("#resultplace").innerHTML = "sam bolton";
        },
        '(hey aubrey)(aubrey) (ok aubrey)': function() {
            speak('Ready, sir');
            document.getElementById("#resultplace").innerHTML = "Ready, sir";

        },
        '(thats good) (that is good)': function() {
            speak('good');
            document.getElementById("#resultplace").innerHTML = "good";
        },

        '(shutup) (shut up) (pause) (be quit) (go to sleep) (stop)': function() {
            if (mood == 'iffy' || mood == "not very good") {
                speak("no")
                document.getElementById('#resultplace').innerHTML = "no";
            }
            else {
                annyang.pause();
                annyang.removeCommands();
                annyang.addCommands(commands2);
                annyang.resume();
                document.getElementById("#resultplace").innerHTML = "Paused";
            }
        },

        '(hey aubrey can you) (can you) youtube *term': actions.youtube,
        '(hey aubrey can you) (can you) search *term': actions.google,
        '(hey aubrey can you) (can you) google *term': actions.google,
        'roll a d20': actions.d20,
        'roll a d6': actions.d6,
        //    'What is *term': actions.wolfram,
        'what is the weather in *term': actions.weather,
        '(how are you) (you good) (are you alright)': actions.howu,
        'roll a d *term': actions.diceroll1,
        'remember (for me) *term' : actions.reminder,
        'list reminders' : actions.remeberCommand,
        '(whats wrong) (whats up)(what is up)' : actions.badAsk,
        'code test' : actions.testcode,

    };
    var commands2 = {
        //this is for the pause function only!
        '(wake up)(resume)(aubry wakeup)(start)': function() {
            annyang.pause();
            annyang.removeCommands();
            annyang.addCommands(commands);
            annyang.resume();
            document.getElementById("#resultplace").innerHTML = "Resumed";
        }

    }
    // take our list of commands and stick them all in
    annyang.addCommands(commands);
}

window.setInterval(function() {
    actions.mood()

}, 60000);
<commit_msg>multiple reminders added (with bugs)<commit_after>
var brain =["hi",];

_mood = ['very good, thank you', 'not very good', 'fair', 'iffy', 'Awesome!', 'Good, thank you', 'Ready to Rock',];
mood = _mood[Math.floor(Math.random() * 7)];

//change this if we have longer commands.
annyang.start({continuous: true});

function save_data(){
    var input = document.getElementById("fname");
    localStorage.setItem("fname", input.value);
}
var firstname = localStorage.getItem("fname");

annyang.addCallback('resultNoMatch', function(){document.getElementById("#resultplace").innerHTML = "Say that again.";});
function speak (phrase) {
    var worte = new SpeechSynthesisUtterance(phrase);
    worte.lang = "en-GB";
    window.speechSynthesis.speak(worte);
};

// Just a list of functions that anyone can call
// you can call these in the console by typing actions.YourFunctioName()
var actions = {

    youtube: function (term) {
        if (mood == 'iffy' || mood == "not very good") {
            speak("no")
            document.getElementById('#resultplace').innerHTML = "no";
        }
        else {
            window.location.href = 'https://www.youtube.com/results?search_query='+term;
        }
    },
    //youtube: function (term) {
    //    speak(term)
    //},

    google: function (term) {
        if (mood == 'iffy' || mood == "not very good") {
            speak("no")
            document.getElementById('#resultplace').innerHTML = "no";
        }
        else {
            window.location.href = 'https://www.google.com/#q='+term;
        }
    },
    d20: function () {
        var d20 = Math.floor(Math.random() * 20);

        speak(d20);
        document.getElementById("#resultplace").innerHTML = d20;
    },
    testcode: function() {

        newcommand = prompt("Wanted code");
        if (newcommand.indexOf("document.getElementById") >= 0) {
            alert("Not allowed");

        }
        else if (newcommand.indexOf("document.getItem") >= 0) {
            alert("Not allowed");

        }

        else {
            eval(newcommand);
        }

    },
    reminder: function(term, ReminderName) {
        localStorage.setItem(ReminderName, term);
        RememberName = ReminderName;
        speak('Saved to my memory')
        document.getElementById('#resultplace').innerHTML = "Saved to my memory";
        /*        function remindData(){
        var info = term;
        localStorage.setItem("Rinfo", info);
    }
    rememberThing = localStorage.getItem("Rinfo");
    speak('Saved to my memory')*/
},
remeberCommand: function() {
    //rememberThing = localStorage.getItem("reminder");
    //speak("you asked me to remeber " + rememberThing)
    //document.getElementById('#resultplace').innerHTML = "you asked me to remeber " + rememberThing;
    for(var i=0, len=localStorage.length; i<len; i++) {
        var key = localStorage.key(i);
        var value = localStorage[key];
        speak("you asked me to remeber " + value);
        document.getElementById('#resultplace').innerHTML = key + " => " + value;
    }
},
d6: function () {
    var d6 = Math.floor(Math.random() * 6);
    speak(d6);
    document.getElementById("#resultplace").innerHTML = d6;
},
diceroll1: function (term) {

    if (mood == 'iffy' || mood == "not very good") {
        speak("no")
        document.getElementById('#resultplace').innerHTML = "no";
    }
    else {
        var diceroll2 = Math.floor(Math.random() * term);
        speak(diceroll2);
        document.getElementById("#resultplace").innerHTML = diceroll2;
    }
},

wolfram: function(term) {
    $.get("https://api.wolframalpha.com/v2/query?input="+term+"&appid=THYQLJ-3K45Y2A7W5"), function(wolfram__) {
        speak(wolfram__);
    };
    //http://api.wolframalpha.com/v2/query?input=pi&appid=XXXX
    //var wolfram_ = "http://api.wolframalpha.com/v2/query?input="+term+"&appid=THYQLJ-3K45Y2A7W5";
    //speak(wolfram_);
},
weather: function (term) {
    $.get('https://api.openweathermap.org/data/2.5/weather?q='+term, function (theweather) {
        speak(theweather.temp);

    });

},
badAsk: function() {
    if (mood == 'not very good' || mood == 'iffy') {
        _askBad = ['its not about me', 'nothing'];
        askBad = _askBad[Math.floor(Math.random() * 2)];
        speak(askBad);
        document.getElementById("#resultplace").innerHTML = askBad;
    }
    else {}
},

mood: function() {
    _mood = ['very good, thank you', 'not very good', 'fair', 'iffy', 'Awesome!', 'Good, thank you', 'Ready to Rock',];
    mood = _mood[Math.floor(Math.random() * 7)];

},

howu: function () {

    speak(mood);
    document.getElementById("#resultplace").innerHTML = mood;

},

};

function on() {
    speak("now listening")
}

// bind all of our spoken commands to the actions
if (annyang) {
    annyang.setLanguage('en-GB');

    // Define the triggers for the commands
    var commands = {
        '(hello)(hi)(hey)': function() {
            speak('hello ');
            document.getElementById("#resultplace").innerHTML = "hello ";
        },

        '(Who made you)(Who created you) (who is your creator) ': function() {
            speak('sam bolton');
            document.getElementById("#resultplace").innerHTML = "sam bolton";
        },
        '(hey aubrey)(aubrey) (ok aubrey)': function() {
            speak('Ready, sir');
            document.getElementById("#resultplace").innerHTML = "Ready, sir";

        },
        '(thats good) (that is good)': function() {
            speak('good');
            document.getElementById("#resultplace").innerHTML = "good";
        },

        '(shutup) (shut up) (pause) (be quit) (go to sleep) (stop)': function() {
            if (mood == 'iffy' || mood == "not very good") {
                speak("no")
                document.getElementById('#resultplace').innerHTML = "no";
            }
            else {
                annyang.pause();
                annyang.removeCommands();
                annyang.addCommands(commands2);
                annyang.resume();
                document.getElementById("#resultplace").innerHTML = "Paused";
            }
        },

        '(hey aubrey can you) (can you) youtube *term': actions.youtube,
        '(hey aubrey can you) (can you) search *term': actions.google,
        '(hey aubrey can you) (can you) google *term': actions.google,
        'roll a d20': actions.d20,
        'roll a d6': actions.d6,
        //    'What is *term': actions.wolfram,
        'what is the weather in *term': actions.weather,
        '(how are you) (you good) (are you alright)': actions.howu,
        'roll a d *term': actions.diceroll1,
        'remember (for me) *term *ReminderName' : actions.reminder,
        'list reminders' : actions.remeberCommand,
        '(whats wrong) (whats up)(what is up)' : actions.badAsk,
        'code test' : actions.testcode,

    };
    var commands2 = {
        //this is for the pause function only!
        '(wake up)(resume)(aubry wakeup)(start)': function() {
            annyang.pause();
            annyang.removeCommands();
            annyang.addCommands(commands);
            annyang.resume();
            document.getElementById("#resultplace").innerHTML = "Resumed";
        }

    }
    // take our list of commands and stick them all in
    annyang.addCommands(commands);
}

window.setInterval(function() {
    actions.mood()

}, 60000);
<|endoftext|>


<commit_before>/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, window */

define(function (require, exports, module)
{
    "use strict";

    var EditorManager        = brackets.getModule("editor/EditorManager"),
    ExtensionUtils           = brackets.getModule("utils/ExtensionUtils"),
    Strings                  = brackets.getModule("strings"),
    QuickFormToolTemplate    = require("text!ui/QuickFormToolTemplate.html");

    function quickFormToolProvider()
    {
        try
        {
            var $element = $(Mustache.render(QuickFormToolTemplate, Strings));
            $element.find(".form").click(function () { quickFormTool("form"); });
            $element.find(".textfield").click(function () { quickFormTool("textfield"); });
            $element.find(".textarea").click(function () { quickFormTool("textarea"); });
            $element.find(".button").click(function () { quickFormTool("button"); });
            $element.find(".checkbox").click(function () { quickFormTool("checkbox"); });
            $element.find(".radiobutton").click(function () { quickFormTool("radiobutton"); });
            $element.find(".listmenu").click(function () { quickFormTool("listmenu"); });
            $element.find(".imagefield").click(function () { quickFormTool("imagefield"); });
            $element.find(".filefield").click(function () { quickFormTool("filefield"); });
            $element.find(".hiddenfiled").click(function () { quickFormTool("hiddenfiled"); });

            $($element).insertBefore("#editor-holder");
        }
        catch(e)
        {
            alert("Error: " + e);
        }
    }
    var loadfunction = quickFormToolProvider();
    function quickFormTool(_class)
    {
        try
    {
            EditorManager.focusEditor();
            var hosteditor = EditorManager.getFocusedEditor();
            if (hosteditor)
            {
                var htmlcode = "";
                switch (_class)
                {
                    case "form":
                        htmlcode = "<form action=\"\" method=\"get\"></form>";
                    break;

                    case "textfield":
                        htmlcode = "<input name=\"\" type=\"text\" />";
                    break;

                    case "textarea":
                        htmlcode = "<textarea name=\"\" cols=\"\" rows=\"\"></textarea>";
                    break;

                    case "button":
                        htmlcode = "<input name=\"\" type=\"button\" />";
                    break;

                    case "checkbox":
                        htmlcode = "<input name=\"\" type=\"checkbox\" value=\"\" />";
                    break;

                    case "radiobutton":
                        htmlcode = "<input name=\"\" type=\"radio\" value=\"\" />";
                    break;

                    case "listmenu":
                        htmlcode = "<select name=\"\"></select>";
                    break;

                    case "imagefield":
                        htmlcode = "<input name=\"\" type=\"image\" src=\"asd\" align=\"middle\" width=\"\" height=\"\" />";
                    break;

                    case "filefield":
                        htmlcode = "<input name=\"\" type=\"file\" />";
                    break;

                    case "hiddenfiled":
                        htmlcode = "<input name=\"\" type=\"hidden\" value=\"\" />";
                    break;
                }
                hosteditor.document.replaceRange(htmlcode, hosteditor.getCursorPos());
            }
        }
        catch(e)
        {
            alert("Error: " + e);
        }
    };

    ExtensionUtils.loadStyleSheet(module, "ui/style.css");
    exports.quickFormToolProvider = quickFormToolProvider;
});
<commit_msg>Fix hidden field typo<commit_after>/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, window */

define(function (require, exports, module)
{
    "use strict";

    var EditorManager        = brackets.getModule("editor/EditorManager"),
    ExtensionUtils           = brackets.getModule("utils/ExtensionUtils"),
    Strings                  = brackets.getModule("strings"),
    QuickFormToolTemplate    = require("text!ui/QuickFormToolTemplate.html");

    function quickFormToolProvider()
    {
        try
        {
            var $element = $(Mustache.render(QuickFormToolTemplate, Strings));
            $element.find(".form").click(function () { quickFormTool("form"); });
            $element.find(".textfield").click(function () { quickFormTool("textfield"); });
            $element.find(".textarea").click(function () { quickFormTool("textarea"); });
            $element.find(".button").click(function () { quickFormTool("button"); });
            $element.find(".checkbox").click(function () { quickFormTool("checkbox"); });
            $element.find(".radiobutton").click(function () { quickFormTool("radiobutton"); });
            $element.find(".listmenu").click(function () { quickFormTool("listmenu"); });
            $element.find(".imagefield").click(function () { quickFormTool("imagefield"); });
            $element.find(".filefield").click(function () { quickFormTool("filefield"); });
            $element.find(".hiddenfield").click(function () { quickFormTool("hiddenfield"); });

            $($element).insertBefore("#editor-holder");
        }
        catch(e)
        {
            alert("Error: " + e);
        }
    }
    var loadfunction = quickFormToolProvider();
    function quickFormTool(_class)
    {
        try
    {
            EditorManager.focusEditor();
            var hosteditor = EditorManager.getFocusedEditor();
            if (hosteditor)
            {
                var htmlcode = "";
                switch (_class)
                {
                    case "form":
                        htmlcode = "<form action=\"\" method=\"get\"></form>";
                    break;

                    case "textfield":
                        htmlcode = "<input name=\"\" type=\"text\" />";
                    break;

                    case "textarea":
                        htmlcode = "<textarea name=\"\" cols=\"\" rows=\"\"></textarea>";
                    break;

                    case "button":
                        htmlcode = "<input name=\"\" type=\"button\" />";
                    break;

                    case "checkbox":
                        htmlcode = "<input name=\"\" type=\"checkbox\" value=\"\" />";
                    break;

                    case "radiobutton":
                        htmlcode = "<input name=\"\" type=\"radio\" value=\"\" />";
                    break;

                    case "listmenu":
                        htmlcode = "<select name=\"\"></select>";
                    break;

                    case "imagefield":
                        htmlcode = "<input name=\"\" type=\"image\" src=\"asd\" align=\"middle\" width=\"\" height=\"\" />";
                    break;

                    case "filefield":
                        htmlcode = "<input name=\"\" type=\"file\" />";
                    break;

                    case "hiddenfield":
                        htmlcode = "<input name=\"\" type=\"hidden\" value=\"\" />";
                    break;
                }
                hosteditor.document.replaceRange(htmlcode, hosteditor.getCursorPos());
            }
        }
        catch(e)
        {
            alert("Error: " + e);
        }
    };

    ExtensionUtils.loadStyleSheet(module, "ui/style.css");
    exports.quickFormToolProvider = quickFormToolProvider;
});
<|endoftext|>