<commit_before>var net = require('net');
var url = require('url');
var querystring = require('querystring');

var device_sockets = [];
var device_server = net.createServer(function (device_conn) {

    var client_sockets = [];
    var device_request = {};
    var device_id = device_sockets.length;

    device_sockets.push(device_conn);

    console.log('device ' + device_id + ' connected');

    device_conn.on('data', function (data) {
        var m, index, data_str = data.toString();

        if (m = data_str.match(/^(GET|POST) (.*) HTTP\/1\.[01]/)) {
            device_request = {};
            device_request.method = m[1];
            device_request.url = m[2];

            if (device_request.method == 'GET') {
                device_request.header = data_str;
                device_request.body = new Buffer(0);
                device_request.end = device_request.header.length > 4 && device_request.header.substr(-4, 4) == '\r\n\r\n';
            } else if (device_request.method == 'POST') {
                index = data_str.indexOf('\r\n\r\n');
                device_request.header = (index == -1) ? data_str : data_str.substr(0, index + 4);
                device_request.length = (m = device_request.header.match(/Content-Length: (\d+)/)) ? m[1] : 0;
                device_request.body = index != -1 ? data.slice(index + 4, data.length) : new Buffer(0);
                device_request.end = index != -1 && device_request.body.length >= device_request.length;
            }
        } else if (!device_request.end && device_request.method == 'GET') {
            device_request.header += data_str;
            device_request.end = device_request.header.length > 4 && device_request.header.substr(-4, 4) == '\r\n\r\n';
        } else if (!device_request.end && device_request.method == 'POST') {
            if (device_request.header.length > 4 && device_request.header.substr(-4, 4) == '\r\n\r\n') {
                device_request.body = Buffer.concat([device_request.body, data]);
                device_request.end = device_request.body.length >= device_request.length;
            } else {
                index = data_str.indexOf('\r\n\r\n');
                device_request.header += (index == -1) ? data_str : data_str.substr(0, index + 4);
                device_request.length = (m = device_request.header.match(/Content-Length: (\d+)/)) ? m[1] : 0;
                device_request.body = index != -1 ? data.slice(index + 4, data.length) : new Buffer(0);
                device_request.end = index != -1 && device_request.body.length >= device_request.length;
            }
        }

        if (!device_request.end) {
            return;
        }

        console.log('device ' + device_id + ' ' + device_request.url);

        var device_param = querystring.parse(device_request.body.toString().trim());

        if (device_request.method == 'POST' &&
            url.parse(device_request.url).pathname == '/device/connect' &&
            device_param.username !== undefined &&
            device_param.password !== undefined
        ) {

            var device_auth = device_param;

            var client_server = net.createServer(function (client_conn) {

                var authorized = false;
                var client_request = {};
                var client_id = client_sockets.length;

                client_sockets.push(client_conn);

                console.log('client ' + [device_id, client_id].join(':')  + ' connected');

                client_conn.on('data', function (data) {
                    var m, index, data_str = data.toString();

                    if (authorized) {
                        device_conn.write(data);
                        return;
                    }

                    if (m = data_str.match(/^(GET|POST) (.*) HTTP\/1\.[01]/)) {
                        client_request = {};
                        client_request.method = m[1];
                        client_request.url = m[2];

                        if (client_request.method == 'GET') {
                            client_request.header = data_str;
                            client_request.body = new Buffer(0);
                            client_request.end = client_request.header.length > 4 && client_request.header.substr(-4, 4) == '\r\n\r\n';
                        } else if (client_request.method == 'POST') {
                            index = data_str.indexOf('\r\n\r\n');
                            client_request.header = (index == -1) ? data_str : data_str.substr(0, index + 4);
                            client_request.length = (m = client_request.header.match(/Content-Length: (\d+)/)) ? m[1] : 0;
                            client_request.body = index != -1 ? data.slice(index + 4, data.length) : new Buffer(0);
                            client_request.end = index != -1 && client_request.body.length >= client_request.length;
                        }
                    } else if (!client_request.end && client_request.method == 'GET') {
                        client_request.header += data_str;
                        client_request.end = client_request.header.length > 4 && client_request.header.substr(-4, 4) == '\r\n\r\n';
                    } else if (!client_request.end && client_request.method == 'POST') {
                        if (client_request.header.length > 4 && client_request.header.substr(-4, 4) == '\r\n\r\n') {
                            client_request.body = Buffer.concat([client_request.body, data]);
                            client_request.end = client_request.body.length >= client_request.length;
                        } else {
                            index = data_str.indexOf('\r\n\r\n');
                            client_request.header += (index == -1) ? data_str : data_str.substr(0, index + 4);
                            client_request.length = (m = client_request.header.match(/Content-Length: (\d+)/)) ? m[1] : 0;
                            client_request.body = index != -1 ? data.slice(index + 4, data.length) : new Buffer(0);
                            client_request.end = index != -1 && client_request.body.length >= client_request.length;
                        }
                    }

                    if (!client_request.end) {
                        return;
                    }

                    var client_param = querystring.parse(client_request.body.toString().trim());

                    console.log('client ' + [device_id, client_id].join(':') + ' ' + client_request.url);

                    if (
                        client_request.method == 'POST' &&
                        url.parse(client_request.url).pathname == '/client/authorize' &&
                        client_param.username !== undefined &&
                        client_param.password !== undefined
                    ) {
                        var client_auth = client_param;

                        if (client_auth.username === device_auth.username && client_auth.password === device_auth.password) {
                            authorized = true;
                            client_conn.write('HTTP/1.1 200 OK\r\n');
                            client_conn.write('Content-Length: 0\r\n\r\n');
                        } else {
                            client_conn.write('HTTP/1.1 403 FORBIDDEN\r\n');
                            client_conn.write('Content-Length: 0\r\n\r\n');
                        }
                        client_request = {};
                        return;
                    }

                    client_conn.write('HTTP/1.1 401 UNAUTHORIZED\r\n');
                    client_conn.write('Content-Length: 0\r\n\r\n');
                    client_request = {};
                    return;
                });

                device_conn.on('data', function (data) {
                    if (authorized) {
                        client_conn.write(data);
                        return;
                    }
                });

                client_conn.on('error', function (error) {
                    console.log(error);
                });

                client_conn.on('close', function (had_error) {
                    console.log('client ' + [device_id, client_id].join(':') + ' disconnected');

                    client_sockets[client_id] = false;
                });
            });

            client_server.listen(0, '127.0.0.1', function () {
                var port = String(client_server.address().port);

                console.log('client server listening on port ' + port + ' for device ' + device_id);

                device_conn.write('HTTP/1.1 200 OK\r\n');
                device_conn.write('Content-Type: application/json\r\n');
                device_conn.write('Content-Length: ' + (port.length + 18) + '\r\n\r\n');
                device_conn.write('{"client_port":"' + port + '"}');
            });

            device_request = {};
            return;
        }

        device_conn.write('HTTP/1.1 400 BAD REQUEST\r\n');
        device_conn.write('Content-Length: 0\r\n\r\n');
        device_request = {};
        return;
    });

    device_conn.on('error', function (error) {
        console.log(error);
    });

    device_conn.on('close', function (had_error) {
        console.log('device ' + device_id + ' disconnected');

        device_sockets[device_id] = false;

        for (var i = 0; i < client_sockets.length; i++) {
            if (client_sockets[i])
                client_sockets[i].destroy();
        }
    });
});

device_server.listen(3000, function () {
    console.log('device server listening on port ' + device_server.address().port);
});
<commit_msg>unbind device conn event when client disconnect<commit_after>var net = require('net');
var url = require('url');
var querystring = require('querystring');

var device_sockets = [];
var device_server = net.createServer(function (device_conn) {

    var client_sockets = [];
    var device_request = {};
    var device_id = device_sockets.length;

    device_sockets.push(device_conn);

    console.log('device ' + device_id + ' connected');

    device_conn.on('data', function (data) {
        var m, index, data_str = data.toString();

        if (m = data_str.match(/^(GET|POST) (.*) HTTP\/1\.[01]/)) {
            device_request = {};
            device_request.method = m[1];
            device_request.url = m[2];

            if (device_request.method == 'GET') {
                device_request.header = data_str;
                device_request.body = new Buffer(0);
                device_request.end = device_request.header.length > 4 && device_request.header.substr(-4, 4) == '\r\n\r\n';
            } else if (device_request.method == 'POST') {
                index = data_str.indexOf('\r\n\r\n');
                device_request.header = (index == -1) ? data_str : data_str.substr(0, index + 4);
                device_request.length = (m = device_request.header.match(/Content-Length: (\d+)/)) ? m[1] : 0;
                device_request.body = index != -1 ? data.slice(index + 4, data.length) : new Buffer(0);
                device_request.end = index != -1 && device_request.body.length >= device_request.length;
            }
        } else if (!device_request.end && device_request.method == 'GET') {
            device_request.header += data_str;
            device_request.end = device_request.header.length > 4 && device_request.header.substr(-4, 4) == '\r\n\r\n';
        } else if (!device_request.end && device_request.method == 'POST') {
            if (device_request.header.length > 4 && device_request.header.substr(-4, 4) == '\r\n\r\n') {
                device_request.body = Buffer.concat([device_request.body, data]);
                device_request.end = device_request.body.length >= device_request.length;
            } else {
                index = data_str.indexOf('\r\n\r\n');
                device_request.header += (index == -1) ? data_str : data_str.substr(0, index + 4);
                device_request.length = (m = device_request.header.match(/Content-Length: (\d+)/)) ? m[1] : 0;
                device_request.body = index != -1 ? data.slice(index + 4, data.length) : new Buffer(0);
                device_request.end = index != -1 && device_request.body.length >= device_request.length;
            }
        }

        if (!device_request.end) {
            return;
        }

        console.log('device ' + device_id + ' ' + device_request.url);

        var device_param = querystring.parse(device_request.body.toString().trim());

        if (device_request.method == 'POST' &&
            url.parse(device_request.url).pathname == '/device/connect' &&
            device_param.username !== undefined &&
            device_param.password !== undefined
        ) {

            var device_auth = device_param;

            var client_server = net.createServer(function (client_conn) {

                var authorized = false;
                var client_request = {};
                var client_id = client_sockets.length;
                var client_hook;

                client_sockets.push(client_conn);

                console.log('client ' + [device_id, client_id].join(':')  + ' connected');

                client_conn.on('data', function (data) {
                    var m, index, data_str = data.toString();

                    if (authorized) {
                        device_conn.write(data);
                        return;
                    }

                    if (m = data_str.match(/^(GET|POST) (.*) HTTP\/1\.[01]/)) {
                        client_request = {};
                        client_request.method = m[1];
                        client_request.url = m[2];

                        if (client_request.method == 'GET') {
                            client_request.header = data_str;
                            client_request.body = new Buffer(0);
                            client_request.end = client_request.header.length > 4 && client_request.header.substr(-4, 4) == '\r\n\r\n';
                        } else if (client_request.method == 'POST') {
                            index = data_str.indexOf('\r\n\r\n');
                            client_request.header = (index == -1) ? data_str : data_str.substr(0, index + 4);
                            client_request.length = (m = client_request.header.match(/Content-Length: (\d+)/)) ? m[1] : 0;
                            client_request.body = index != -1 ? data.slice(index + 4, data.length) : new Buffer(0);
                            client_request.end = index != -1 && client_request.body.length >= client_request.length;
                        }
                    } else if (!client_request.end && client_request.method == 'GET') {
                        client_request.header += data_str;
                        client_request.end = client_request.header.length > 4 && client_request.header.substr(-4, 4) == '\r\n\r\n';
                    } else if (!client_request.end && client_request.method == 'POST') {
                        if (client_request.header.length > 4 && client_request.header.substr(-4, 4) == '\r\n\r\n') {
                            client_request.body = Buffer.concat([client_request.body, data]);
                            client_request.end = client_request.body.length >= client_request.length;
                        } else {
                            index = data_str.indexOf('\r\n\r\n');
                            client_request.header += (index == -1) ? data_str : data_str.substr(0, index + 4);
                            client_request.length = (m = client_request.header.match(/Content-Length: (\d+)/)) ? m[1] : 0;
                            client_request.body = index != -1 ? data.slice(index + 4, data.length) : new Buffer(0);
                            client_request.end = index != -1 && client_request.body.length >= client_request.length;
                        }
                    }

                    if (!client_request.end) {
                        return;
                    }

                    var client_param = querystring.parse(client_request.body.toString().trim());

                    console.log('client ' + [device_id, client_id].join(':') + ' ' + client_request.url);

                    if (
                        client_request.method == 'POST' &&
                        url.parse(client_request.url).pathname == '/client/authorize' &&
                        client_param.username !== undefined &&
                        client_param.password !== undefined
                    ) {
                        var client_auth = client_param;

                        if (client_auth.username === device_auth.username && client_auth.password === device_auth.password) {
                            authorized = true;
                            client_conn.write('HTTP/1.1 200 OK\r\n');
                            client_conn.write('Content-Length: 0\r\n\r\n');
                        } else {
                            client_conn.write('HTTP/1.1 403 FORBIDDEN\r\n');
                            client_conn.write('Content-Length: 0\r\n\r\n');
                        }
                        client_request = {};
                        return;
                    }

                    client_conn.write('HTTP/1.1 401 UNAUTHORIZED\r\n');
                    client_conn.write('Content-Length: 0\r\n\r\n');
                    client_request = {};
                    return;
                });

                device_conn.on('data', client_hook = function (data) {
                    if (authorized) {
                        client_conn.write(data);
                        return;
                    }
                });

                client_conn.on('error', function (error) {
                    console.log(error);
                });

                client_conn.on('close', function (had_error) {
                    console.log('client ' + [device_id, client_id].join(':') + ' disconnected');

                    client_sockets[client_id] = false;
                    device_conn.removeListener('data', client_hook);
                });
            });

            client_server.listen(0, '127.0.0.1', function () {
                var port = String(client_server.address().port);

                console.log('client server listening on port ' + port + ' for device ' + device_id);

                device_conn.write('HTTP/1.1 200 OK\r\n');
                device_conn.write('Content-Type: application/json\r\n');
                device_conn.write('Content-Length: ' + (port.length + 18) + '\r\n\r\n');
                device_conn.write('{"client_port":"' + port + '"}');
            });

            device_request = {};
            return;
        }

        device_conn.write('HTTP/1.1 400 BAD REQUEST\r\n');
        device_conn.write('Content-Length: 0\r\n\r\n');
        device_request = {};
        return;
    });

    device_conn.on('error', function (error) {
        console.log(error);
    });

    device_conn.on('close', function (had_error) {
        console.log('device ' + device_id + ' disconnected');

        device_sockets[device_id] = false;

        for (var i = 0; i < client_sockets.length; i++) {
            if (client_sockets[i])
                client_sockets[i].destroy();
        }
    });
});

device_server.listen(3000, function () {
    console.log('device server listening on port ' + device_server.address().port);
});
<|endoftext|>


<commit_before>require.paths.unshift("lib");

var fishback = require("fishback");

var server = fishback.createServer();

server.addResFilter(function (res) {
    // If origin doesn't return a cache-control header, make everything cacheable
    // for 0 seconds.  This seems useless, but it means that if the client
    // explicitly passes max-stale, it will get a cached response.
    if (!("cache-control" in res.headers)) {
        res.headers["cache-control"] = "max-age=0";
    }
});

server.listen();
<commit_msg>Add #!/usr/local/bin/node.<commit_after>#!/usr/local/bin/node

require.paths.unshift("lib");

var fishback = require("fishback");

var server = fishback.createServer();

server.addResFilter(function (res) {
    // If origin doesn't return a cache-control header, make everything cacheable
    // for 0 seconds.  This seems useless, but it means that if the client
    // explicitly passes max-stale, it will get a cached response.
    if (!("cache-control" in res.headers)) {
        res.headers["cache-control"] = "max-age=0";
    }
});

server.listen();
<|endoftext|>


<commit_before>// var netanos = require('netanos');
var netanos = require('./Netanos.js');
var input = "Max and Ben spent more than 1000 hours on writing the software. They started in August 2016 in Amsterdam.";

netanos.anon(input, function(output) {
    console.log(output);
});
<commit_msg>Updated example<commit_after>// var netanos = require('netanos');
var netanos = require('./Netanos.js');
var input = "Max and Ben spent more than 1000 hours on writing the software. They started in August 2016 in Amsterdam.";

var entities = {
    person: true,
    organization: true,
    currency: true,
    date: true,
    location: true
};

netanos.anon(input, entities, function(output) {
    console.log(output);
});
<|endoftext|>


<commit_before>// Requires
const Discord = require('discord.js')

// Create an instance of a Discord client
const client = new Discord.Client()

// The bot is ready
client.on('ready', () => {
  console.log('Bot Started')
})

client.on('message', (message) => {// when message is sent
  // Set the prefix
  let prefix = config.prefix;

  // Exit and stop if it's not there
  if (!message.content.startsWith(prefix) || message.author.bot) return;

  if (message.content ===("<>")){ // when message is <>
      message.channel.sendMessage("Shinies!"); // send running message into the channel where the message was sent
  }

  if (message.content.startsWith(prefix + 'help'))
  {
    message.channel.send('I don\'t know what to help with yet!');
  }
  else if (message.content.startsWith(prefix + 'idoruu'))
  {
    message.channel.send('http://i.imgur.com/Emk9LEb.png!');
  }

  else if(message.content.startsWith(config.prefix + 'prefix'))
  {
    // if it's not me it won't work
    if(message.author.id !== config.ownerID) return;
  // Gets the prefix from the command (eg. "!prefix +" it will take the "+" from it)
  let newPrefix = message.content.split(' ').slice(1, 2)[0];
  // change the configuration in memory
  config.prefix = newPrefix;

  // Now we have to save the file.
  fs.writeFile('./config.json', JSON.stringify(config));
  }
  else if(message.content.startsWith(config.prefix + 'waifu'))
  {
    // if it's not me it won't work
    if(message.author.id !== config.ownerID)
    {
      message.channel.send('Not AA-senpai go away');
    }
    else
    {
    message.channel.send('AA-senpai!');
    }

  }
})
client.login(process.env.BOT_TOKEN)
<commit_msg>Added Config proper<commit_after>// Requires
const Discord = require('discord.js')
const fs = require('fs')
const config = require('./config.json');
// Create an instance of a Discord client
const client = new Discord.Client()

// The bot is ready
client.on('ready', () => {
  console.log('Bot Started')
})

client.on('message', (message) => {// when message is sent
  // Set the prefix
  let prefix = config.prefix;

  // Exit and stop if it's not there
  if (!message.content.startsWith(prefix) || message.author.bot) return;

  if (message.content ===("<>")){ // when message is <>
      message.channel.sendMessage("Shinies!"); // send running message into the channel where the message was sent
  }

  if (message.content.startsWith(prefix + 'help'))
  {
    message.channel.send('I don\'t know what to help with yet!');
  }
  else if (message.content.startsWith(prefix + 'idoruu'))
  {
    message.channel.send('http://i.imgur.com/Emk9LEb.png!');
  }

  else if(message.content.startsWith(config.prefix + 'prefix'))
  {
    // if it's not me it won't work
    if(message.author.id !== config.ownerID) return;
  // Gets the prefix from the command (eg. "!prefix +" it will take the "+" from it)
  let newPrefix = message.content.split(' ').slice(1, 2)[0];
  // change the configuration in memory
  config.prefix = newPrefix;

  // Now we have to save the file.
  fs.writeFile('./config.json', JSON.stringify(config));
  }
  else if(message.content.startsWith(config.prefix + 'waifu'))
  {
    // if it's not me it won't work
    if(message.author.id !== config.ownerID)
    {
      message.channel.send('Not AA-senpai go away');
    }
    else
    {
    message.channel.send('AA-senpai!');
    }

  }
})
client.login(process.env.BOT_TOKEN)
<|endoftext|>


<commit_before>if (!window.J) window.J = {

  _modules: {},

  module: function (name, obj) {
    this._modules[name] = obj;
  },

  init: function () {
    this.injectDependency();
    this.initModules();
  },

  /**
   * Inject module dependency to variables that start with '$'.
   * e.g. if object has $some variable, module 'some' is assigned to $some.
   */
  injectDependency: function () {
    var t = this;
    t.eachModule(function (name, obj) {
      t.eachProperty(obj, function (k, v) {
        if (k.substring(0, 1) === '$') {
          var refName = k.substring(1);
          this[k] = t.get(refName);
        }
      });
    });
  },

  /**
   * @param callback(name, obj)
   */
  eachModule: function (callback) {
    var ms = this._modules;
    this.eachProperty(ms, callback);
  },

  /**
   * @param obj
   * @param callback(k, v)
   */
  eachProperty: function (obj, callback) {
    var k, v;
    for (k in obj) {
      if (obj.hasOwnProperty(k)) {
        v = obj[k];
        callback.call(obj, k, v);
      }
    }
  },

  /**
   * get module by name
   */
  get: function (name) {
    return this._modules[name];
  },

  /**
   * init method of each module is called
   */
  initModules: function () {
    this.eachModule(function (name, obj) {
      if (typeof obj.init === 'function') {
        obj.init();
      }
    });
  },

	/**
	 * clear module
	 * @param name name[, name, ...]
	 */
  clear: function () {
    var args = Array.prototype.slice.call(arguments),
    	modules = this._modules,
    	i, len = args.length;

    for (i = 0; i < len; i++) {
    	delete modules[args[i]];
    }
  }

};
/**
 * call async init function if script downloaded
 */
window.setTimeout(function () {
  if (window.jAsyncInit && !window.jAsyncInit.hasRun) {
    window.jAsyncInit.hasRun = true;
    window.jAsyncInit();
  }
}, 0);

/**
 * Util Module
 */
J.module('util', {

  /**
   * @param arr
   * @param callback(i, v)
   */
  eachArray: function (arr, callback) {
    var i, v, len = arr.length;
    for (i = 0; i < len; i++) {
      v = arr[i];
      callback.call(arr, i, v);
    }
  },

  /**
   * @param obj
   * @param callback(k, v)
   */
  eachProperty: function (obj, callback) {
    var k, v;
    for (k in obj) {
      if (obj.hasOwnProperty(k)) {
        v = obj[k];
        callback.call(obj, k, v);
      }
    }
  },

  /**
   * @param fn
   * @param context
   * @param data, ...
   */
  bind: function (fn, context) {
    var slice = Array.prototype.slice,
      args = slice.call(arguments, 2);

    return function () {
      fn.apply(context, args.concat(slice.call(arguments)));
    };
  },

  guid: function () {
    return 'j' + (Math.random() * (1 << 30)).toString(32).replace('.', '');
  }
});

/**
 * Pub/Sub Module
 */
J.module('ps', {

  $util: null,

  /**
   * subscribers map.
   * e.g. If you subscribe 'some.one.*' and 'some.two',..
   * {
   *   some: {
   *     one: {
   *       *: {
   *         callbackId: callback
   *       }
   *     }
   *   },
   *   two: {
   *     callbackId: callback
   *   }
   * }
   */
  _subscribersMap: {},

  /**
   * Subscribe topic.
   * You can seperate topics by dot(.), and subscribe all topics using asterisk(*).
   * e.g. 'some.topic.*'
   *
   * @param topic string or *
   * @param callback(data)
   * @return subscribed callback id
   */
  subscribe: function (topic, callback) {
  	var callbackId = this.$util.guid();

  	this.eachSubscriberMapDepth(topic, function (n, m, map, isLast) {
  		if (isLast) {
  		  m[callbackId] = callback;
  		}
  	});

    return callbackId;
  },

  /**
   * Do callback for each subscribers map depth
   *
   * @param topic
   * @param callback(n, m, map, isLast)
   *           n (string) depth name
   *           m (object) current map
   *           map (object) parent map
   *           isLast (boolean) is last depth
   */
  eachSubscriberMapDepth: function (topic, callback) {
  	var map = this._subscribersMap,
  	  topics = topic.split('.'),
  	  len = topics.length,
  	  n, m;

  	for (var i = 0; i < len; i++) {
  		n = topics[i];
  		m = map[n] = (map[n] || {});

  		callback(n, m, map, i + 1 === len);

  		map = m;
  	}
  },

  unsubscribe: function (topic, callbackId) {
  	this.eachSubscriberMapDepth(topic, function (n, m, map, isLast) {
  		if (isLast) {
  		  delete m[callbackId];
  		}
  	});
  },

  publish: function (topic, data) {
    var t = this,
      runCallback = function (m) {
    		t.$util.eachProperty(m, function (k, v) {
    			if (typeof v === 'function') {
    				v(data);
    			}
    		});
    	};

    this.eachSubscriberMapDepth(topic, function (n, m, map, isLast) {
    	runCallback(map['*']);

    	if (isLast) {
    		runCallback(m);
    	}
    });
  },

  clear: function (topic) {
  	this.eachSubscriberMapDepth(topic, function (n, m, map, isLast) {
  		if (isLast) {
  		  delete map[n];
  		}
  	});
  }
});
<commit_msg>modify annotation<commit_after>if (!window.J) window.J = {

  _modules: {},

  module: function (name, obj) {
    this._modules[name] = obj;
  },

  init: function () {
    this.injectDependency();
    this.initModules();
  },

  /**
   * Inject module dependency to variables that start with '$'.
   * e.g. if object has $some variable, module 'some' is assigned to $some.
   */
  injectDependency: function () {
    var t = this;
    t.eachModule(function (name, obj) {
      t.eachProperty(obj, function (k, v) {
        if (k.substring(0, 1) === '$') {
          var refName = k.substring(1);
          this[k] = t.get(refName);
        }
      });
    });
  },

  /**
   * @param callback(name, obj)
   */
  eachModule: function (callback) {
    var ms = this._modules;
    this.eachProperty(ms, callback);
  },

  /**
   * @param obj
   * @param callback(k, v)
   */
  eachProperty: function (obj, callback) {
    var k, v;
    for (k in obj) {
      if (obj.hasOwnProperty(k)) {
        v = obj[k];
        callback.call(obj, k, v);
      }
    }
  },

  /**
   * get module by name
   */
  get: function (name) {
    return this._modules[name];
  },

  /**
   * init method of each module is called
   */
  initModules: function () {
    this.eachModule(function (name, obj) {
      if (typeof obj.init === 'function') {
        obj.init();
      }
    });
  },

  /**
   * clear module
   * @param name name[, name, ...]
   */
  clear: function () {
    var args = Array.prototype.slice.call(arguments),
    	modules = this._modules,
    	i, len = args.length;

    for (i = 0; i < len; i++) {
    	delete modules[args[i]];
    }
  }

};
/**
 * call async init function if script downloaded
 */
window.setTimeout(function () {
  if (window.jAsyncInit && !window.jAsyncInit.hasRun) {
    window.jAsyncInit.hasRun = true;
    window.jAsyncInit();
  }
}, 0);

/**
 * Util Module
 */
J.module('util', {

  /**
   * Do callback for each array
   * @param arr
   * @param callback(i, v)
   */
  eachArray: function (arr, callback) {
    var i, v, len = arr.length;
    for (i = 0; i < len; i++) {
      v = arr[i];
      callback.call(arr, i, v);
    }
  },

  /**
   * Do callback for each property
   * @param obj
   * @param callback(k, v)
   */
  eachProperty: function (obj, callback) {
    var k, v;
    for (k in obj) {
      if (obj.hasOwnProperty(k)) {
        v = obj[k];
        callback.call(obj, k, v);
      }
    }
  },

  /**
   * Bind function to context object
   * @param fn
   * @param context
   * @param data, ...
   */
  bind: function (fn, context) {
    var slice = Array.prototype.slice,
      args = slice.call(arguments, 2);

    return function () {
      fn.apply(context, args.concat(slice.call(arguments)));
    };
  },

  /**
   * Create random unique id
   */
  guid: function () {
    return 'j' + (Math.random() * (1 << 30)).toString(32).replace('.', '');
  }
});

/**
 * Pub/Sub Module
 */
J.module('ps', {

  $util: null,

  /**
   * Subscribers map.
   * e.g. If you subscribe 'some.one.*' and 'some.two',..
   * {
   *   some: {
   *     one: {
   *       *: {
   *         callbackId: callback
   *       }
   *     }
   *   },
   *   two: {
   *     callbackId: callback
   *   }
   * }
   */
  _subscribersMap: {},

  /**
   * Subscribe topic.
   * You can seperate topics by dot(.), and subscribe all topics using asterisk(*).
   * e.g. 'some.topic.*'
   *
   * @param topic string or *
   * @param callback(data)
   * @return subscribed callback id
   */
  subscribe: function (topic, callback) {
  	var callbackId = this.$util.guid();

  	this.eachSubscriberMapDepth(topic, function (n, m, map, isLast) {
  		if (isLast) {
  		  m[callbackId] = callback;
  		}
  	});

    return callbackId;
  },

  /**
   * Do callback for each subscribers map depth
   *
   * @param topic
   * @param callback(n, m, map, isLast)
   *           n (string) depth name
   *           m (object) current map
   *           map (object) parent map
   *           isLast (boolean) is last depth
   */
  eachSubscriberMapDepth: function (topic, callback) {
  	var map = this._subscribersMap,
  	  topics = topic.split('.'),
  	  len = topics.length,
  	  n, m;

  	for (var i = 0; i < len; i++) {
  		n = topics[i];
  		m = map[n] = (map[n] || {});

  		callback(n, m, map, i + 1 === len);

  		map = m;
  	}
  },

  /**
   * Unsubscribe specific callback
   */
  unsubscribe: function (topic, callbackId) {
  	this.eachSubscriberMapDepth(topic, function (n, m, map, isLast) {
  		if (isLast) {
  		  delete m[callbackId];
  		}
  	});
  },

  /**
   * Publish topic with data
   * @param topic (string) The topic has seperator dot('.'), and does not recommand include '*'.
   * @param data (object)
   */
  publish: function (topic, data) {
    var t = this,
      runCallback = function (m) {
    		t.$util.eachProperty(m, function (k, v) {
    			if (typeof v === 'function') {
    				v(data);
    			}
    		});
    	};

    this.eachSubscriberMapDepth(topic, function (n, m, map, isLast) {
    	runCallback(map['*']);

    	if (isLast) {
    		runCallback(m);
    	}
    });
  },

  /**
   * Remove subscribers of specific topic
   */
  clear: function (topic) {
  	this.eachSubscriberMapDepth(topic, function (n, m, map, isLast) {
  		if (isLast) {
  		  delete map[n];
  		}
  	});
  }
});
<|endoftext|>


<commit_before>/**
 *  set.js
 *
 *  David Janes
 *  IOTDB
 *  2017-04-26
 *
 *  Copyright (2013-2018) David Janes
 */

"use strict";

const _ = require("iotdb-helpers");

const assert = require("assert");

/**
 *  Accepts: self.redis, self.key, self.value
 *  Produces: N/A
 */
const set = _.promise.make((self, done) => {
    const method = "set";

    assert.ok(self.redis, `${method}: expected self.redis`)
    assert.ok(_.is.String(self.key), `${method}: expected self.key to be a String`)
    assert.ok(_.is.String(self.value), `${method}: expected self.value to be a String`)

    self.redis.set(self.key, self.value, error => {
        if (error) {
            return done(error);
        }

        done(null, self);
    })
})

/**
 *  Accepts: self.redis, self.key, self.json
 *  Produces: N/A
 */
const set_json = _.promise.make((self, done) => {
    const method = "json.set";

    assert.ok(self.redis, `${method}: expected self.redis`)
    assert.ok(_.is.String(self.key), `${method}: expected self.key to be a String`)
    assert.ok(_.is.JSON(self.json), `${method}: expected self.json to be a JSONable Object`)

    self.redis.set(self.key, JSON.stringify(self.json), error => {
        if (error) {
            return done(error);
        }

        done(null, self);
    })
})

/**
 *  Paramaterized
 */
const set_p = (key, value) => _.promise.make((self, done) => {
    const method = "set.p";

    _.promise.make(self)
        .then(_.promise.add({
            key: key || self.key,
            value: value || self.value,
        }))
        .then(set)
        .then(_.promise.done(done, self))
        .catch(done)
})

const set_json_p = (key, json) => _.promise.make((self, done) => {
    const method = "set.json.p";

    _.promise.make(self)
        .then(_.promise.add({
            key: key || self.key,
            json: json || self.json,
        }))
        .then(set_json)
        .then(_.promise.done(done, self))
        .catch(done)
})

/**
 *  API
 */
exports.set = set;
exports.set.p = set_p;
exports.set.json = set_json;
exports.set.json.p = set_json_p;
<commit_msg>curryied version add LPUSH/RPUSH<commit_after>/**
 *  set.js
 *
 *  David Janes
 *  IOTDB
 *  2017-04-26
 *
 *  Copyright (2013-2018) David Janes
 */

"use strict";

const _ = require("iotdb-helpers");

const assert = require("assert");

/**
 *  Accepts: self.redis, self.key, self.value
 *  Produces: N/A
 */
const key_value = (method, redis_method) => _.promise.make((self, done) => {
    assert.ok(self.redis, `${method}: expected self.redis`)
    assert.ok(_.is.String(self.key), `${method}: expected self.key to be a String`)
    assert.ok(_.is.String(self.value), `${method}: expected self.value to be a String`)

    self.redis[redis_method](self.key, self.value, error => {
        if (error) {
            return done(error);
        }

        done(null, self);
    })
})

/**
 *  Accepts: self.redis, self.key, self.json
 *  Produces: N/A
 */
const key_json = (method, redis_method) => _.promise.make((self, done) => {
    assert.ok(self.redis, `${method}: expected self.redis`)
    assert.ok(_.is.String(self.key), `${method}: expected self.key to be a String`)
    assert.ok(_.is.JSON(self.json), `${method}: expected self.json to be a JSONable Object`)

    self.redis[redis_method](self.key, JSON.stringify(self.json), error => {
        if (error) {
            return done(error);
        }

        done(null, self);
    })
})

/**
 *  Paramaterized
 */
const key_value_p = (method, underlying) => (key, value) => _.promise.make((self, done) => {
    _.promise.make(self)
        .then(_.promise.add({
            key: key || self.key,
            value: value || self.value,
        }))
        .then(underlying)
        .then(_.promise.done(done, self))
        .catch(done)
})

const key_json_p = (method, underlying) => (key, json) => _.promise.make((self, done) => {
    _.promise.make(self)
        .then(_.promise.add({
            key: key || self.key,
            json: json || self.json,
        }))
        .then(underlying)
        .then(_.promise.done(done, self))
        .catch(done)
})

/**
 *  API
 *
 *  Note the highly curried generalized functions
 */
exports.set = key_value("set", "set");
exports.set.p = key_value_p("set.p", exports.set);
exports.set.json = key_json("set.json", "set");
exports.set.json.p = key_json_p("set.json.p", exports.set.json)

exports.rpush = key_value("rpush", "rpush");
exports.rpush.p = key_value_p("rpush.p", exports.rpush);
exports.rpush.json = key_json("rpush.json", "rpush");
exports.rpush.json.p = key_json_p("rpush.json.p", exports.rpush.json)

exports.lpush = key_value("lpush", "lpush");
exports.lpush.p = key_value_p("lpush.p", exports.lpush);
exports.lpush.json = key_json("lpush.json", "lpush");
exports.lpush.json.p = key_json_p("lpush.json.p", exports.lpush.json)
<|endoftext|>


<commit_before>/*
 *   Copyright 2012 OSBI Ltd
 *
 *   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.
 */

/**
 * The "about us" dialog
 */
var AboutModal = Modal.extend({
    type: 'login',

    message: '
' +
                 '
' +
                     '' + Settings.VERSION + '' +
                     'http://saiku.meteorite.bi' +
                 '
' +
                 '
' +
                     '
License Info
' +
                     '
' +
                         '
Type:
' +
                         '
Expires:
' +
                         '
Number of users:
' +
                         '
Lincesed to:  -
' +
                         '
Order more licenses here
' +
                     '
' +
                 '
' +
                 '
' +
                     'Want to help? Make a donation or contribute to the code!' +
                     'Powered by  www.meteorite.bi' +
                 '
' +
             '
',

    events: {
        'click .dialog_footer a' : 'call'
    },

    initialize: function(args) {
        _.extend(this, args);

        this.options.title = 'About ' + Settings.VERSION;

        this.bind('open', function() {
            this.render_license_info();
        });
    },

    render_license_info: function() {
        var licenseType = Settings.LICENSE.licenseType === 'community_edition'
            ? 'Open Source License'
            : Settings.LICENSE.licenseType;
        var expiration;

        if (Settings.LICENSE.expiration) {
            expiration = new Date(parseFloat(Settings.LICENSE.expiration));
            this.$el.find('.item-license-expiration').show();
            this.$el.find('.license-expiration').text(expiration.toLocaleDateString());
        }

        this.$el.find('.license-type').text(licenseType);
        this.$el.find('.license-user-limit').text(Settings.LICENSE.userLimit);
        this.$el.find('.license-name').text(Settings.LICENSE.name);
        this.$el.find('.license-email').text(Settings.LICENSE.email);
    }
});
<commit_msg>fix typo<commit_after>/*
 *   Copyright 2012 OSBI Ltd
 *
 *   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.
 */

/**
 * The "about us" dialog
 */
var AboutModal = Modal.extend({
    type: 'login',

    message: '
' +
                 '
' +
                     '' + Settings.VERSION + '' +
                     'http://saiku.meteorite.bi' +
                 '
' +
                 '
' +
                     '
License Info
' +
                     '
' +
                         '
Type:
' +
                         '
Expires:
' +
                         '
Number of users:
' +
                         '
Licensed to:  -
' +
                         '
Order more licenses here
' +
                     '
' +
                 '
' +
                 '
' +
                     'Want to help? Make a donation or contribute to the code!' +
                     'Powered by  www.meteorite.bi' +
                 '
' +
             '
',

    events: {
        'click .dialog_footer a' : 'call'
    },

    initialize: function(args) {
        _.extend(this, args);

        this.options.title = 'About ' + Settings.VERSION;

        this.bind('open', function() {
            this.render_license_info();
        });
    },

    render_license_info: function() {
        var licenseType = Settings.LICENSE.licenseType === 'community_edition'
            ? 'Open Source License'
            : Settings.LICENSE.licenseType;
        var expiration;

        if (Settings.LICENSE.expiration) {
            expiration = new Date(parseFloat(Settings.LICENSE.expiration));
            this.$el.find('.item-license-expiration').show();
            this.$el.find('.license-expiration').text(expiration.toLocaleDateString());
        }

        this.$el.find('.license-type').text(licenseType);
        this.$el.find('.license-user-limit').text(Settings.LICENSE.userLimit);
        this.$el.find('.license-name').text(Settings.LICENSE.name);
        this.$el.find('.license-email').text(Settings.LICENSE.email);
    }
});
<|endoftext|>


<commit_before>exports.version=1443978877
<commit_msg>update version since the subtle synctable fixes are very important<commit_after>exports.version=1444022562
<|endoftext|>


<commit_before>// Copyright 2015 Google Inc. All rights reserved.
//
// 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.

import JsFileSystem from 'axiom/fs/js/file_system';
import DomFileSystem from 'axiom/fs/dom/file_system';
import GDriveFileSystem from 'axiom/fs/gdrive/file_system';
import FileSystemManager from 'axiom/fs/base/file_system_manager';
import ExecuteContext from 'axiom/fs/base/execute_context';
import StdioSource from 'axiom/fs/stdio_source';
import Path from 'axiom/fs/path';

import scriptMain from 'shell/exe/script';
import TerminalView from 'shell/terminal';
import washExecutables from 'wash/exe_modules';

var welcomeMessage = [
  'Welcome to the Axiom web_shell sample.',
  '',
  'This is a cross-browser interactive shell written in JavaScript which ',
  'can be extended with new commands at runtime.',
  '',
  'To get started, try:',
  ' * \x1b[1mmount\x1b[m to see a list of mounted filesystems.',
  ' * \x1b[1mls\x1b[m to see the contents of the current directory.',
  ' * \x1b[1mls jsfs:/exe\x1b[m to list the executables.',
  ' * \x1b[1mcd <path>\x1b[m to change your working directory.',
  ' * \x1b[1menv-get\x1b[m, \x1b[1menv-set\x1b[m, and \x1b[1menv-del\x1b[m ' +
      'to view and modify environment variables.',
  ' * \x1b[1mscript <url>\x1b[m to load third party scripts (but be careful).',
  '',
  'For more information, please visit: \x1b[1mhttp://goo.gl/DmDqct\x1b[m',
  ''
].join('\r\n');

export var main = function() {
  var fsm = new FileSystemManager();
  var jsfs = new JsFileSystem(fsm, 'jsfs');
  fsm.mount(jsfs);

  // Add executables to new filesystem
  jsfs.rootDirectory.mkdir('exe')
    .then(function( /** JsDirectory */ jsdir) {
      jsdir.install({
        'script': scriptMain
      });
      jsdir.install(washExecutables);
    })
    .then(function() {
      return DomFileSystem.mount(fsm, 'html5', 'permanent')
        .then(function() {
          return DomFileSystem.mount(fsm, 'tmp', 'temporary');
        })
        .catch(function(e) {
          console.log("Error mounting DomFileSystem", e);
        });
    })
    .then(function() {
      return launchHterm(fsm);
    }).catch(function(e) {
      console.log('Error lauching app:', e);
    });
};

export default main;

var launchHterm = function(fsm) {
  var stdioSource = new StdioSource();
  return fsm.createExecuteContext(
    new Path('jsfs:exe/wash'), stdioSource.stdio, {})
    .then(function (/** ExecuteContext */cx) {
      var tv = new TerminalView();

      tv.println(welcomeMessage);

      cx.setEnvs({
        '@PATH': ['jsfs:/exe'],
        '$TERM': 'xterm-256color',
        '$HOME': 'html5:/',
        '$HISTFILE': 'html5:/.wash_history'
      });
      tv.execute(stdioSource, cx);

      setTimeout(function(tv) {
        tv.stdioSource.stdin.write('import');
        tv.stdioSource.stdin.write('\r');
      }.bind(this, tv), 1000)

      // debugger;

      return Promise.resolve(null);
  });
};
<commit_msg>DEV: Test cases for extension stream mounting<commit_after>// Copyright 2015 Google Inc. All rights reserved.
//
// 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.

import JsFileSystem from 'axiom/fs/js/file_system';
import DomFileSystem from 'axiom/fs/dom/file_system';
import GDriveFileSystem from 'axiom/fs/gdrive/file_system';
import FileSystemManager from 'axiom/fs/base/file_system_manager';
import ExecuteContext from 'axiom/fs/base/execute_context';
import StdioSource from 'axiom/fs/stdio_source';
import Path from 'axiom/fs/path';

import scriptMain from 'shell/exe/script';
import TerminalView from 'shell/terminal';
import washExecutables from 'wash/exe_modules';

var welcomeMessage = [
  'Welcome to the Axiom web_shell sample.',
  '',
  'This is a cross-browser interactive shell written in JavaScript which ',
  'can be extended with new commands at runtime.',
  '',
  'To get started, try:',
  ' * \x1b[1mmount\x1b[m to see a list of mounted filesystems.',
  ' * \x1b[1mls\x1b[m to see the contents of the current directory.',
  ' * \x1b[1mls jsfs:/exe\x1b[m to list the executables.',
  ' * \x1b[1mcd <path>\x1b[m to change your working directory.',
  ' * \x1b[1menv-get\x1b[m, \x1b[1menv-set\x1b[m, and \x1b[1menv-del\x1b[m ' +
      'to view and modify environment variables.',
  ' * \x1b[1mscript <url>\x1b[m to load third party scripts (but be careful).',
  '',
  'For more information, please visit: \x1b[1mhttp://goo.gl/DmDqct\x1b[m',
  ''
].join('\r\n');

export var main = function() {
  var fsm = new FileSystemManager();
  var jsfs = new JsFileSystem(fsm, 'jsfs');
  fsm.mount(jsfs);

  // Add executables to new filesystem
  jsfs.rootDirectory.mkdir('exe')
    .then(function( /** JsDirectory */ jsdir) {
      jsdir.install({
        'script': scriptMain
      });
      jsdir.install(washExecutables);
    })
    .then(function() {
      return DomFileSystem.mount(fsm, 'html5', 'permanent')
        .then(function() {
          return DomFileSystem.mount(fsm, 'tmp', 'temporary');
        })
        .catch(function(e) {
          console.log("Error mounting DomFileSystem", e);
        });
    })
    .then(function() {
      return launchHterm(fsm);
    }).catch(function(e) {
      console.log('Error lauching app:', e);
    });
};

export default main;

var launchHterm = function(fsm) {
  var stdioSource = new StdioSource();
  return fsm.createExecuteContext(
    new Path('jsfs:exe/wash'), stdioSource.stdio, {})
    .then(function (/** ExecuteContext */cx) {
      var tv = new TerminalView();

      tv.println(welcomeMessage);

      cx.setEnvs({
        '@PATH': ['jsfs:/exe'],
        '$TERM': 'xterm-256color',
        '$HOME': 'html5:/',
        '$HISTFILE': 'html5:/.wash_history'
      });
      tv.execute(stdioSource, cx);

      var delay = function(ms, command) {return new Promise(function(rs, rj) {setTimeout(
          function() {rs() }, ms)}).then(function() {tv.stdioSource.stdin.write(command);
          tv.stdioSource.stdin.write('\r');})};

      delay(100,
          'mkstream --src ws://localhost:8000 --type extension --src lfbhahfblgmngkkgbgbccedhhnkkhknb jsfs:/bar3.str').then(function () {return delay(100,
          'mount.stream jsfs:/bar3.str')}).then(function () {return delay(100,
          'mount')}).then(function () {return delay(100,
          // 'ls streamfs:/')}).then(function () {return delay(100,
          '')});

      // delay(100,
      //     'mkstream --src ws://localhost:8000 --type extension jsfs:/bar3.str').then(function () {return delay(100,
      //     'mount.stream jsfs:/bar3.str')}).then(function () {return delay(100,
      //     'mount')}).then(function () {return delay(100,
      //     // 'ls streamfs:/')}).then(function () {return delay(100,
      //     '')});

      // delay(100,
      //     'mkstream --src ws://localhost:8000 --type websocket jsfs:/bar3.str').then(function () {return delay(100,
      //     'mount.stream jsfs:/bar3.str')}).then(function () {return delay(100,
      //     'mount')}).then(function () {return delay(100,
      //     // 'ls streamfs:/')}).then(function () {return delay(100,
      //     '')});

      // }.bind(this, tv), 100)

      // setTimeout(function(tv) {
        // tv.stdioSource.stdin.write('mount.stream jsfs:/bar3.str');
        // tv.stdioSource.stdin.write('\r');
      // }.bind(this, tv), 200)
// mount.stream jsfs:/bar3.str
      // debugger;

      return Promise.resolve(null);
  });
};
<|endoftext|>


<commit_before>/**
 * A method for submitting an HTML form using AJAX, as opposed to the
 * standard page-load way.
 *
 * This method attempts to mimic the functionality of the original form
 * as best as possible (duplicating the method, action, and exact contents
 * of the form).
 *
 * There are three different resulting operations that can occur, after
 * your form has been submitted.
 *
 * 1. The form is submitted and a callback is fired, letting you know
 *    when it's done:
 *    $("form").ajaxSubmit(function(){
 *      alert("all done!");
 *    });
 *
 * 2. The form is submitted and the resulting HTML contents are injected
 *    into the page, at your specified location.
 *    $("form").ajaxSubmit("#destination");
 *
 * 3. The form is submitted and the results returned from the server are
 *    automatically executed (useful for having the server return more
 *    Javascript commands to execute).
 *    $("form").ajaxSubmit();
 *
 * Additionally, an optional pre-submit callback can be provided. If it,
 * when called with the contents of the form, returns false, the form will
 * not be submitted.
 *
 * Finally, both the URL and method of the form submission can be
 * overidden using the 'url' and 'mth' arguments.
 *
 * @param target   arg for the target id element to render
 * @param post_cb  callback after any results are returned
 * @param pre_cb   callback function before submission
 * @param url      form action override
 * @param mth      form method override
 * @return         "this" object
 * @see            ajaxForm(), serialize(), load(), $.ajax()
 * @author         Mark Constable (markc@renta.net)
 * @author         G. vd Hoven, Mike Alsup, Sam Collett, John Resig
 */
$.fn.ajaxSubmit = function(target, post_cb, pre_cb, url, mth) {
	if ( !this.vars ) this.serialize();

	if (pre_cb && pre_cb.constructor == Function)
		if (pre_cb(this.vars) === false) return;

	var f = this.get(0);
	var url = url || f.action || '';
	var mth = mth || f.method || 'POST';

	if (target && target.constructor == Function) {
		$.ajax(mth, url, $.param(this.vars), target);
	} else if (target && target.constructor == String) {
		$(target).load(url, this.vars, post_cb);
	} else {
		this.vars.push({name: 'evaljs', value: 1});
		$.ajax(mth, url, $.param(this.vars), function(r) {
			eval(r.responseText);
		});
	}

	return this;
};

/**
 * This function can be used to turn any HTML form into a form
 * that submits using AJAX only.
 *
 * The purpose of using this method, instead of the ajaxSubmit()
 * and submit() methods, is to make absolutely sure that the
 * coordinates of <input type="image"/> elements are transmitted
 * correctly OR figuring out exactly which <input type="submit"/>
 * element was clicked to submit the form.
 *
 * If neither of the above points are important to you, then you'll
 * probably just want to stick with the simpler ajaxSubmit() function.
 *
 * Usage examples, similar to ajaxSubmit():
 *
 * 1. Just eval the results returned from the backend.
 *    $('#form-id').ajaxForm();
 *
 * 2. Render backend results directly to target ID (expects (x)HTML).
 *    $('#form-id').ajaxForm('#target-id');
 *
 * 3. Submit to backend URL (form action) then call this function.
 *    $('#form-id').ajaxForm(post_callback);
 *
 * 4. Load target ID with backend results then call a function.
 *    $('#form-id').ajaxForm('#target-id', post_callback);
 *
 * 5. Call a browser function (for validation) and then (optionally)
 *    load server results to target ID.
 *    $('#form-id').ajaxForm('#target-id', null, pre_callback);
 *
 * 6. Call validation function first then load server results to
 *    target ID and then also call a browser function.
 *    $('#form-id').ajaxForm('#target-id', post_callback, pre_callback);
 *
 * @param target   arg for the target id element to render
 * @param post_cb  callback after any results are returned
 * @param pre_cb   callback function before submission
 * @return         the jQuery Object
 * @see            serialize(), ajaxSubmit()
 * @author         Mark Constable (markc@renta.net)
 * @author         G. vd Hoven, Mike Alsup, Sam Collett, John Resig
 */
$.fn.ajaxForm = function(target, post_cb, pre_cb) {
	return this.each(function(){
		$('input[@type="submit"],input[@type="image"]', this).click(function(ev){
			this.form.clicked = this;
			if (ev.offsetX != undefined) {
				this.form.clicked_x = ev.offsetX;
				this.form.clicked_y = ev.offsetY;
			} else {
				this.form.clicked_x = ev.pageX - this.offsetLeft;
				this.form.clicked_y = ev.pageY - this.offsetTop;
			}
		});
	}).submit(function(e){
		e.preventDefault();
		$(this).ajaxSubmit(target, post_cb, pre_cb);
		return false;
	});
};

/**
 * A simple wrapper function that sits around the .serialize()
 * method, allowing you to easily extract the data stored within
 * a form.
 *
 * Usage examples:
 *
 * 1. Serialize the contents of a form to a & and = delmited string:
 *    $.param( $("form").formdata() );
 *
 * @return         An array of name/value pairs representing the form
 * @see            serialize()
 # @author         John Resig
 */
$.fn.formdata = function(){
	this.serialize();
	return this.vars;
};

/**
 * This function gathers form element variables into an array that
 * is embedded into the current "this" variable as "this.vars". It
 * is normally used in conjunction with formdata() or ajaxSubmit() but can
 * be used standalone as long as you don't need the x and y coordinates
 * associated with an <input type="image"/> element..
 *
 * Standalone usage examples:
 *
 * 1. Gather form vars and return array to LHS variable.
 *    var myform = $('#form-id').serialize();
 *
 * 2. Provide a serialized URL-ready string (after 1. above).
 *    var mystring = $.param(myform.vars);
 *
 * 3. Gather form vars and send to RHS plugin via "this.vars".
 *    $('#form-id').serialize().some_other_plugin();
 *
 * @return         the jQuery Object
 * @see            ajaxForm(), ajaxSubmit()
 * @author         Mark Constable (markc@renta.net)
 * @author         G. vd Hoven, Mike Alsup, Sam Collett, John Resig
 */
$.fn.serialize = function() {
	var a = [];
	var ok = {INPUT:true, TEXTAREA:true, OPTION:true};

	$('*', this).each(function() {
		if (this.disabled || this.type == 'reset' ||
			(this.type == 'checkbox' && !this.checked) ||
			(this.type == 'radio' && !this.checked)) return;

		if (this.type == 'submit' || this.type == 'image') {
			if (this.form.clicked != this) return;

			if (this.type == 'image') {
				if (this.form.clicked_x) {
					a.push({name: this.name+'_x', value: this.form.clicked_x});
					a.push({name: this.name+'_y', value: this.form.clicked_y});
					return;
				}
			}
		}

		if (!ok[this.nodeName.toUpperCase()])
			return;

		var par = this.parentNode;
		var p = par.nodeName.toUpperCase();
		if ((p == 'SELECT' || p == 'OPTGROUP') && !this.selected) return;

		var n = this.name || par.name;
		if (!n && p == 'OPTGROUP' && (par = par.parentNode))
			n = par.name;

		if (n == undefined) return;

		a.push({name: n, value: this.value});
	});

	this.vars = a;

	return this;
};
<commit_msg>fix for $.fn.serialize bug (see mailinglist)<commit_after>/**
 * A method for submitting an HTML form using AJAX, as opposed to the
 * standard page-load way.
 *
 * This method attempts to mimic the functionality of the original form
 * as best as possible (duplicating the method, action, and exact contents
 * of the form).
 *
 * There are three different resulting operations that can occur, after
 * your form has been submitted.
 *
 * 1. The form is submitted and a callback is fired, letting you know
 *    when it's done:
 *    $("form").ajaxSubmit(function(){
 *      alert("all done!");
 *    });
 *
 * 2. The form is submitted and the resulting HTML contents are injected
 *    into the page, at your specified location.
 *    $("form").ajaxSubmit("#destination");
 *
 * 3. The form is submitted and the results returned from the server are
 *    automatically executed (useful for having the server return more
 *    Javascript commands to execute).
 *    $("form").ajaxSubmit();
 *
 * Additionally, an optional pre-submit callback can be provided. If it,
 * when called with the contents of the form, returns false, the form will
 * not be submitted.
 *
 * Finally, both the URL and method of the form submission can be
 * overidden using the 'url' and 'mth' arguments.
 *
 * @param target   arg for the target id element to render
 * @param post_cb  callback after any results are returned
 * @param pre_cb   callback function before submission
 * @param url      form action override
 * @param mth      form method override
 * @return         "this" object
 * @see            ajaxForm(), serialize(), load(), $.ajax()
 * @author         Mark Constable (markc@renta.net)
 * @author         G. vd Hoven, Mike Alsup, Sam Collett, John Resig
 */
$.fn.ajaxSubmit = function(target, post_cb, pre_cb, url, mth) {
	if ( !this.vars ) this.serialize();

	if (pre_cb && pre_cb.constructor == Function)
		if (pre_cb(this.vars) === false) return;

	var f = this.get(0);
	var url = url || f.action || '';
	var mth = mth || f.method || 'POST';

	if (target && target.constructor == Function) {
		$.ajax(mth, url, $.param(this.vars), target);
	} else if (target && target.constructor == String) {
		$(target).load(url, this.vars, post_cb);
	} else {
		this.vars.push({name: 'evaljs', value: 1});
		$.ajax(mth, url, $.param(this.vars), function(r) {
			eval(r.responseText);
		});
	}

	return this;
};

/**
 * This function can be used to turn any HTML form into a form
 * that submits using AJAX only.
 *
 * The purpose of using this method, instead of the ajaxSubmit()
 * and submit() methods, is to make absolutely sure that the
 * coordinates of <input type="image"/> elements are transmitted
 * correctly OR figuring out exactly which <input type="submit"/>
 * element was clicked to submit the form.
 *
 * If neither of the above points are important to you, then you'll
 * probably just want to stick with the simpler ajaxSubmit() function.
 *
 * Usage examples, similar to ajaxSubmit():
 *
 * 1. Just eval the results returned from the backend.
 *    $('#form-id').ajaxForm();
 *
 * 2. Render backend results directly to target ID (expects (x)HTML).
 *    $('#form-id').ajaxForm('#target-id');
 *
 * 3. Submit to backend URL (form action) then call this function.
 *    $('#form-id').ajaxForm(post_callback);
 *
 * 4. Load target ID with backend results then call a function.
 *    $('#form-id').ajaxForm('#target-id', post_callback);
 *
 * 5. Call a browser function (for validation) and then (optionally)
 *    load server results to target ID.
 *    $('#form-id').ajaxForm('#target-id', null, pre_callback);
 *
 * 6. Call validation function first then load server results to
 *    target ID and then also call a browser function.
 *    $('#form-id').ajaxForm('#target-id', post_callback, pre_callback);
 *
 * @param target   arg for the target id element to render
 * @param post_cb  callback after any results are returned
 * @param pre_cb   callback function before submission
 * @return         the jQuery Object
 * @see            serialize(), ajaxSubmit()
 * @author         Mark Constable (markc@renta.net)
 * @author         G. vd Hoven, Mike Alsup, Sam Collett, John Resig
 */
$.fn.ajaxForm = function(target, post_cb, pre_cb) {
	return this.each(function(){
		$('input[@type="submit"],input[@type="image"]', this).click(function(ev){
			this.form.clicked = this;
			if (ev.offsetX != undefined) {
				this.form.clicked_x = ev.offsetX;
				this.form.clicked_y = ev.offsetY;
			} else {
				this.form.clicked_x = ev.pageX - this.offsetLeft;
				this.form.clicked_y = ev.pageY - this.offsetTop;
			}
		});
	}).submit(function(e){
		e.preventDefault();
		$(this).ajaxSubmit(target, post_cb, pre_cb);
		return false;
	});
};

/**
 * A simple wrapper function that sits around the .serialize()
 * method, allowing you to easily extract the data stored within
 * a form.
 *
 * Usage examples:
 *
 * 1. Serialize the contents of a form to a & and = delmited string:
 *    $.param( $("form").formdata() );
 *
 * @return         An array of name/value pairs representing the form
 * @see            serialize()
 # @author         John Resig
 */
$.fn.formdata = function(){
	this.serialize();
	return this.vars;
};

/**
 * This function gathers form element variables into an array that
 * is embedded into the current "this" variable as "this.vars". It
 * is normally used in conjunction with formdata() or ajaxSubmit() but can
 * be used standalone as long as you don't need the x and y coordinates
 * associated with an <input type="image"/> element..
 *
 * Standalone usage examples:
 *
 * 1. Gather form vars and return array to LHS variable.
 *    var myform = $('#form-id').serialize();
 *
 * 2. Provide a serialized URL-ready string (after 1. above).
 *    var mystring = $.param(myform.vars);
 *
 * 3. Gather form vars and send to RHS plugin via "this.vars".
 *    $('#form-id').serialize().some_other_plugin();
 *
 * @return         the jQuery Object
 * @see            ajaxForm(), ajaxSubmit()
 * @author         Mark Constable (markc@renta.net)
 * @author         G. vd Hoven, Mike Alsup, Sam Collett, John Resig
 */
$.fn.serialize = function() {
	var a = [];
	var ok = {INPUT:true, TEXTAREA:true, OPTION:true};

	$('*', this).each(function() {
		if (this.disabled || this.type == 'reset' ||
			(this.type == 'checkbox' && !this.checked) ||
			(this.type == 'radio' && !this.checked)) return;

		if (this.type == 'submit' || this.type == 'image') {
			if (this.form.clicked != this) return;

			if (this.type == 'image') {
				if (this.form.clicked_x) {
					a.push({name: this.name+'_x', value: this.form.clicked_x});
					a.push({name: this.name+'_y', value: this.form.clicked_y});
					return;
				}
			}
		}

		if (!ok[this.nodeName.toUpperCase()])
			return;

		var par = this.parentNode;
		var p = par.nodeName.toUpperCase();
		if ((p == 'SELECT' || p == 'OPTGROUP') && !this.selected) return;

		var n = this.name;
		if (!n && p == 'OPTGROUP' && (par = par.parentNode))
			n = par.name;

		if (n == undefined) return;

		a.push({name: n, value: this.value});
	});

	this.vars = a;

	return this;
};
<|endoftext|>


<commit_before>define(module, function(exports, require, make) {

  var path = require('path');
  var mime = require('mime');
  var qp = require('qp-utility');
  var fss = require('qp-library/fss');

  make({

    ns: 'qp-library/fso',

    self: {

      has_filename: function(filepath) {
        var parts = qp.trim(filepath, path.sep).split(path.sep);
        return parts.pop().indexOf('.') !== -1;
      },

      filename: function(filepath) {
        var parts = qp.trim(filepath, path.sep).split(path.sep);
        var part = parts.pop();
        return part.indexOf('.') === -1 ? '' : part;
      },

      pathname: function(filepath) {
        var parts = qp.trim(filepath, path.sep).split(path.sep);
        if (parts.slice(-1)[0].indexOf('.') !== -1) {
          parts.pop();
        }
        return path.sep + parts.join(path.sep) + path.sep;
      },

      load: function() {
        return this.create({ path: path.join.apply(null, qp.compact(arguments)) });
      },

      split: function(filepath) {
        return qp.trim(filepath, path.sep).split(path.sep);
      },

      join: function() {
        return path.join.apply(null, qp.compact(arguments));
      }

    },

    exists: false,
    is_file: false,
    is_directory: false,
    ino: 0,
    atime: 0,
    mtime: 0,
    ctime: 0,
    size: 0,
    mime: '',

    fullname: '', // eg: /one/two/three.four || /one/two/three
    filename: '', // eg: /one/two/three.four

    path: '',     // eg: /one/two
    file: '',     // eg: three.four
    name: '',     // eg: three
    ext: '',      // eg: four

    init: function(config) {
      if (qp.is(config.fso, 'fso')) {
        this.fullname = config.fso.fullname;
      } else if (qp.is(config.url, 'url')) {
        var fullname = path.join(config.base, config.url.fullname);
        if (qp.starts(fullname, config.base)) {
          this.fullname = fullname;
        }
      } else if (qp.is(config.path, 'string')) {
        this.fullname = path.join(config.base || '', config.path);
      } else if (qp.is(config.path, 'array')) {
        this.fullname = path.join.apply(null, config.path);
      }

      this.exists = fss.exists(this.fullname);
      if (this.exists) {
        var stat = fss.stat(this.fullname);
        this.size = stat.size;
        this.is_file = stat.isFile();
        this.is_directory = stat.isDirectory();
        this.ino = stat.ino;
        this.atime = stat.atime;
        this.mtime = stat.mtime;
        this.ctime = stat.ctime;
      }
      if (!this.exists || this.is_file) {
        this.path = this.self.pathname(this.fullname);
        this.file = this.self.filename(this.fullname);
        if (this.file.length) {
          this.is_file = true;
          var parts = qp.split(this.file, '.');
          this.ext = parts.pop();
          this.name = parts.join('.');
        } else {
          this.is_directory = true;
        }
      }
      if (this.is_file) this.filename = this.fullname;
      this.mime = mime.lookup(this.fullname);
    },

    set_ext: function(ext) {
      if (this.is_file) {
        return this.self.create({ path: this.path + this.name + '.' + qp.ltrim(ext, '.') });
      } else if (this.is_directory) {
        return this.self.create({ path: qp.rtrim(this.path, path.sep) + '.' + qp.ltrim(ext, '.') });
      }
    },

    set_file: function(name, ext) {
      if (this.is_file) {
        return this.self.create({ path: this.path + path.sep + name + '.' + qp.ltrim(ext, '.') });
      } else if (this.is_directory) {
        return this.self.create({ path: this.path + name + '.' + qp.ltrim(ext, '.') });
      }
    }

  });

});
<commit_msg>fso - add filepath property<commit_after>define(module, function(exports, require, make) {

  var path = require('path');
  var mime = require('mime');
  var qp = require('qp-utility');
  var fss = require('qp-library/fss');

  make({

    ns: 'qp-library/fso',

    self: {

      has_filename: function(filepath) {
        var parts = qp.trim(filepath, path.sep).split(path.sep);
        return parts.pop().indexOf('.') !== -1;
      },

      filename: function(filepath) {
        var parts = qp.trim(filepath, path.sep).split(path.sep);
        var part = parts.pop();
        return part.indexOf('.') === -1 ? '' : part;
      },

      pathname: function(filepath) {
        var parts = qp.trim(filepath, path.sep).split(path.sep);
        if (parts.slice(-1)[0].indexOf('.') !== -1) {
          parts.pop();
        }
        return path.sep + parts.join(path.sep) + path.sep;
      },

      load: function() {
        return this.create({ path: path.join.apply(null, qp.compact(arguments)) });
      },

      split: function(filepath) {
        return qp.trim(filepath, path.sep).split(path.sep);
      },

      join: function() {
        return path.join.apply(null, qp.compact(arguments));
      }

    },

    exists: false,
    is_file: false,
    is_directory: false,
    ino: 0,
    atime: 0,
    mtime: 0,
    ctime: 0,
    size: 0,
    mime: '',

    fullname: '', // eg: /one/two/three.four || /one/two/three
    filename: '', // eg: /one/two/three.four
    filepath: '', // eg: /one/two/three

    path: '',     // eg: /one/two
    file: '',     // eg: three.four
    name: '',     // eg: three
    ext: '',      // eg: four

    init: function(config) {
      if (qp.is(config.fso, 'fso')) {
        this.fullname = config.fso.fullname;
      } else if (qp.is(config.url, 'url')) {
        var fullname = path.join(config.base, config.url.fullname);
        if (qp.starts(fullname, config.base)) {
          this.fullname = fullname;
        }
      } else if (qp.is(config.path, 'string')) {
        this.fullname = path.join(config.base || '', config.path);
      } else if (qp.is(config.path, 'array')) {
        this.fullname = path.join.apply(null, config.path);
      }

      this.exists = fss.exists(this.fullname);
      if (this.exists) {
        var stat = fss.stat(this.fullname);
        this.size = stat.size;
        this.is_file = stat.isFile();
        this.is_directory = stat.isDirectory();
        this.ino = stat.ino;
        this.atime = stat.atime;
        this.mtime = stat.mtime;
        this.ctime = stat.ctime;
      }
      if (!this.exists || this.is_file) {
        this.path = this.self.pathname(this.fullname);
        this.file = this.self.filename(this.fullname);
        if (this.file.length) {
          this.is_file = true;
          var parts = qp.split(this.file, '.');
          this.ext = parts.pop();
          this.name = parts.join('.');
        } else {
          this.is_directory = true;
        }
      }
      if (this.is_file) {
        this.filename = this.fullname;
        this.filepath = qp.rtrim(this.fullname, '.' + this.ext);
      }
      this.mime = mime.lookup(this.fullname);
    },

    set_ext: function(ext) {
      if (this.is_file) {
        return this.self.create({ path: this.path + this.name + '.' + qp.ltrim(ext, '.') });
      } else if (this.is_directory) {
        return this.self.create({ path: qp.rtrim(this.path, path.sep) + '.' + qp.ltrim(ext, '.') });
      }
    },

    set_file: function(name, ext) {
      if (this.is_file) {
        return this.self.create({ path: this.path + path.sep + name + '.' + qp.ltrim(ext, '.') });
      } else if (this.is_directory) {
        return this.self.create({ path: this.path + name + '.' + qp.ltrim(ext, '.') });
      }
    }

  });

});
<|endoftext|>