<commit_before>define(function (require) {

    "use strict";

    var $                       = require('jquery'),
        _                       = require('underscore'),
        Backbone                = require('backbone'),
        SongListItemView    	= require('app/views/SongListItem');

    return Backbone.View.extend({

    	tagName: 'ul',

        initialize: function () {
        	console.log("SongList: Init");
        	this.collection.on("reset", this.render, this);
            this.collection.on("add", this.render, this);
        },

        render: function () {
        	this.$el.empty().addClass('list-group');
		    _.each(this.collection.models, function (song) {
            	this.$el.append(new SongListItemView({model: song}).render().el);
            }, this);

            return this;
        }
    });

});

<commit_msg>SongList: Render only the required elements<commit_after>define(function (require) {

    "use strict";

    var $                       = require('jquery'),
        _                       = require('underscore'),
        Backbone                = require('backbone'),
        SongListItemView    	= require('app/views/SongListItem');

    return Backbone.View.extend({

    	tagName: 'ul',

        initialize: function () {
        	console.log("SongList: Init");
        	this.collection.on("reset", this.render, this);
            this.collection.on("add", this.renderOne, this);
        },

        render: function () {
        	this.$el.empty().addClass('list-group');
		    _.each(this.collection.models, function (song) {
            	this.$el.append(new SongListItemView({model: song}).render().el);
            }, this);

            return this;
       },

       renderOne: function (model) {
       		this.$el.append(new SongListItemView({model: model}).render().el);
            return this;
        }
    });

});

<|endoftext|>


<commit_before>var xmlrpc = require('xmlrpc'),
Url = require('url');

function api(host) {
  var hostParts = {};

  if(typeof host == 'string')
  {
      if (host.indexOf('http') !== 0) {
          host = 'http://' + host;
      }
      hostParts = Url.parse(host);

      if(hostParts.auth)
      {
          var authParts = hostParts.auth.split(':');
          hostParts.user = authParts[0];
          hostParts.pass = authParts[1];
      }
  }
  else if(host)
  {
      hostParts = host;
  }

  if(!hostParts.hostname) hostParts.hostname = 'localhost';
  if(!hostParts.port) hostParts.port = 9001;

  this.client = xmlrpc.createClient({
      host: hostParts.hostname,
      port: hostParts.port,
      path: '/RPC2',
      basic_auth: {
          user: hostParts.user,
          pass: hostParts.pass
      }
  });
}

api.prototype._call = function(method, args, callback)
{
    this.client.methodCall(method, args, callback);
};

['supervisor.addProcessGroup',
  'supervisor.clearAllProcessLogs',
  'supervisor.clearLog',
  'supervisor.clearProcessLog',
  'supervisor.clearProcessLogs',
  'supervisor.getAPIVersion',
  'supervisor.getAllConfigInfo',
  'supervisor.getAllProcessInfo',
  'supervisor.getIdentification',
  'supervisor.getPID',
  'supervisor.getProcessInfo',
  'supervisor.getState',
  'supervisor.getSupervisorVersion',
  'supervisor.getVersion',
  'supervisor.readLog',
  'supervisor.readMainLog',
  'supervisor.readProcessLog',
  'supervisor.readProcessStderrLog',
  'supervisor.readProcessStdoutLog',
  'supervisor.reloadConfig',
  'supervisor.removeProcessGroup',
  'supervisor.restart',
  'supervisor.sendProcessStdin',
  'supervisor.sendRemoteCommEvent',
  'supervisor.signalProcess',
  'supervisor.signalProcessGroup',
  'supervisor.shutdown',
  'supervisor.startAllProcesses',
  'supervisor.startProcess',
  'supervisor.startProcessGroup',
  'supervisor.stopAllProcesses',
  'supervisor.stopProcess',
  'supervisor.stopProcessGroup',
  'supervisor.tailProcessLog',
  'supervisor.tailProcessStderrLog',
  'supervisor.tailProcessStdoutLog',
  'system.listMethods',
  'system.methodHelp',
  'system.methodSignature',
  'system.multicall'].forEach(function(property){
  api.prototype[property.split('.').pop()] = function(){
    var args = Array.prototype.slice.call(arguments);
    callback = args.pop();
    this._call(property, args, callback);
  };
});

module.exports = api;
<commit_msg>add unix socket support<commit_after>var xmlrpc = require('xmlrpc'),
Url = require('url');

function api(host) {
  var hostParts = {};

  if(typeof host == 'string')
  {
      if (host.indexOf('unix') === 0) {

          hostParts.socketPath = Url.parse(host).pathname;
      }else{
          if (host.indexOf('http') !== 0) {
              host = 'http://' + host;
          }
          hostParts = Url.parse(host);

          if(hostParts.auth)
          {
              var authParts = hostParts.auth.split(':');
              hostParts.user = authParts[0];
              hostParts.pass = authParts[1];
          }
      }
  }
  else if(host)
  {
      hostParts = host;
  }

  if(!hostParts.hostname) hostParts.hostname = 'localhost';
  if(!hostParts.port) hostParts.port = 9001;

  if(hostParts.socketPath){
      this.client = xmlrpc.createClient({
          socketPath: hostParts.socketPath,
          path: '/RPC2',
      });
  }else{
      this.client = xmlrpc.createClient({
          host: hostParts.hostname,
          port: hostParts.port,
          path: '/RPC2',
          basic_auth: {
              user: hostParts.user,
              pass: hostParts.pass
          }
      });
  }
}

api.prototype._call = function(method, args, callback)
{
    this.client.methodCall(method, args, callback);
};

['supervisor.addProcessGroup',
  'supervisor.clearAllProcessLogs',
  'supervisor.clearLog',
  'supervisor.clearProcessLog',
  'supervisor.clearProcessLogs',
  'supervisor.getAPIVersion',
  'supervisor.getAllConfigInfo',
  'supervisor.getAllProcessInfo',
  'supervisor.getIdentification',
  'supervisor.getPID',
  'supervisor.getProcessInfo',
  'supervisor.getState',
  'supervisor.getSupervisorVersion',
  'supervisor.getVersion',
  'supervisor.readLog',
  'supervisor.readMainLog',
  'supervisor.readProcessLog',
  'supervisor.readProcessStderrLog',
  'supervisor.readProcessStdoutLog',
  'supervisor.reloadConfig',
  'supervisor.removeProcessGroup',
  'supervisor.restart',
  'supervisor.sendProcessStdin',
  'supervisor.sendRemoteCommEvent',
  'supervisor.signalProcess',
  'supervisor.signalProcessGroup',
  'supervisor.shutdown',
  'supervisor.startAllProcesses',
  'supervisor.startProcess',
  'supervisor.startProcessGroup',
  'supervisor.stopAllProcesses',
  'supervisor.stopProcess',
  'supervisor.stopProcessGroup',
  'supervisor.tailProcessLog',
  'supervisor.tailProcessStderrLog',
  'supervisor.tailProcessStdoutLog',
  'system.listMethods',
  'system.methodHelp',
  'system.methodSignature',
  'system.multicall'].forEach(function(property){
  api.prototype[property.split('.').pop()] = function(){
    var args = Array.prototype.slice.call(arguments);
    callback = args.pop();
    this._call(property, args, callback);
  };
});

module.exports = api;
<|endoftext|>


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

var deliciousUrl = "http://delicious.com/save?v=5&noui&jump=close&url=";
var url;
var title;

// Listener for messages posted via the content script
chrome.extension.onConnect.addListener(function(port) {
    port.onMessage.addListener(function(data) {
        url = data.url;
        title = data.title;

        // Register the tab with the tagging page action
        chrome.pageActions.enableForTab("tag_page",
                                        {
                                            tabId: port.tab.id,
                                            url: port.tab.url,
                                            title: "Click to tag this page on Delicious",
                                            iconId: 0
                                        });

    });
});

chrome.pageActions["tag_page"].addListener(function(pageActionId, reply) {
    console.log(reply);
    tagCurrentPage();
});

function tagCurrentPage() {
    window.open(deliciousUrl + url + '&title=' + title +' ','deliciousuiv5','location=yes,links=no,scrollbars=no,toolbar=no,width=550,height=550');
};

this._database = window.openDatabase("deliciousDatabase", "0.1", "Delicious Database", 250 * 1024);

if (!this._database) {
    console.log("Error opening database");
}

// Create settings table
this._database.transaction(function(query) {
    query.executeSql('CREATE TABLE settings(id INTEGER PRIMARY KEY AUTOINCREMENT, username VARCHAR(50), password VARCHAR(50))',
                     []);
});

// Write a user
this._database.transaction(function(query) {
    query.executeSql('INSERT INTO settings(username, password) VALUES(?, ?)',
                     ['Scott', 'password'],
                     function(transaction, result) {
                         console.log(result);
                     },
                     function(transaction, error) {
                         console.log(error);
                     });
});

// Read the table
this._database.transaction(function(query) {
    query.executeSql('SELECT * FROM settings',
                     [],
                     function(transaction, result) {
                        console.log(transaction);
                        console.log(result);
                     },
                     function(transaction, error) {
                         console.log(error);
                     });
});
<commit_msg>Fix database reference<commit_after>// Copyright (c) 2009, William Best and Scott Ferguson
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the software nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY WILLIAM BEST AND SCOTT FERGUSON ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL WILLIAM BEST AND SCOTT FERGUSON BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

var deliciousUrl = "http://delicious.com/save?v=5&noui&jump=close&url=";
var url;
var title;

// Listener for messages posted via the content script
chrome.extension.onConnect.addListener(function(port) {
    port.onMessage.addListener(function(data) {
        url = data.url;
        title = data.title;

        // Register the tab with the tagging page action
        chrome.pageActions.enableForTab("tag_page",
                                        {
                                            tabId: port.tab.id,
                                            url: port.tab.url,
                                            title: "Click to tag this page on Delicious",
                                            iconId: 0
                                        });

    });
});

chrome.pageActions["tag_page"].addListener(function(pageActionId, reply) {
    console.log(reply);
    tagCurrentPage();
});

function tagCurrentPage() {
    window.open(deliciousUrl + url + '&title=' + title +' ','deliciousuiv5','location=yes,links=no,scrollbars=no,toolbar=no,width=550,height=550');
};

var database = window.openDatabase("deliciousDatabase", "0.1", "Delicious Database", 250 * 1024);

if (!database) {
    console.log("Error opening database");
}

// Create settings table
database.transaction(function(query) {
    query.executeSql('CREATE TABLE settings(id INTEGER PRIMARY KEY AUTOINCREMENT, username VARCHAR(50), password VARCHAR(50))',
                     []);
});

// Write a user
database.transaction(function(query) {
    query.executeSql('INSERT INTO settings(username, password) VALUES(?, ?)',
                     ['Scott', 'password'],
                     function(transaction, result) {
                         console.log(result);
                     },
                     function(transaction, error) {
                         console.log(error);
                     });
});

// Read the table
database.transaction(function(query) {
    query.executeSql('SELECT * FROM settings',
                     [],
                     function(transaction, result) {
                        console.log(transaction);
                        console.log(result);
                     },
                     function(transaction, error) {
                         console.log(error);
                     });
});
<|endoftext|>


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

var api = new (function () {
  /**
    @name task
    @static
    @function
    @description Creates a Jake Task
    `
    @param {String} name The name of the Task
    @param {Array} [prereqs] Prerequisites to be run before this task
    @param {Function} [action] The action to perform for this task
    @param {Object} [opts]
      @param {Boolean} [opts.asyc=false] Perform this task asynchronously.
      If you flag a task with this option, you must call the global
      `complete` method inside the task's action, for execution to proceed
      to the next task.

    @example
    desc('This is the default task.');
    task('default', function (params) {
      console.log('This is the default task.');
    });

    desc('This task has prerequisites.');
    task('hasPrereqs', ['foo', 'bar', 'baz'], function (params) {
      console.log('Ran some prereqs first.');
    });

    desc('This is an asynchronous task.');
    task('asyncTask', function () {
      setTimeout(complete, 1000);
    }, {async: true});
   */
  this.task = function (name, prereqs, action, opts) {
    var args = Array.prototype.slice.call(arguments);
       var createdTask;
    args.unshift('task');
    createdTask = jake.createTask.apply(global, args);
    jake.currentTaskDescription = null;
    return createdTask;
  };

  /**
    @name rule
    @static
    @function
    @description Creates a Jake Suffix Rule
    `
    @param {String} pattern The suffix name of the objective
    @param {String} source The suffix name of the objective
    @param {Array} [prereqs] Prerequisites to be run before this task
    @param {Function} [action] The action to perform for this task
    @param {Object} [opts]
      @param {Boolean} [opts.asyc=false] Perform this task asynchronously.
      If you flag a task with this option, you must call the global
      `complete` method inside the task's action, for execution to proceed
      to the next task.
    @example
    desc('This is a rule, which does not support namespace or pattern.');
    rule('.o', '.c', {async: true}, function () {
      var cmd = util.format('gcc -o %s %s', this.name, this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    desc('This rule has prerequisites.');
    rule('.o', '.c', ['util.h'], {async: true}, function () {
      var cmd = util.format('gcc -o %s %s', this.name, this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    desc('This is a rule with patterns.');
    rule('%.o', '%.c', {async: true}, function () {
      var cmd = util.format('gcc -o %s %s', this.name, this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    desc('This is another rule with patterns.');
    rule('obj/%.o', 'src/%.c', {async: true}, function () {
      var cmd = util.format('gcc -o %s %s', this.name, this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    desc('This is an example with chain rules.');
    rule('%.pdf', '%.dvi', {async: true}, function () {
      var cmd = util.format('dvipdfm %s',this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    rule('%.dvi', '%.tex', {async: true}, function () {
      var cmd = util.format('latex %s',this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    desc('This rule has a namespace.');
    task('default', ['debug:obj/main.o]);

    namespace('debug', {async: true}, function() {
      rule('obj/%.o', 'src/%.c', function () {
        // ...
      });
    }
   */
  this.rule = function () {
    var args = Array.prototype.slice.call(arguments);
       var arg;
       var pattern = args.shift();
       var source = args.shift();
       var prereqs = [];
       var action = function () {};
       var opts = {};
       var key = pattern.toString(); // May be a RegExp

    while ((arg = args.shift())) {
      if (typeof arg == 'function') {
        action = arg;
      }
      else if (Array.isArray(arg)) {
        prereqs = arg;
      }
      else {
        opts = arg;
      }
    }

    jake.currentNamespace.rules[key] = new jake.Rule({
      pattern: pattern,
     source: source,
     prereqs: prereqs,
     action: action,
     opts: opts,
     desc: jake.currentTaskDescription,
     ns: jake.currentNamespace
    });
    jake.currentTaskDescription = null;
  };

  /**
    @name directory
    @static
    @function
    @description Creates a Jake DirectoryTask. Can be used as a prerequisite
    for FileTasks, or for simply ensuring a directory exists for use with a
    Task's action.
    `
    @param {String} name The name of the DiretoryTask

    @example

    // Creates the package directory for distribution
    directory('pkg');
   */
  this.directory = function (name) {
    var args = Array.prototype.slice.call(arguments);
       var createdTask;
    args.unshift('directory');
    createdTask = jake.createTask.apply(global, args);
    jake.currentTaskDescription = null;
    return createdTask;
  };

  /**
    @name file
    @static
    @function
    @description Creates a Jake FileTask.
    `
    @param {String} name The name of the FileTask
    @param {Array} [prereqs] Prerequisites to be run before this task
    @param {Function} [action] The action to create this file, if it doesn't
    exist already.
    @param {Object} [opts]
      @param {Array} [opts.asyc=false] Perform this task asynchronously.
      If you flag a task with this option, you must call the global
      `complete` method inside the task's action, for execution to proceed
      to the next task.

   */
  this.file = function (name, prereqs, action, opts) {
    var args = Array.prototype.slice.call(arguments);
       var createdTask;
    args.unshift('file');
    createdTask = jake.createTask.apply(global, args);
    jake.currentTaskDescription = null;
    return createdTask;
  };

  /**
    @name desc
    @static
    @function
    @description Creates a description for a Jake Task (or FileTask,
    DirectoryTask). When invoked, the description that iscreated will
    be associated with whatever Task is created next.
    `
    @param {String} description The description for the Task
   */
  this.desc = function (description) {
    jake.currentTaskDescription = description;
  };

  /**
    @name namespace
    @static
    @function
    @description Creates a namespace which allows logical grouping
    of tasks, and prevents name-collisions with task-names. Namespaces
    can be nested inside of other namespaces.
    `
    @param {String} name The name of the namespace
    @param {Function} scope The enclosing scope for the namespaced tasks

    @example
    namespace('doc', function () {
      task('generate', ['doc:clobber'], function () {
        // Generate some docs
      });

      task('clobber', function () {
        // Clobber the doc directory first
      });
    });
   */
  this.namespace = function (name, closure) {
    var curr = jake.currentNamespace;
       var ns = curr.childNamespaces[name] || new jake.Namespace(name, curr);
    curr.childNamespaces[name] = ns;
    jake.currentNamespace = ns;
    closure();
    jake.currentNamespace = curr;
    jake.currentTaskDescription = null;
    return ns;
  };

  /**
    @name complete
    @static
    @function
    @description Completes an asynchronous task, allowing Jake's
    execution to proceed to the next task. Calling complete globally or without
    arguments completes the last task on the invocationChain. If you use parallel
    execution of prereqs this will probably complete a wrong task. You should call this
    function with this task as the first argument, before the optional return value.
    Alternatively you can call task.complete()
    `
    @example
    task('generate', ['doc:clobber'], function () {
      exec('./generate_docs.sh', function (err, stdout, stderr) {
        if (err || stderr) {
          fail(err || stderr);
        }
        else {
          console.log(stdout);
          complete();
        }
      });
    }, {async: true});
   */
  this.complete = function (task, val) {
    //this should detect if the first arg is a task, but I guess it should be more thorough
    if(task && task. _currentPrereqIndex >=0 ) {
      task.complete(val);
    }
 else {
      val = task;
      if(jake._invocationChain.length > 0) {
        jake._invocationChain[jake._invocationChain.length-1].complete(val);
      }
    }
  };

  /**
    @name fail
    @static
    @function
    @description Causes Jake execution to abort with an error.
    Allows passing an optional error code, which will be used to
    set the exit-code of exiting process.
    `
    @param {Error|String} err The error to thow when aborting execution.
    If this argument is an Error object, it will simply be thrown. If
    a String, it will be used as the error-message. (If it is a multi-line
    String, the first line will be used as the Error message, and the
    remaining lines will be used as the error-stack.)

    @example
    task('createTests, function () {
      if (!fs.existsSync('./tests')) {
        fail('Test directory does not exist.');
      }
      else {
        // Do some testing stuff ...
      }
    });
   */
  this.fail = function (err, code) {
    var msg;
       var errObj;
    if (code) {
      jake.errorCode = code;
    }
    if (err) {
      if (typeof err == 'string') {
        // Use the initial or only line of the error as the error-message
        // If there was a multi-line error, use the rest as the stack
        msg = err.split('\n');
        errObj = new Error(msg.shift());
        if (msg.length) {
          errObj.stack = msg.join('\n');
        }
        throw errObj;
      }
      else if (err instanceof Error) {
        throw err;
      }
      else {
        throw new Error(err.toString());
      }
    }
    else {
      throw new Error();
    }
  };

  this.packageTask = function (name, version, prereqs, definition) {
    return new jake.PackageTask(name, version, prereqs, definition);
  };

  this.publishTask = function (name, prereqs, opts, definition) {
    return new jake.PublishTask(name, prereqs, opts, definition);
  };

  // Backward-compat
  this.npmPublishTask = function (name, prereqs, opts, definition) {
    return new jake.PublishTask(name, prereqs, opts, definition);
  };

  this.watchTask = function (name, taskNames, definition) {
    return new jake.WatchTask(name, taskNames, definition);
  };

  this.testTask = function () {
    var ctor = function () {};
       var t;
    ctor.prototype = jake.TestTask.prototype;
    t = new ctor();
    jake.TestTask.apply(t, arguments);
    return t;
  };

  this.setTaskTimeout = function (t) {
    this._taskTimeout = t;
  };

  this.setSeriesAutoPrefix = function (prefix) {
    this._seriesAutoPrefix = prefix;
  };

  this.series = function (...args) {
    let prereqs = args.map((arg) => {
      let name = (this._seriesAutoPrefix || '') + arg.name;
      jake.task(name, arg);
      return name;
    });
    let seriesName = utils.string.uuid();
    let seriesTask = jake.task(seriesName, prereqs);
    seriesTask._internal = true;
    let res = function () {
      return new Promise((resolve) => {
        seriesTask.invoke();
        seriesTask.on('complete', (val) => {
          resolve(val);
        });
      });
    };
    Object.defineProperty(res, 'name', {value: utils.string.uuid(),
          writable: false});
    return res;
  };

})();

module.exports = api;
<commit_msg>Updated syntax<commit_after>/*
 * Jake JavaScript build tool
 * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/
let utils = require('./utils');

let api = new (function () {
  /**
    @name task
    @static
    @function
    @description Creates a Jake Task
    `
    @param {String} name The name of the Task
    @param {Array} [prereqs] Prerequisites to be run before this task
    @param {Function} [action] The action to perform for this task
    @param {Object} [opts]
      @param {Boolean} [opts.asyc=false] Perform this task asynchronously.
      If you flag a task with this option, you must call the global
      `complete` method inside the task's action, for execution to proceed
      to the next task.

    @example
    desc('This is the default task.');
    task('default', function (params) {
      console.log('This is the default task.');
    });

    desc('This task has prerequisites.');
    task('hasPrereqs', ['foo', 'bar', 'baz'], function (params) {
      console.log('Ran some prereqs first.');
    });

    desc('This is an asynchronous task.');
    task('asyncTask', function () {
      setTimeout(complete, 1000);
    }, {async: true});
   */
  this.task = function (name, prereqs, action, opts) {
    let args = Array.prototype.slice.call(arguments);
       let createdTask;
    args.unshift('task');
    createdTask = jake.createTask.apply(global, args);
    jake.currentTaskDescription = null;
    return createdTask;
  };

  /**
    @name rule
    @static
    @function
    @description Creates a Jake Suffix Rule
    `
    @param {String} pattern The suffix name of the objective
    @param {String} source The suffix name of the objective
    @param {Array} [prereqs] Prerequisites to be run before this task
    @param {Function} [action] The action to perform for this task
    @param {Object} [opts]
      @param {Boolean} [opts.asyc=false] Perform this task asynchronously.
      If you flag a task with this option, you must call the global
      `complete` method inside the task's action, for execution to proceed
      to the next task.
    @example
    desc('This is a rule, which does not support namespace or pattern.');
    rule('.o', '.c', {async: true}, function () {
      let cmd = util.format('gcc -o %s %s', this.name, this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    desc('This rule has prerequisites.');
    rule('.o', '.c', ['util.h'], {async: true}, function () {
      let cmd = util.format('gcc -o %s %s', this.name, this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    desc('This is a rule with patterns.');
    rule('%.o', '%.c', {async: true}, function () {
      let cmd = util.format('gcc -o %s %s', this.name, this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    desc('This is another rule with patterns.');
    rule('obj/%.o', 'src/%.c', {async: true}, function () {
      let cmd = util.format('gcc -o %s %s', this.name, this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    desc('This is an example with chain rules.');
    rule('%.pdf', '%.dvi', {async: true}, function () {
      let cmd = util.format('dvipdfm %s',this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    rule('%.dvi', '%.tex', {async: true}, function () {
      let cmd = util.format('latex %s',this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    desc('This rule has a namespace.');
    task('default', ['debug:obj/main.o]);

    namespace('debug', {async: true}, function() {
      rule('obj/%.o', 'src/%.c', function () {
        // ...
      });
    }
   */
  this.rule = function () {
    let args = Array.prototype.slice.call(arguments);
       let arg;
       let pattern = args.shift();
       let source = args.shift();
       let prereqs = [];
       let action = function () {};
       let opts = {};
       let key = pattern.toString(); // May be a RegExp

    while ((arg = args.shift())) {
      if (typeof arg == 'function') {
        action = arg;
      }
      else if (Array.isArray(arg)) {
        prereqs = arg;
      }
      else {
        opts = arg;
      }
    }

    jake.currentNamespace.rules[key] = new jake.Rule({
      pattern: pattern,
     source: source,
     prereqs: prereqs,
     action: action,
     opts: opts,
     desc: jake.currentTaskDescription,
     ns: jake.currentNamespace
    });
    jake.currentTaskDescription = null;
  };

  /**
    @name directory
    @static
    @function
    @description Creates a Jake DirectoryTask. Can be used as a prerequisite
    for FileTasks, or for simply ensuring a directory exists for use with a
    Task's action.
    `
    @param {String} name The name of the DiretoryTask

    @example

    // Creates the package directory for distribution
    directory('pkg');
   */
  this.directory = function (name) {
    let args = Array.prototype.slice.call(arguments);
       let createdTask;
    args.unshift('directory');
    createdTask = jake.createTask.apply(global, args);
    jake.currentTaskDescription = null;
    return createdTask;
  };

  /**
    @name file
    @static
    @function
    @description Creates a Jake FileTask.
    `
    @param {String} name The name of the FileTask
    @param {Array} [prereqs] Prerequisites to be run before this task
    @param {Function} [action] The action to create this file, if it doesn't
    exist already.
    @param {Object} [opts]
      @param {Array} [opts.asyc=false] Perform this task asynchronously.
      If you flag a task with this option, you must call the global
      `complete` method inside the task's action, for execution to proceed
      to the next task.

   */
  this.file = function (name, prereqs, action, opts) {
    let args = Array.prototype.slice.call(arguments);
       let createdTask;
    args.unshift('file');
    createdTask = jake.createTask.apply(global, args);
    jake.currentTaskDescription = null;
    return createdTask;
  };

  /**
    @name desc
    @static
    @function
    @description Creates a description for a Jake Task (or FileTask,
    DirectoryTask). When invoked, the description that iscreated will
    be associated with whatever Task is created next.
    `
    @param {String} description The description for the Task
   */
  this.desc = function (description) {
    jake.currentTaskDescription = description;
  };

  /**
    @name namespace
    @static
    @function
    @description Creates a namespace which allows logical grouping
    of tasks, and prevents name-collisions with task-names. Namespaces
    can be nested inside of other namespaces.
    `
    @param {String} name The name of the namespace
    @param {Function} scope The enclosing scope for the namespaced tasks

    @example
    namespace('doc', function () {
      task('generate', ['doc:clobber'], function () {
        // Generate some docs
      });

      task('clobber', function () {
        // Clobber the doc directory first
      });
    });
   */
  this.namespace = function (name, closure) {
    let curr = jake.currentNamespace;
       let ns = curr.childNamespaces[name] || new jake.Namespace(name, curr);
    curr.childNamespaces[name] = ns;
    jake.currentNamespace = ns;
    closure();
    jake.currentNamespace = curr;
    jake.currentTaskDescription = null;
    return ns;
  };

  /**
    @name complete
    @static
    @function
    @description Completes an asynchronous task, allowing Jake's
    execution to proceed to the next task. Calling complete globally or without
    arguments completes the last task on the invocationChain. If you use parallel
    execution of prereqs this will probably complete a wrong task. You should call this
    function with this task as the first argument, before the optional return value.
    Alternatively you can call task.complete()
    `
    @example
    task('generate', ['doc:clobber'], function () {
      exec('./generate_docs.sh', function (err, stdout, stderr) {
        if (err || stderr) {
          fail(err || stderr);
        }
        else {
          console.log(stdout);
          complete();
        }
      });
    }, {async: true});
   */
  this.complete = function (task, val) {
    //this should detect if the first arg is a task, but I guess it should be more thorough
    if(task && task. _currentPrereqIndex >=0 ) {
      task.complete(val);
    }
 else {
      val = task;
      if(jake._invocationChain.length > 0) {
        jake._invocationChain[jake._invocationChain.length-1].complete(val);
      }
    }
  };

  /**
    @name fail
    @static
    @function
    @description Causes Jake execution to abort with an error.
    Allows passing an optional error code, which will be used to
    set the exit-code of exiting process.
    `
    @param {Error|String} err The error to thow when aborting execution.
    If this argument is an Error object, it will simply be thrown. If
    a String, it will be used as the error-message. (If it is a multi-line
    String, the first line will be used as the Error message, and the
    remaining lines will be used as the error-stack.)

    @example
    task('createTests, function () {
      if (!fs.existsSync('./tests')) {
        fail('Test directory does not exist.');
      }
      else {
        // Do some testing stuff ...
      }
    });
   */
  this.fail = function (err, code) {
    let msg;
       let errObj;
    if (code) {
      jake.errorCode = code;
    }
    if (err) {
      if (typeof err == 'string') {
        // Use the initial or only line of the error as the error-message
        // If there was a multi-line error, use the rest as the stack
        msg = err.split('\n');
        errObj = new Error(msg.shift());
        if (msg.length) {
          errObj.stack = msg.join('\n');
        }
        throw errObj;
      }
      else if (err instanceof Error) {
        throw err;
      }
      else {
        throw new Error(err.toString());
      }
    }
    else {
      throw new Error();
    }
  };

  this.packageTask = function (name, version, prereqs, definition) {
    return new jake.PackageTask(name, version, prereqs, definition);
  };

  this.publishTask = function (name, prereqs, opts, definition) {
    return new jake.PublishTask(name, prereqs, opts, definition);
  };

  // Backward-compat
  this.npmPublishTask = function (name, prereqs, opts, definition) {
    return new jake.PublishTask(name, prereqs, opts, definition);
  };

  this.watchTask = function (name, taskNames, definition) {
    return new jake.WatchTask(name, taskNames, definition);
  };

  this.testTask = function () {
    let ctor = function () {};
    let t;
    ctor.prototype = jake.TestTask.prototype;
    t = new ctor();
    jake.TestTask.apply(t, arguments);
    return t;
  };

  this.setTaskTimeout = function (t) {
    this._taskTimeout = t;
  };

  this.setSeriesAutoPrefix = function (prefix) {
    this._seriesAutoPrefix = prefix;
  };

  this.series = function (...args) {
    let prereqs = args.map((arg) => {
      let name = (this._seriesAutoPrefix || '') + arg.name;
      jake.task(name, arg);
      return name;
    });
    let seriesName = utils.string.uuid();
    let seriesTask = jake.task(seriesName, prereqs);
    seriesTask._internal = true;
    let res = function () {
      return new Promise((resolve) => {
        seriesTask.invoke();
        seriesTask.on('complete', (val) => {
          resolve(val);
        });
      });
    };
    Object.defineProperty(res, 'name', {value: utils.string.uuid(),
          writable: false});
    return res;
  };

})();

module.exports = api;
<|endoftext|>


<commit_before>// Copyright 2020, University of Colorado Boulder

/**
 * Central class for the sun button hierarchy. This type factors out logic that applies to all sun buttons.
 *
 * @author John Blanco (PhET Interactive Simulations)
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Michael Kauzmann (PhET Interactive Simulations)
 */

import Bounds2 from '../../../dot/js/Bounds2.js';
import Vector2 from '../../../dot/js/Vector2.js';
import merge from '../../../phet-core/js/merge.js';
import AlignBox from '../../../scenery/js/nodes/AlignBox.js';
import Node from '../../../scenery/js/nodes/Node.js';
import PaintColorProperty from '../../../scenery/js/util/PaintColorProperty.js';
import Tandem from '../../../tandem/js/Tandem.js';
import ColorConstants from '../ColorConstants.js';
import EnabledNode from '../EnabledNode.js';
import sun from '../sun.js';
import ButtonInteractionState from './ButtonInteractionState.js';

// constants
const X_ALIGN_VALUES = [ 'center', 'left', 'right' ];
const Y_ALIGN_VALUES = [ 'center', 'top', 'bottom' ];

class ButtonNode extends Node {

  /**
   * @param {ButtonModel} buttonModel
   * @param {Node} buttonBackground - the background of the button (like a circle or rectangle).
   * @param {Property} interactionStateProperty - a Property that is used to drive the visual appearance of the button
   * @param {Object} [options] - this type does not mutate its options, but relies on the subtype to
   */
  constructor( buttonModel, buttonBackground, interactionStateProperty, options ) {

    options = merge( {

      // {Node|null} what appears on the button (icon, label, etc.)
      content: null,

      xMargin: 10, // margin in x direction, i.e. on left and right
      yMargin: 5, // margin in y direction, i.e. on top and bottom

      // Alignment, relevant only when options minWidth or minHeight are greater than the size of options.content
      xAlign: 'center', // {string} see X_ALIGN_VALUES
      yAlign: 'center', // {string} see Y_ALIGN_VALUES

      // By default, icons are centered in the button, but icons with odd
      // shapes that are not wrapped in a normalizing parent node may need to
      // specify offsets to line things up properly
      xContentOffset: 0,
      yContentOffset: 0,

      // Options that will be passed through to the main input listener (PressListener)
      listenerOptions: null,

      // {ColorDef} initial color of the button's background
      baseColor: ColorConstants.LIGHT_BLUE,

      // {string} default cursor
      cursor: 'pointer',

      // Class that determines the button's appearance for the values of interactionStateProperty.
      // See ButtonNode.FlatAppearanceStrategy for an example of the interface required.
      buttonAppearanceStrategy: ButtonNode.FlatAppearanceStrategy,

      // phet-io
      // TODO: workaround for difficulty in mutate/instrumentation order of sun buttons,
      //  see https://github.com/phetsims/sun/issues/643 or https://github.com/phetsims/sun/issues/515
      phetioLinkEnabledElement: false,
      tandem: Tandem.OPTIONAL,
      visiblePropertyOptions: { phetioFeatured: true }
    }, options );

    options.listenerOptions = merge( {
      tandem: options.tandem.createTandem( 'pressListener' )
    }, options.listenerOptions );

    assert && options.enabledProperty && assert( options.enabledProperty === buttonModel.enabledProperty,
      'if options.enabledProperty is provided, it must === buttonModel.enabledProperty' );
    options.enabledProperty = buttonModel.enabledProperty;

    // validate options - TODO: are these needed? Won't AlignBox handle this validation? https://github.com/phetsims/sun/issues/643
    assert && assert( _.includes( X_ALIGN_VALUES, options.xAlign ), 'invalid xAlign: ' + options.xAlign );
    assert && assert( _.includes( Y_ALIGN_VALUES, options.yAlign ), 'invalid yAlign: ' + options.yAlign );

    super();

    this.initializeEnabledNode( options );

    // @protected
    this.buttonModel = buttonModel;

    // Make the base color into a Property so that the appearance strategy can update itself if changes occur.
    this.baseColorProperty = new PaintColorProperty( options.baseColor ); // @private

    // @private {PressListener}
    this._pressListener = buttonModel.createPressListener( options.listenerOptions );
    this.addInputListener( this._pressListener );

    assert && assert( buttonBackground.fill === null, 'ButtonNode controls the fill for the buttonBackground' );
    buttonBackground.pickable = false;
    buttonBackground.fill = this.baseColorProperty;
    this.addChild( buttonBackground );

    // Hook up the strategy that will control the button's appearance.
    const buttonAppearanceStrategy = new options.buttonAppearanceStrategy( buttonBackground, interactionStateProperty,
      this.baseColorProperty, options );

    let alignBox = null;
    if ( options.content ) {

      // TODO: there is likely a simpler way to support this content offset, https://github.com/phetsims/sun/issues/643
      const contentContainer = new Node( {
        children: [ options.content ],
        center: new Vector2( options.xContentOffset, options.yContentOffset )
      } );

      // Align content in the button rectangle. Must be disposed since it adds listener to content bounds.
      alignBox = new AlignBox( contentContainer, {

        // TODO https://github.com/phetsims/sun/issues/643 Margins here would be broken for round buttons if they
        //  don't use the same value for x and y. Because they are used here differently from how they are used to
        //  calculate radius in RoundButton (as a minimum). Is that OK?
        alignBounds: new Bounds2(
          options.xMargin,
          options.yMargin,
          buttonBackground.width - options.xMargin,
          buttonBackground.height - options.yMargin
        ),
        xAlign: options.xAlign,
        yAlign: options.yAlign,
        center: buttonBackground.center,
        pickable: false // for performance
      } );
      this.addChild( alignBox );
    }

    this.mutate( options );

    // @private - define a dispose function
    this.disposeButtonNode = () => {
      alignBox && alignBox.dispose();
      buttonAppearanceStrategy.dispose && buttonAppearanceStrategy.dispose();
      this._pressListener.dispose();
      this.baseColorProperty.dispose();
    };
  }

  /**
   * @public
   * @override
   */
  dispose() {
    this.disposeButtonNode();
    super.dispose();
  }

  /**
   * Sets the base color, which is the main background fill color used for the button.
   * @param {Color|String} baseColor
   * @public
   */
  setBaseColor( baseColor ) { this.baseColorProperty.paint = baseColor; }

  set baseColor( baseColor ) { this.setBaseColor( baseColor ); }

  /**
   * Gets the base color for this button.
   * @returns {Color}
   * @public
   */
  getBaseColor() { return this.baseColorProperty.paint; }

  get baseColor() { return this.getBaseColor(); }

  /**
   * Manually click the button, as it would be clicked in response to alternative input. Recommended only for
   * accessibility usages. For the most part, PDOM button functionality should be managed by PressListener, this should
   * rarely be used.
   * @public
   */
  pdomClick() {
    this._pressListener.click();
  }

  /**
   * Is the button currently firing because of accessibility input coming from the PDOM?
   * @public (pdom)
   * @returns {boolean}
   */
  isPDOMClicking() {
    return this._pressListener.pdomClickingProperty.get();
  }
}

/**
 * FlatAppearanceStrategy is a value for ButtonNode options.buttonAppearanceStrategy. It makes a
 * button look flat, i.e. no shading or highlighting, with color changes on mouseover, press, etc.
 */
class FlatAppearanceStrategy {

  /*
   * @param {Node} button - the Node for the button's shape, sans content
   * @param {Property.<boolean>} interactionStateProperty
   * @param {Property.<Color>} baseColorProperty
   * @param {Object} [options]
   */
  constructor( button, interactionStateProperty, baseColorProperty, options ) {

    // Dynamic colors
    const baseBrighter4 = new PaintColorProperty( baseColorProperty, { luminanceFactor: 0.4 } );
    const baseDarker4 = new PaintColorProperty( baseColorProperty, { luminanceFactor: -0.4 } );

    // Various fills that are used to alter the button's appearance
    const upFill = baseColorProperty;
    const overFill = baseBrighter4;
    const downFill = baseDarker4;

    // If the stroke wasn't provided, set a default
    button.stroke = ( typeof ( options.stroke ) === 'undefined' ) ? baseDarker4 : options.stroke;

    // Cache colors
    button.cachedPaints = [ upFill, overFill, downFill ];

    // Change colors to match interactionState
    function interactionStateListener( interactionState ) {
      switch( interactionState ) {

        case ButtonInteractionState.IDLE:
        case ButtonInteractionState.DISABLED:
          button.fill = upFill;
          break;

        case ButtonInteractionState.OVER:
          button.fill = overFill;
          break;

        case ButtonInteractionState.PRESSED:
        case ButtonInteractionState.DISABLED_PRESSED:
          button.fill = downFill;
          break;

        default:
          throw new Error( `unsupported interactionState: ${interactionState}` );
      }
    }

    // Do the initial update explicitly, then lazy link to the properties.  This keeps the number of initial updates to
    // a minimum and allows us to update some optimization flags the first time the base color is actually changed.
    interactionStateProperty.link( interactionStateListener );

    // @public
    this.dispose = () => {
      if ( interactionStateProperty.hasListener( interactionStateListener ) ) {
        interactionStateProperty.unlink( interactionStateListener );
      }

      baseBrighter4.dispose();
      baseDarker4.dispose();
    };
  }
}

ButtonNode.FlatAppearanceStrategy = FlatAppearanceStrategy;

EnabledNode.mixInto( ButtonNode );

sun.register( 'ButtonNode', ButtonNode );
export default ButtonNode;<commit_msg>fix xContentOffset and yContentOffset options for ButtonNode, https://github.com/phetsims/sun/issues/649<commit_after>// Copyright 2020, University of Colorado Boulder

/**
 * Central class for the sun button hierarchy. This type factors out logic that applies to all sun buttons.
 *
 * @author John Blanco (PhET Interactive Simulations)
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Michael Kauzmann (PhET Interactive Simulations)
 */

import merge from '../../../phet-core/js/merge.js';
import AlignBox from '../../../scenery/js/nodes/AlignBox.js';
import Node from '../../../scenery/js/nodes/Node.js';
import PaintColorProperty from '../../../scenery/js/util/PaintColorProperty.js';
import Tandem from '../../../tandem/js/Tandem.js';
import ColorConstants from '../ColorConstants.js';
import EnabledNode from '../EnabledNode.js';
import sun from '../sun.js';
import ButtonInteractionState from './ButtonInteractionState.js';

// constants
const X_ALIGN_VALUES = [ 'center', 'left', 'right' ];
const Y_ALIGN_VALUES = [ 'center', 'top', 'bottom' ];

class ButtonNode extends Node {

  /**
   * @param {ButtonModel} buttonModel
   * @param {Node} buttonBackground - the background of the button (like a circle or rectangle).
   * @param {Property} interactionStateProperty - a Property that is used to drive the visual appearance of the button
   * @param {Object} [options] - this type does not mutate its options, but relies on the subtype to
   */
  constructor( buttonModel, buttonBackground, interactionStateProperty, options ) {

    options = merge( {

      // {Node|null} what appears on the button (icon, label, etc.)
      content: null,

      xMargin: 10, // margin in x direction, i.e. on left and right
      yMargin: 5, // margin in y direction, i.e. on top and bottom

      // Alignment, relevant only when options minWidth or minHeight are greater than the size of options.content
      xAlign: 'center', // {string} see X_ALIGN_VALUES
      yAlign: 'center', // {string} see Y_ALIGN_VALUES

      // By default, icons are centered in the button, but icons with odd
      // shapes that are not wrapped in a normalizing parent node may need to
      // specify offsets to line things up properly
      xContentOffset: 0,
      yContentOffset: 0,

      // Options that will be passed through to the main input listener (PressListener)
      listenerOptions: null,

      // {ColorDef} initial color of the button's background
      baseColor: ColorConstants.LIGHT_BLUE,

      // {string} default cursor
      cursor: 'pointer',

      // Class that determines the button's appearance for the values of interactionStateProperty.
      // See ButtonNode.FlatAppearanceStrategy for an example of the interface required.
      buttonAppearanceStrategy: ButtonNode.FlatAppearanceStrategy,

      // phet-io
      // TODO: workaround for difficulty in mutate/instrumentation order of sun buttons,
      //  see https://github.com/phetsims/sun/issues/643 or https://github.com/phetsims/sun/issues/515
      phetioLinkEnabledElement: false,
      tandem: Tandem.OPTIONAL,
      visiblePropertyOptions: { phetioFeatured: true }
    }, options );

    options.listenerOptions = merge( {
      tandem: options.tandem.createTandem( 'pressListener' )
    }, options.listenerOptions );

    assert && options.enabledProperty && assert( options.enabledProperty === buttonModel.enabledProperty,
      'if options.enabledProperty is provided, it must === buttonModel.enabledProperty' );
    options.enabledProperty = buttonModel.enabledProperty;

    // validate options - TODO: are these needed? Won't AlignBox handle this validation? https://github.com/phetsims/sun/issues/643
    assert && assert( _.includes( X_ALIGN_VALUES, options.xAlign ), 'invalid xAlign: ' + options.xAlign );
    assert && assert( _.includes( Y_ALIGN_VALUES, options.yAlign ), 'invalid yAlign: ' + options.yAlign );

    super();

    this.initializeEnabledNode( options );

    // @protected
    this.buttonModel = buttonModel;

    // Make the base color into a Property so that the appearance strategy can update itself if changes occur.
    this.baseColorProperty = new PaintColorProperty( options.baseColor ); // @private

    // @private {PressListener}
    this._pressListener = buttonModel.createPressListener( options.listenerOptions );
    this.addInputListener( this._pressListener );

    assert && assert( buttonBackground.fill === null, 'ButtonNode controls the fill for the buttonBackground' );
    buttonBackground.pickable = false;
    buttonBackground.fill = this.baseColorProperty;
    this.addChild( buttonBackground );

    // Hook up the strategy that will control the button's appearance.
    const buttonAppearanceStrategy = new options.buttonAppearanceStrategy( buttonBackground, interactionStateProperty,
      this.baseColorProperty, options );

    let alignBox = null;
    if ( options.content ) {

      // Align content in the button rectangle. Must be disposed since it adds listener to content bounds.
      alignBox = new AlignBox( options.content, {

        alignBounds: buttonBackground.bounds,
        xAlign: options.xAlign,
        yAlign: options.yAlign,

        // TODO https://github.com/phetsims/sun/issues/643 Margins here would be broken for round buttons if they
        //  don't use the same value for x and y. Because they are used here differently from how they are used to
        //  calculate radius in RoundButton (as a minimum). Is that OK?

        // Apply offsets via margins, so that bounds of the AlignBox doesn't unnecessarily extend past the
        // buttonBackground. See https://github.com/phetsims/sun/issues/649
        leftMargin: options.xMargin + options.xContentOffset,
        rightMargin: options.xMargin - options.xContentOffset,
        topMargin: options.yMargin + options.yContentOffset,
        bottomMargin: options.yMargin - options.yContentOffset,

        // for performance
        pickable: false
      } );
      this.addChild( alignBox );
    }

    this.mutate( options );

    // @private - define a dispose function
    this.disposeButtonNode = () => {
      alignBox && alignBox.dispose();
      buttonAppearanceStrategy.dispose && buttonAppearanceStrategy.dispose();
      this._pressListener.dispose();
      this.baseColorProperty.dispose();
    };
  }

  /**
   * @public
   * @override
   */
  dispose() {
    this.disposeButtonNode();
    super.dispose();
  }

  /**
   * Sets the base color, which is the main background fill color used for the button.
   * @param {Color|String} baseColor
   * @public
   */
  setBaseColor( baseColor ) { this.baseColorProperty.paint = baseColor; }

  set baseColor( baseColor ) { this.setBaseColor( baseColor ); }

  /**
   * Gets the base color for this button.
   * @returns {Color}
   * @public
   */
  getBaseColor() { return this.baseColorProperty.paint; }

  get baseColor() { return this.getBaseColor(); }

  /**
   * Manually click the button, as it would be clicked in response to alternative input. Recommended only for
   * accessibility usages. For the most part, PDOM button functionality should be managed by PressListener, this should
   * rarely be used.
   * @public
   */
  pdomClick() {
    this._pressListener.click();
  }

  /**
   * Is the button currently firing because of accessibility input coming from the PDOM?
   * @public (pdom)
   * @returns {boolean}
   */
  isPDOMClicking() {
    return this._pressListener.pdomClickingProperty.get();
  }
}

/**
 * FlatAppearanceStrategy is a value for ButtonNode options.buttonAppearanceStrategy. It makes a
 * button look flat, i.e. no shading or highlighting, with color changes on mouseover, press, etc.
 */
class FlatAppearanceStrategy {

  /*
   * @param {Node} button - the Node for the button's shape, sans content
   * @param {Property.<boolean>} interactionStateProperty
   * @param {Property.<Color>} baseColorProperty
   * @param {Object} [options]
   */
  constructor( button, interactionStateProperty, baseColorProperty, options ) {

    // Dynamic colors
    const baseBrighter4 = new PaintColorProperty( baseColorProperty, { luminanceFactor: 0.4 } );
    const baseDarker4 = new PaintColorProperty( baseColorProperty, { luminanceFactor: -0.4 } );

    // Various fills that are used to alter the button's appearance
    const upFill = baseColorProperty;
    const overFill = baseBrighter4;
    const downFill = baseDarker4;

    // If the stroke wasn't provided, set a default
    button.stroke = ( typeof ( options.stroke ) === 'undefined' ) ? baseDarker4 : options.stroke;

    // Cache colors
    button.cachedPaints = [ upFill, overFill, downFill ];

    // Change colors to match interactionState
    function interactionStateListener( interactionState ) {
      switch( interactionState ) {

        case ButtonInteractionState.IDLE:
        case ButtonInteractionState.DISABLED:
          button.fill = upFill;
          break;

        case ButtonInteractionState.OVER:
          button.fill = overFill;
          break;

        case ButtonInteractionState.PRESSED:
        case ButtonInteractionState.DISABLED_PRESSED:
          button.fill = downFill;
          break;

        default:
          throw new Error( `unsupported interactionState: ${interactionState}` );
      }
    }

    // Do the initial update explicitly, then lazy link to the properties.  This keeps the number of initial updates to
    // a minimum and allows us to update some optimization flags the first time the base color is actually changed.
    interactionStateProperty.link( interactionStateListener );

    // @public
    this.dispose = () => {
      if ( interactionStateProperty.hasListener( interactionStateListener ) ) {
        interactionStateProperty.unlink( interactionStateListener );
      }

      baseBrighter4.dispose();
      baseDarker4.dispose();
    };
  }
}

ButtonNode.FlatAppearanceStrategy = FlatAppearanceStrategy;

EnabledNode.mixInto( ButtonNode );

sun.register( 'ButtonNode', ButtonNode );
export default ButtonNode;<|endoftext|>


<commit_before>var xmlrpc = require('xmlrpc'),
Url = require('url');

function api(host) {
  var hostParts = {};

  if(typeof host == 'string')
  {
      if (host.indexOf('http') !== 0) {
          host = 'http://' + host;
      }
      hostParts = Url.parse(host);

      if(hostParts.auth)
      {
          var authParts = hostParts.auth.split(':');
          hostParts.user = authParts[0];
          hostParts.pass = authParts[1];
      }
  }
  else if(host)
  {
      hostParts = host;
  }

  if(!hostParts.hostname) hostParts.hostname = 'localhost';
  if(!hostParts.port) hostParts.port = 9001;

  this.client = xmlrpc.createClient({
      host: hostParts.hostname,
      port: hostParts.port,
      path: '/RPC2',
      basic_auth: {
          user: hostParts.user,
          pass: hostParts.pass
      }
  });
}

api.prototype._call = function(method, args, callback)
{
    this.client.methodCall(method, args, callback);
};

['supervisor.addProcessGroup',
  'supervisor.clearAllProcessLogs',
  'supervisor.clearLog',
  'supervisor.clearProcessLog',
  'supervisor.clearProcessLogs',
  'supervisor.getAPIVersion',
  'supervisor.getAllConfigInfo',
  'supervisor.getAllProcessInfo',
  'supervisor.getIdentification',
  'supervisor.getPID',
  'supervisor.getProcessInfo',
  'supervisor.getState',
  'supervisor.getSupervisorVersion',
  'supervisor.getVersion',
  'supervisor.readLog',
  'supervisor.readMainLog',
  'supervisor.readProcessLog',
  'supervisor.readProcessStderrLog',
  'supervisor.readProcessStdoutLog',
  'supervisor.reloadConfig',
  'supervisor.removeProcessGroup',
  'supervisor.restart',
  'supervisor.sendProcessStdin',
  'supervisor.sendRemoteCommEvent',
  'supervisor.shutdown',
  'supervisor.startAllProcesses',
  'supervisor.startProcess',
  'supervisor.startProcessGroup',
  'supervisor.stopAllProcesses',
  'supervisor.stopProcess',
  'supervisor.stopProcessGroup',
  'supervisor.tailProcessLog',
  'supervisor.tailProcessStderrLog',
  'supervisor.tailProcessStdoutLog',
  'system.listMethods',
  'system.methodHelp',
  'system.methodSignature',
  'system.multicall'].forEach(function(property){
  api.prototype[property.split('.').pop()] = function(){
    var args = Array.prototype.slice.call(arguments);
    callback = args.pop();
    this._call(property, args, callback);
  };
});

module.exports = api;
<commit_msg>Add function 'supervisor.signalProcess' and 'supervisor.signalProcessGroup'<commit_after>var xmlrpc = require('xmlrpc'),
Url = require('url');

function api(host) {
  var hostParts = {};

  if(typeof host == 'string')
  {
      if (host.indexOf('http') !== 0) {
          host = 'http://' + host;
      }
      hostParts = Url.parse(host);

      if(hostParts.auth)
      {
          var authParts = hostParts.auth.split(':');
          hostParts.user = authParts[0];
          hostParts.pass = authParts[1];
      }
  }
  else if(host)
  {
      hostParts = host;
  }

  if(!hostParts.hostname) hostParts.hostname = 'localhost';
  if(!hostParts.port) hostParts.port = 9001;

  this.client = xmlrpc.createClient({
      host: hostParts.hostname,
      port: hostParts.port,
      path: '/RPC2',
      basic_auth: {
          user: hostParts.user,
          pass: hostParts.pass
      }
  });
}

api.prototype._call = function(method, args, callback)
{
    this.client.methodCall(method, args, callback);
};

['supervisor.addProcessGroup',
  'supervisor.clearAllProcessLogs',
  'supervisor.clearLog',
  'supervisor.clearProcessLog',
  'supervisor.clearProcessLogs',
  'supervisor.getAPIVersion',
  'supervisor.getAllConfigInfo',
  'supervisor.getAllProcessInfo',
  'supervisor.getIdentification',
  'supervisor.getPID',
  'supervisor.getProcessInfo',
  'supervisor.getState',
  'supervisor.getSupervisorVersion',
  'supervisor.getVersion',
  'supervisor.readLog',
  'supervisor.readMainLog',
  'supervisor.readProcessLog',
  'supervisor.readProcessStderrLog',
  'supervisor.readProcessStdoutLog',
  'supervisor.reloadConfig',
  'supervisor.removeProcessGroup',
  'supervisor.restart',
  'supervisor.sendProcessStdin',
  'supervisor.sendRemoteCommEvent',
  'supervisor.signalProcess',
  'supervisor.signalProcessGroup',
  'supervisor.shutdown',
  'supervisor.startAllProcesses',
  'supervisor.startProcess',
  'supervisor.startProcessGroup',
  'supervisor.stopAllProcesses',
  'supervisor.stopProcess',
  'supervisor.stopProcessGroup',
  'supervisor.tailProcessLog',
  'supervisor.tailProcessStderrLog',
  'supervisor.tailProcessStdoutLog',
  'system.listMethods',
  'system.methodHelp',
  'system.methodSignature',
  'system.multicall'].forEach(function(property){
  api.prototype[property.split('.').pop()] = function(){
    var args = Array.prototype.slice.call(arguments);
    callback = args.pop();
    this._call(property, args, callback);
  };
});

module.exports = api;
<|endoftext|>


<commit_before>var Database = exports;

var log = require('./log');
var fs = require('fs');
var path = require('path');
var SqlString = require('./SqlString');
var sqlite3 = require('sqlite3').verbose();

var db_path = path.join(__dirname, '..', 'data', 'library.db');
var db_initialised = path.existsSync(db_path);

var db = new sqlite3.Database(db_path);

if(!db_initialised) {
	db.serialize(function() {
		log.info('Initialising database');
		// Create Artist Table
		db.run('CREATE TABLE artists (' +
			'id INTEGER PRIMARY KEY AUTOINCREMENT, ' +
			'name TEXT COLLATE NOCASE, ' +
			'UNIQUE(name) ON CONFLICT IGNORE)');
		// Create Album Table
		db.run('CREATE TABLE albums (' +
			'id INTEGER PRIMARY KEY AUTOINCREMENT, ' +
			'name TEXT COLLATE NOCASE, ' +
			'albumart TEXT, ' +
			'artist_id INTEGER, ' +
			'UNIQUE(name, artist_id) ON CONFLICT IGNORE, ' +  // Ignore incase album art has already been set.
			'FOREIGN KEY(artist_id) REFERENCES artist(id))');
		// A View that combines albums & artists
		db.run('CREATE VIEW if not exists album_view as select ' +
			'albums.id as id, ' +
			'albums.name as name, ' +
			'albums.album_art as album_art, ' +
			'artists.id as artist_id, ' +
			'artists.name as artist_name ' +
			'from albums, artists ' +
			'where albums.artist_id = artists.id');
		// Create Song Table
		db.run('CREATE TABLE songs (' +
			'id INTEGER PRIMARY KEY AUTOINCREMENT, ' +
			'name TEXT, ' +
			'path TEXT UNIQUE, ' +
			'tracknumber INTEGER, ' +
			'artist_id INTEGER, ' +
			'album_id INTEGER, ' +
			'FOREIGN KEY(artist_id) REFERENCES artist(id), ' +
			'FOREIGN KEY(album_id) REFERENCES album(id))');
		// Song View
		// Song(id, name, path, tracknumber), Artist(id, name), Album(id, name, albumart)
		db.run('CREATE VIEW if not exists song_view as select ' +
			'songs.id as id, ' +
			'songs.name as name, ' +
			'songs.path as path, ' +
			'songs.tracknumber as tracknumber, ' +
			'album_view.id as album_id, ' +
			'album_view.name as album_name, ' +
			'album_view.albumart as album_art, ' +
			'album_view.artist_id as artist_id, ' +
			'album_view.artist_name as artist_name ' +
			'from songs, album_view ' +
			'where songs.album_id = album_view.id');
	});

}

Database.addSong = function(song, path, callback) {
    if(song == undefined) {
    	return callback(false);
    }
    if(isEmpty(song.title) || isEmpty(song.artist)) {
		return callback(false);
	}
	if(isEmpty(song.album)) {
		// Create an Album Title
		song.album = song.artist + ' - Unknown Album';
	}
	db.serialize(function() {

		var insert_artist = db.prepare("INSERT INTO artists (name) VALUES (?);");
      	insert_artist.run(SqlString.escape(song.artist));
  		insert_artist.finalize();

		db.get('SELECT * FROM artists where name like ?', [ SqlString.escape(song.artist) ], function(err, artist) {
			if(err) throw err;
			var artist_id = artist.id;
			db.run('INSERT INTO albums (name, artist_id) VALUES (?, ?);', [ SqlString.escape(song.album), artist_id ]);
			db.get('SELECT * FROM albums where name = ? and artist_id = ?', [ SqlString.escape(song.album), artist_id], function(err, album) {
				if(err) throw err;
				var album_id = album.id;
				var tracknumber = 0;
				if(song.track != undefined && song.track.no != undefined) {
					tracknumber = song.track.no;
				}
				db.run('INSERT INTO songs (name, path, tracknumber, artist_id, album_id) VALUES (?, ?, ?, ?, ?);', [ SqlString.escape(song.title), SqlString.escape(path), tracknumber, artist_id, album_id ]);
				return callback(true, song, artist, album);
			});
    	});
	});
}

Database.updateAlbumArtwork = function(album_id, path, callback) {
	db.run("UPDATE albums SET albumart = ? WHERE id = ?", path, album_id, callback);
}

Database.hasSong = function(path, callback) {
	if(isEmpty(path)) {
		log.info('Empty Path');
		callback(true); // Empty path. Just pretend we have this stored
	}
	db.serialize(function() {
		db.get('SELECT * FROM songs where path = ?', [ SqlString.escape(path) ], function(err, rows) {
			if(err || rows == undefined) {
				return callback(false);
			}
			return callback(true);
		});
	});
}

function isEmpty(x) {
	return (x == undefined || (x + '').replace(/^\s*|\s*$/g, '') === '');
}

Database.getArtists = function(callback) {
	db.serialize(function() {
		db.all('SELECT * FROM artists ORDER BY name COLLATE NOCASE', callback);
	});
}

Database.getArtist = function(id, callback) {
	db.serialize(function() {
		db.get('SELECT * FROM artists where id = ' + id, callback);
	});
}

Database.getAlbums = function(callback) {
	db.serialize(function() {
		db.all('SELECT * FROM albums', callback);
	});
}

Database.getAlbumsByArtist = function(id, callback) {
	db.serialize(function() {
		db.all('SELECT * FROM albums where artist_id = ' + id, callback);
	});
}

Database.getAlbumById = function(id, callback) {
	db.serialize(function() {
		db.get('SELECT * FROM albums where id = ' + id, callback);
	});
}

Database.getSongsByAlbum = function(id, callback) {
	db.serialize(function() {
		db.all('SELECT * FROM song_view where album_id=? order by tracknumber' , [ id ], callback);
	});
}

Database.getSongById = function(id, callback) {
	db.serialize(function() {
		db.get('SELECT * FROM song_view where id = ' + id , callback);
	});
}

Database.getSongsByArtist = function(id, callback) {
	db.serialize(function() {
		db.get('SELECT * FROM song_view where artist_id = ?', [ id ], callback);
	});
}

Database.getRandomSong = function(callback) {
	db.serialize(function() {
		db.get('SELECT * FROM song_view ORDER BY RANDOM() LIMIT 1', callback);
	});
}

Database.getXRandomAlbums = function(x, callback) {
	db.serialize(function() {
		db.all('SELECT * FROM albums ORDER BY RANDOM() LIMIT ' + x, callback);
	});
}

Database.close = function() {
  db.close();
  log.info('Closed Database');
}<commit_msg>Fix some db view error<commit_after>var Database = exports;

var log = require('./log');
var fs = require('fs');
var path = require('path');
var SqlString = require('./SqlString');
var sqlite3 = require('sqlite3').verbose();

var db_path = path.join(__dirname, '..', 'data', 'library.db');
var db_initialised = path.existsSync(db_path);

var db = new sqlite3.Database(db_path);

if(!db_initialised) {
	db.serialize(function() {
		log.info('Initialising database');
		// Create Artist Table
		db.run('CREATE TABLE artists (' +
			'id INTEGER PRIMARY KEY AUTOINCREMENT, ' +
			'name TEXT COLLATE NOCASE, ' +
			'UNIQUE(name) ON CONFLICT IGNORE)');
		// Create Album Table
		db.run('CREATE TABLE albums (' +
			'id INTEGER PRIMARY KEY AUTOINCREMENT, ' +
			'name TEXT COLLATE NOCASE, ' +
			'albumart TEXT, ' +
			'artist_id INTEGER, ' +
			'UNIQUE(name, artist_id) ON CONFLICT IGNORE, ' +  // Ignore incase album art has already been set.
			'FOREIGN KEY(artist_id) REFERENCES artist(id))');
		// A View that combines albums & artists
		db.run('CREATE VIEW if not exists album_view as select ' +
			'albums.id as id, ' +
			'albums.name as name, ' +
			'albums.albumart as albumart, ' +
			'artists.id as artist_id, ' +
			'artists.name as artist_name ' +
			'from albums, artists ' +
			'where albums.artist_id = artists.id');
		// Create Song Table
		db.run('CREATE TABLE songs (' +
			'id INTEGER PRIMARY KEY AUTOINCREMENT, ' +
			'name TEXT, ' +
			'path TEXT UNIQUE, ' +
			'tracknumber INTEGER, ' +
			'artist_id INTEGER, ' +
			'album_id INTEGER, ' +
			'FOREIGN KEY(artist_id) REFERENCES artist(id), ' +
			'FOREIGN KEY(album_id) REFERENCES album(id))');
		// Song View
		// Song(id, name, path, tracknumber), Artist(id, name), Album(id, name, albumart)
		db.run('CREATE VIEW if not exists song_view as select ' +
			'songs.id as id, ' +
			'songs.name as name, ' +
			'songs.path as path, ' +
			'songs.tracknumber as tracknumber, ' +
			'album_view.id as album_id, ' +
			'album_view.name as album_name, ' +
			'album_view.albumart as album_art, ' +
			'album_view.artist_id as artist_id, ' +
			'album_view.artist_name as artist_name ' +
			'from songs, album_view ' +
			'where songs.album_id = album_view.id');
	});

}

Database.addSong = function(song, path, callback) {
    if(song == undefined) {
    	return callback(false);
    }
    if(isEmpty(song.title) || isEmpty(song.artist)) {
		return callback(false);
	}
	if(isEmpty(song.album)) {
		// Create an Album Title
		song.album = song.artist + ' - Unknown Album';
	}
	db.serialize(function() {

		var insert_artist = db.prepare("INSERT INTO artists (name) VALUES (?);");
      	insert_artist.run(SqlString.escape(song.artist));
  		insert_artist.finalize();

		db.get('SELECT * FROM artists where name like ?', [ SqlString.escape(song.artist) ], function(err, artist) {
			if(err) throw err;
			var artist_id = artist.id;
			db.run('INSERT INTO albums (name, artist_id) VALUES (?, ?);', [ SqlString.escape(song.album), artist_id ]);
			db.get('SELECT * FROM albums where name = ? and artist_id = ?', [ SqlString.escape(song.album), artist_id], function(err, album) {
				if(err) throw err;
				var album_id = album.id;
				var tracknumber = 0;
				if(song.track != undefined && song.track.no != undefined) {
					tracknumber = song.track.no;
				}
				db.run('INSERT INTO songs (name, path, tracknumber, artist_id, album_id) VALUES (?, ?, ?, ?, ?);', [ SqlString.escape(song.title), SqlString.escape(path), tracknumber, artist_id, album_id ]);
				return callback(true, song, artist, album);
			});
    	});
	});
}

Database.updateAlbumArtwork = function(album_id, path, callback) {
	db.run("UPDATE albums SET albumart = ? WHERE id = ?", path, album_id, callback);
}

Database.hasSong = function(path, callback) {
	if(isEmpty(path)) {
		log.info('Empty Path');
		callback(true); // Empty path. Just pretend we have this stored
	}
	db.serialize(function() {
		db.get('SELECT * FROM songs where path = ?', [ SqlString.escape(path) ], function(err, rows) {
			if(err || rows == undefined) {
				return callback(false);
			}
			return callback(true);
		});
	});
}

function isEmpty(x) {
	return (x == undefined || (x + '').replace(/^\s*|\s*$/g, '') === '');
}

Database.getArtists = function(callback) {
	db.serialize(function() {
		db.all('SELECT * FROM artists ORDER BY name COLLATE NOCASE', callback);
	});
}

Database.getArtist = function(id, callback) {
	db.serialize(function() {
		db.get('SELECT * FROM artists where id = ' + id, callback);
	});
}

Database.getAlbums = function(callback) {
	db.serialize(function() {
		db.all('SELECT * FROM albums', callback);
	});
}

Database.getAlbumsByArtist = function(id, callback) {
	db.serialize(function() {
		db.all('SELECT * FROM albums where artist_id = ' + id, callback);
	});
}

Database.getAlbumById = function(id, callback) {
	db.serialize(function() {
		db.get('SELECT * FROM albums where id = ' + id, callback);
	});
}

Database.getSongsByAlbum = function(id, callback) {
	db.serialize(function() {
		db.all('SELECT * FROM song_view where album_id=? order by tracknumber' , [ id ], callback);
	});
}

Database.getSongById = function(id, callback) {
	db.serialize(function() {
		db.get('SELECT * FROM song_view where id = ' + id , callback);
	});
}

Database.getSongsByArtist = function(id, callback) {
	db.serialize(function() {
		db.get('SELECT * FROM song_view where artist_id = ?', [ id ], callback);
	});
}

Database.getRandomSong = function(callback) {
	db.serialize(function() {
		db.get('SELECT * FROM song_view ORDER BY RANDOM() LIMIT 1', callback);
	});
}

Database.getXRandomAlbums = function(x, callback) {
	db.serialize(function() {
		db.all('SELECT * FROM albums ORDER BY RANDOM() LIMIT ' + x, callback);
	});
}

Database.close = function() {
  db.close();
  log.info('Closed Database');
}<|endoftext|>


<commit_before>var learnding = (function(){
    'use strict';
    var MARGIN    = 20;
    var PADDING   = 100;
    var tau = Math.PI * 2;
    var width = 500;
    var height = 500;
    var dims = {'w': width, 'h': height};

    function init() {
        // input -> domain
        // output -> range
        var timer = 0;
        var max = 100;
        var timer_reset = 100;
        var colorRadial = d3.scale.linear()
        .domain([0, max / 2, max]).range(['red', 'green', 'blue']);

        var data2 = function(max){
            return d3.range(max).map(function(d){
                return [rando(d), d + rando(100)];
            });
        }

        function addTitle(container, title) {
            return container.append('text')
            .attr('x', container[0][0].clientWidth / 2)
            .attr('y', 40)
            .attr('class', 'title')
            .attr('font-size', 20)
            .attr('text-anchor', 'middle')
            .text(title);
        }

        var fns = [
            function() {
                var container = getSVG('chaos', dims);
                var lineR = d3.svg.line.radial()
                .angle(function(d){return d[0];})
                .radius(function(d){return d[1];});

                container.selectAll('path')
                .data([data2(width)])
                .enter()
                .append('path')
                .attr('opacity', 0.7)
                .attr('fill', 'none')
                .attr('stroke', randomColor(255))
                .attr('d', lineR);

                addTitle(container, 'Chaos [d3.svg.line.radial]');
            },
            function() {
                var container = getSVG('area', dims);
                var data = smoothData(height, 10, dims);
                var line = d3.svg.line();
                var area = d3.svg.area().x(function(d){
                    return d[0] * Math.PI;
                });

                container.selectAll('path')
                .data([data])
                .enter()
                .append('path')
                .attr('opacity', 0.7)
                .attr('fill', randomColor(255))
                .attr('d', area);

                addTitle(container, 'Random interpolation [d3.svg.area]');
            },
            function() {
                var container = getSVG('radial-area', dims);
                var data = smoothData(height, 10, dims);
                var area = d3.svg.area.radial()
                .radius(360)
                .innerRadius(10)
                .outerRadius(width / 2)
                .startAngle(function(d){return d[0];})
                .endAngle(function(d){return d[1] / 2;});

                container.selectAll('path')
                .data([data])
                .enter()
                .append('path')
                .attr('transform', function(){
                    return 'translate(' + [width / 2, height / 2].join(',') + ')';
                })
                .attr('opacity', 0.7)
                .attr('fill', randomColor(255))
                .attr('d', function(d){
                    return area(d) + 'Z';
                });

                addTitle(container, '[d3.svg.area.radial]');
            },
            function() {
                var container = getSVG('arc', dims);
                var data = smoothData(height, 10, dims);
                var arc = d3.svg.arc()
                .innerRadius(width / 10)
                .outerRadius(width / 4)
                .startAngle(function(d){return d[0] * 0.1;})
                .endAngle(function(d){return d[1] * 0.1;});

                container.selectAll('path')
                .data(data)
                .enter()
                .append('path')
                .transition()
                .duration(function(d, i){return i * 5})
                .attr('transform', function(d) {
                    return 'translate(' + [width / 2, height / 2].join(',') + ')';
                })
                .attr('fill', function(d){return randomColor(255);})
                .attr('d', arc);

                addTitle(container, '[d3.svg.arc]');
            }
        ];

        // call all wrapped functions
        for(var i = 0; i < fns.length; i++) {
            fns[i]();
        }
    }

    return {
        'init': init
    };
})();

window.onload = learnding.init;
<commit_msg>Update day<commit_after>var learnding = (function(){
    'use strict';
    var MARGIN    = 20;
    var PADDING   = 100;
    var tau = Math.PI * 2;
    var width = 500;
    var height = 500;
    var dims = {'w': width, 'h': height};

    function init() {
        // input -> domain
        // output -> range
        var timer = 0;
        var max = 100;
        var timer_reset = 100;
        var colorRadial = d3.scale.linear()
        .domain([0, max / 2, max]).range(['red', 'green', 'blue']);

        var data2 = function(max){
            return d3.range(max).map(function(d){
                return [rando(d), d + rando(100)];
            });
        }

        function addTitle(container, title) {
            return container.append('text')
            .attr('x', container[0][0].clientWidth / 2)
            .attr('y', 40)
            .attr('class', 'title')
            .attr('font-size', 20)
            .attr('text-anchor', 'middle')
            .text(title);
        }

        var fns = [
            function() {
                var container = getSVG('chaos', dims);
                var lineR = d3.svg.line.radial()
                .angle(function(d){return d[0];})
                .radius(function(d){return d[1];});

                container.selectAll('path')
                .data([data2(width)])
                .enter()
                .append('path')
                .attr('opacity', 0.7)
                .attr('fill', 'none')
                .attr('stroke', randomColor(255))
                .attr('d', lineR);

                addTitle(container, 'Chaos [d3.svg.line.radial]');
            },
            function() {
                var container = getSVG('area', dims);
                var data = smoothData(height, 10, dims);
                var area = d3.svg.area().x(function(d){
                    return d[0] * Math.PI;
                });

                container.selectAll('path')
                .data([data])
                .enter()
                .append('path')
                .attr('opacity', 0.7)
                .attr('fill', randomColor(255))
                .attr('d', area);

                addTitle(container, 'Random interpolation [d3.svg.area]');
            },
            function() {
                var container = getSVG('radial-area', dims);
                var data = smoothData(height, 10, dims);
                var area = d3.svg.area.radial()
                .radius(360)
                .innerRadius(10)
                .outerRadius(width / 2)
                .startAngle(function(d){return d[0];})
                .endAngle(function(d){return d[1] / 2;});

                container.selectAll('path')
                .data([data])
                .enter()
                .append('path')
                .attr('transform', function(){
                    return 'translate(' + [width / 2, height / 2].join(',') + ')';
                })
                .attr('opacity', 0.7)
                .attr('fill', randomColor(255))
                .attr('d', function(d){
                    return area(d) + 'Z';
                });

                addTitle(container, '[d3.svg.area.radial]');
            },
            function() {
                var container = getSVG('arc', dims);
                var data = smoothData(height, 10, dims);
                var arc = d3.svg.arc()
                .innerRadius(width / 10)
                .outerRadius(width / 4)
                .startAngle(function(d){return d[0] * 0.1;})
                .endAngle(function(d){return d[1] * 0.1;});

                container.selectAll('path')
                .data(data)
                .enter()
                .append('path')
                .transition()
                .duration(function(d, i){return i * 5})
                .attr('transform', function(d) {
                    return 'translate(' + [width / 2, height / 2].join(',') + ')';
                })
                .attr('fill', function(d){return randomColor(255);})
                .attr('d', arc);

                addTitle(container, '[d3.svg.arc]');
            }
        ];

        // call all wrapped functions
        for(var i = 0; i < fns.length; i++) {
            fns[i]();
        }
    }

    return {
        'init': init
    };
})();

window.onload = learnding.init;
<|endoftext|>


<commit_before>/**
 * @class Denkmal_Component_Event
 * @extends Denkmal_Component_Abstract
 */
var Denkmal_Component_Event = Denkmal_Component_Abstract.extend({

	/** @type String */
	_class: 'Denkmal_Component_Event',

	/** @type {Object} */
	venue: null,

	/** @type {Object} */
	event: null,

	events: {
		'click .showDetails': 'loadDetails'
	},

	loadDetails: function() {
		var handler = this;
		var details = this.findChild('Denkmal_Component_EventDetails');
		if (details) {
			details.$el.slideToggle('fast');
		} else {
			this.loadComponent('Denkmal_Component_EventDetails', {venue: this.venue, event: this.event}, {
				'success': function() {
					this.$el.hide().appendTo(handler.$('.event-content')).slideDown('fast');
				}
			});
		}
	}
});
<commit_msg>loadDetails rename to showDetails<commit_after>/**
 * @class Denkmal_Component_Event
 * @extends Denkmal_Component_Abstract
 */
var Denkmal_Component_Event = Denkmal_Component_Abstract.extend({

	/** @type String */
	_class: 'Denkmal_Component_Event',

	/** @type {Object} */
	venue: null,

	/** @type {Object} */
	event: null,

	events: {
		'click .showDetails': 'showDetails'
	},

	showDetails: function() {
		var handler = this;
		var details = this.findChild('Denkmal_Component_EventDetails');
		if (details) {
			details.$el.slideToggle('fast');
		} else {
			this.loadComponent('Denkmal_Component_EventDetails', {venue: this.venue, event: this.event}, {
				'success': function() {
					this.$el.hide().appendTo(handler.$('.event-content')).slideDown('fast');
				}
			});
		}
	}
});
<|endoftext|>


<commit_before>// @flow weak
/* eslint max-len: "off" */

import React, { Component } from 'react';
import { interval } from 'd3-timer';
import { transition, stop } from '../core/transition';

type Props = {
  /**
   * Boolean value that determines if the child should be rendered or not.
   */
  show: bool,
  /**
  * An object to be used as the starting state.
  */
  start: {},
  /**
   * An object, array of objects, or function that returns an object or array of objects describing how the state should transform on enter.
   */
  enter?: {} | Array<{}> | () => {},
  /**
   * An object, array of objects, or function that returns an object or array of objects describing how the state should transform on update. ***Note:*** although not required, in most cases it make sense to specify an update prop to handle interrupted enter and leave transitions.
   */
  update?: {} | Array<{}> | () => {},
  /**
   * An object, array of objects, or function that returns an object or array of objects describing how the state should transform on leave.
   */
  leave?: {} | Array<{}>,
  /**
   * A function that renders the node.  The function is passed the data and state.
   */
  children: (state: {}) => {},
};

class Animate extends Component {
  static defaultProps = {
    show: true,
  }

  state = this.props.start

  componentWillMount() {
    if (this.props.show === true) {
      this.renderNull = false;
    }
  }

  componentDidMount() {
    const { enter, show } = this.props;

    if (enter && show === true) {
      transition.call(this, typeof enter === 'function' ? enter() : enter);
    }
  }

  componentWillReceiveProps(next) {
    const { show, start, enter, update, leave } = next;

    if (this.props.show === false && this.renderNull === true && show === true) {
      this.renderNull = false;

      this.setState(() => start, () => {
        if (enter) {
          transition.call(this, typeof enter === 'function' ? enter() : enter);
        }
      });
    } else if (this.props.show === true && show === false) {
      if (leave) {
        transition.call(this, typeof leave === 'function' ? leave() : leave);
        this.interval = interval(this.checkTransitionStatus);
      } else {
        this.renderNull = true;
        this.setState((prevState) => prevState); // force render as null
      }
    } else if (show === true && update) {
      if (this.interval) {
        this.interval.stop();
      }

      transition.call(this, typeof update === 'function' ? update() : update);
    }
  }

  componentWillUnmount() {
    if (this.interval) {
      this.interval.stop();
    }

    stop.call(this);
  }

  checkTransitionStatus = () => {
    if (!this.TRANSITION_SCHEDULES) {
      this.interval.stop();

      if (this.props.show === false) {
        this.renderNull = true;
        this.setState((prevState) => prevState); // force render as null
      }
    }
  }

  props: Props;

  interval = null;
  renderNull = true;

  render() {
    if (this.renderNull === true) {
      return null;
    }

    const renderedChildren = this.props.children(this.state);
    return renderedChildren && React.Children.only(renderedChildren);
  }
}

export default Animate;
<commit_msg>start => function<commit_after>// @flow weak
/* eslint max-len: "off" */

import React, { Component } from 'react';
import { interval } from 'd3-timer';
import { transition, stop } from '../core/transition';

type Props = {
  /**
   * Boolean value that determines if the child should be rendered or not.
   */
  show: bool,
  /**
  * An object or function that returns an obejct to be used as the starting state.
  */
  start: {} | () => {},
  /**
   * An object, array of objects, or function that returns an object or array of objects describing how the state should transform on enter.
   */
  enter?: {} | Array<{}> | () => {},
  /**
   * An object, array of objects, or function that returns an object or array of objects describing how the state should transform on update. ***Note:*** although not required, in most cases it make sense to specify an update prop to handle interrupted enter and leave transitions.
   */
  update?: {} | Array<{}> | () => {},
  /**
   * An object, array of objects, or function that returns an object or array of objects describing how the state should transform on leave.
   */
  leave?: {} | Array<{}> | () => {},
  /**
   * A function that renders the node.  The function is passed the data and state.
   */
  children: (state: {}) => {},
};

class Animate extends Component {
  static defaultProps = {
    show: true,
  }

  state = typeof this.props.start === 'function' ? this.props.start() : this.props.start

  componentWillMount() {
    if (this.props.show === true) {
      this.renderNull = false;
    }
  }

  componentDidMount() {
    const { enter, show } = this.props;

    if (enter && show === true) {
      transition.call(this, typeof enter === 'function' ? enter() : enter);
    }
  }

  componentWillReceiveProps(next) {
    const { show, start, enter, update, leave } = next;

    if (this.props.show === false && this.renderNull === true && show === true) {
      this.renderNull = false;

      this.setState(() => (typeof start === 'function' ? start() : start), () => {
        if (enter) {
          transition.call(this, typeof enter === 'function' ? enter() : enter);
        }
      });
    } else if (this.props.show === true && show === false) {
      if (leave) {
        transition.call(this, typeof leave === 'function' ? leave() : leave);
        this.interval = interval(this.checkTransitionStatus);
      } else {
        this.renderNull = true;
        this.setState((prevState) => prevState); // force render as null
      }
    } else if (show === true && update) {
      if (this.interval) {
        this.interval.stop();
      }

      transition.call(this, typeof update === 'function' ? update() : update);
    }
  }

  componentWillUnmount() {
    if (this.interval) {
      this.interval.stop();
    }

    stop.call(this);
  }

  checkTransitionStatus = () => {
    if (!this.TRANSITION_SCHEDULES) {
      this.interval.stop();

      if (this.props.show === false) {
        this.renderNull = true;
        this.setState((prevState) => prevState); // force render as null
      }
    }
  }

  props: Props;

  interval = null;
  renderNull = true;

  render() {
    if (this.renderNull === true) {
      return null;
    }

    const renderedChildren = this.props.children(this.state);
    return renderedChildren && React.Children.only(renderedChildren);
  }
}

export default Animate;
<|endoftext|>