<commit_before>require.paths.unshift(__dirname);
require.paths.unshift(require("path").join(__dirname, "../vendor/node-applescript/lib"));
var fs = require("fs");
var sys = require("sys");
var Url = require("url");
var xml2js = require('xml2js');
var connect = require("connect");
var helpers = require("helpers");
var handlers = require("handlers");
var nClass = require("nTunes-class");
var Buffer = require("buffer").Buffer;
var nCommand = require("nTunes-command");
var querystring = require("querystring");
var applescript = require("applescript");
var nSpecifier = require("nTunes-specifier");
require.paths.shift();
require.paths.shift();

// Before doing anything, the "iTunes.sdef" file must be read and
// parsed. The SDEF file dynamically builds the 'nTunes' API once
// the file has been parsed into memory.
var parser = new xml2js.Parser();

parser.on('end', function(result) {
  // With the parsed XML result, we need to format the object into
  // nClass and nCommand instances.
  var iTunesSuite = result.suite[1];
  nCommand.processCommands(iTunesSuite.command);
  nClass.processClasses(iTunesSuite['class']);
  nSpecifier.setNClass(nClass);

  // Add the custom nTunes class handlers from "handlers.js"
  handlers(nClass);

  parser = null;
});
fs.readFile(__dirname + '/iTunes.sdef', function(err, data) {
  parser.parseString(data);
});

// The 'nTunes' constructor is a full subclass of 'connect', but allows the
// ability to add aditional layers in front of the nTunes layers, in case you
// would like to serve other content on urls not in use by nTunes (be careful!)
function nTunes(layers) {
  var self = this;

  // Concat nTunes layers to the end of 'layers' here
  layers = layers.concat([
    function(req, res, next) {
      self.ensureSdefIsProcessed(req, res, next);
    },
    //function(req, res, next) {
      //self.handleNTunesAliases(req, res, next);
    //},
    function(req, res, next) {
      self.handleNTunesRequest(req, res, next);
    }
  ]);

  // Call the 'connect' Server constructor, to complete the subclassing.
  connect.Server.call(self, layers);
}

// Public API can use 'nTunes.createServer' for familiarity with the connect
// and http modules, or simply use the 'nTunes' module as a constructor.
nTunes.createServer = function() {
  return new nTunes(Array.prototype.slice.call(arguments));
}

// Don't use `sys.inherits`, since it might be removed. Inherit from the
// prototype of 'connect.Server'.
nTunes.prototype = Object.create(connect.Server.prototype, {
  constructor: {
    value: nTunes,
    enumerable: false
  }
});

nTunes.prototype.doNTunesCommand = function(command, params, res) {
  var ncommand = nCommand.getCommand(command);
  var asStr = command + ' ';
  var self = this;

  ncommand.parameters.forEach(function(parameter) {
    var userDidSupplyParam = parameter.name in params;
    if (!userDidSupplyParam && !parameter.optional) {
      // Return error, user did not supply required param
    }
    if (userDidSupplyParam) {
      if (parameter.name != "value") {
        asStr += parameter.name + " ";
      }
      if (parameter.type == "specifier") {
        var specifier = new nSpecifier(params[parameter.name]);
        asStr = specifier.vars + asStr + specifier.finalVar;
      } else if (parameter.type == "boolean") {
        asStr += String(params[parameter.name]).toLowerCase() == "true" ? "yes" : "no";
      }
      asStr += " ";
    }
  });
  self.doAppleScriptThenResponse(asStr, res);
}

// The first handler ensures that the .sdef XML file has been processed,
// and if it hasn't, it waits for it to finish before calling "next()".
nTunes.prototype.ensureSdefIsProcessed = function(req, res, next) {
  if (parser) {
    parser.on('end', function(result) {
      // Wait a tiny amount of time to ensure that the parsing handler
      // is the first 'end' handler for the parser.
      setTimeout(function() {
        next();
      }, 10);
    });
  } else {
    next();
  }
}

// The primary handler for the nTunes API.
nTunes.prototype.handleNTunesRequest = function(req, res, next) {
  var self = this,
    isValidApiRequest = false;
  req.parsedUrl = res.parsedUrl = Url.parse(req.url, true);

  req.parsedUrl.decodedPath = decodeURIComponent(req.parsedUrl.pathname);

  // Each "/" in the request URI represents selecting a resource, narrowing
  // down the previous selection, or possibly calling a command.
  req.parsedUrl.request = req.parsedUrl.decodedPath.split("/").slice(1);

  // First check for the case of a "command", since it's only valid with a
  // single token in the URI, and a POST method request.
  if (req.method == "POST" && req.parsedUrl.request.length == 1 && nCommand.REGEXP.test(req.parsedUrl.request[0])) {
    isValidApiRequest = true;

    var body = "";
    req.setEncoding("utf8");
    req.on("data", function(chunk) {
      body += chunk;
    });
    req.on("end", function() {
      req.body = querystring.parse(decodeURIComponent(body));
      self.doNTunesCommand(req.parsedUrl.request[0], req.body, res);
    });

  } else {
    // If it's not a command, then maybe it's a class/property lookup.
    // Attempt to resolve the url into a 'specifier'.
    var resolvedSpecifier;
    try {
      resolvedSpecifier = new nSpecifier(req.parsedUrl.decodedPath);
    } catch (e) {
      // If ' new nSpecifier' throws an error, then the user requested
      // an invalid specifier. nTunes should respond with a 400 status
      // code and an Error object.
      return self.sendNTunesResponse(res, 400, null, {
        error: e
      });
    }

    isValidApiRequest = true;

    // If this request is for a custom handler, then invoke the
    // custom callback.
    if (resolvedSpecifier.handler) {
      resolvedSpecifier.handler(req, res, next);

    } else {
      var as = resolvedSpecifier.vars;

      if (req.method == "POST") {
        var body = "";
        req.setEncoding("utf8");
        req.on("data", function(chunk) {
          body += chunk;
        });
        req.on("end", function() {
          req.body = querystring.parse(decodeURIComponent(body));
          as += "set " + resolvedSpecifier.finalVar + " to " + req.body.value + "\n";
          as += "get " + resolvedSpecifier.finalVar;
          self.doAppleScriptThenResponse(as, res);
        });

      } else if (req.method == "GET") {
        as += 'get ' + resolvedSpecifier.finalVar;
        self.doAppleScriptThenResponse(as, res);
      }
    }
  }

  if (!isValidApiRequest) {
    next();
  }
}

// Performs the passed AppleScript code against the "iTunes" application,
// then sends the response from AppleScript to the HTTP client, ending
// the request.
nTunes.prototype.doAppleScriptThenResponse = function(as, res) {
  var self= this;
  as = 'tell application "iTunes"\n' + as + "\nend tell";
  applescript.execString(as, function(err, stdout, stderr) {
    if (err) {
      var e = new Error(stderr);
      e.appleScript = as;
      e.exitCode = err;
      self.sendNTunesResponse(res, 500, null, {
        error: e
      });
    } else {
      self.sendNTunesResponse(res, 200, null, stdout);
    }
  });
}

// Called whenever the nTunes API is ready to send a response to the client.
// It's a single shared function so that we can do last minute things like
// convert the data to a different transfer format if the client requested.
//   i.e. checks for ?format=xml to convert to XML
nTunes.prototype.sendNTunesResponse = function(res, code, headers, body) {
  var format = res.parsedUrl.query && res.parsedUrl.query.format ? res.parsedUrl.query.format : 'json';

  if (res.parsedUrl.query && res.parsedUrl.query.unique && Array.isArray(body)) {
    body = helpers.arrayUniq(body);
  }

  headers = headers || {};
  headers['Content-Type'] = FORMAT_TO_CONTENT_TYPE[format];

  res.writeHead(code, headers);
  res.end(JSON.stringify(body));
}

var FORMAT_TO_CONTENT_TYPE = {
  'json' : 'application/json',
  'xml': 'text/xml'
}

// Export the constructor itself since we're badass like that ☺
module.exports = nTunes;
<commit_msg>Quick implementation of passing through Buffer instances. Artwork is now usable!<commit_after>require.paths.unshift(__dirname);
require.paths.unshift(require("path").join(__dirname, "../vendor/node-applescript/lib"));
var fs = require("fs");
var sys = require("sys");
var Url = require("url");
var xml2js = require('xml2js');
var connect = require("connect");
var helpers = require("helpers");
var handlers = require("handlers");
var nClass = require("nTunes-class");
var Buffer = require("buffer").Buffer;
var nCommand = require("nTunes-command");
var querystring = require("querystring");
var applescript = require("applescript");
var nSpecifier = require("nTunes-specifier");
require.paths.shift();
require.paths.shift();

// Before doing anything, the "iTunes.sdef" file must be read and
// parsed. The SDEF file dynamically builds the 'nTunes' API once
// the file has been parsed into memory.
var parser = new xml2js.Parser();

parser.on('end', function(result) {
  // With the parsed XML result, we need to format the object into
  // nClass and nCommand instances.
  var iTunesSuite = result.suite[1];
  nCommand.processCommands(iTunesSuite.command);
  nClass.processClasses(iTunesSuite['class']);
  nSpecifier.setNClass(nClass);

  // Add the custom nTunes class handlers from "handlers.js"
  handlers(nClass);

  parser = null;
});
fs.readFile(__dirname + '/iTunes.sdef', function(err, data) {
  parser.parseString(data);
});

// The 'nTunes' constructor is a full subclass of 'connect', but allows the
// ability to add aditional layers in front of the nTunes layers, in case you
// would like to serve other content on urls not in use by nTunes (be careful!)
function nTunes(layers) {
  var self = this;

  // Concat nTunes layers to the end of 'layers' here
  layers = layers.concat([
    function(req, res, next) {
      self.ensureSdefIsProcessed(req, res, next);
    },
    //function(req, res, next) {
      //self.handleNTunesAliases(req, res, next);
    //},
    function(req, res, next) {
      self.handleNTunesRequest(req, res, next);
    }
  ]);

  // Call the 'connect' Server constructor, to complete the subclassing.
  connect.Server.call(self, layers);
}

// Public API can use 'nTunes.createServer' for familiarity with the connect
// and http modules, or simply use the 'nTunes' module as a constructor.
nTunes.createServer = function() {
  return new nTunes(Array.prototype.slice.call(arguments));
}

// Don't use `sys.inherits`, since it might be removed. Inherit from the
// prototype of 'connect.Server'.
nTunes.prototype = Object.create(connect.Server.prototype, {
  constructor: {
    value: nTunes,
    enumerable: false
  }
});

nTunes.prototype.doNTunesCommand = function(command, params, res) {
  var ncommand = nCommand.getCommand(command);
  var asStr = command + ' ';
  var self = this;

  ncommand.parameters.forEach(function(parameter) {
    var userDidSupplyParam = parameter.name in params;
    if (!userDidSupplyParam && !parameter.optional) {
      // Return error, user did not supply required param
    }
    if (userDidSupplyParam) {
      if (parameter.name != "value") {
        asStr += parameter.name + " ";
      }
      if (parameter.type == "specifier") {
        var specifier = new nSpecifier(params[parameter.name]);
        asStr = specifier.vars + asStr + specifier.finalVar;
      } else if (parameter.type == "boolean") {
        asStr += String(params[parameter.name]).toLowerCase() == "true" ? "yes" : "no";
      }
      asStr += " ";
    }
  });
  self.doAppleScriptThenResponse(asStr, res);
}

// The first handler ensures that the .sdef XML file has been processed,
// and if it hasn't, it waits for it to finish before calling "next()".
nTunes.prototype.ensureSdefIsProcessed = function(req, res, next) {
  if (parser) {
    parser.on('end', function(result) {
      // Wait a tiny amount of time to ensure that the parsing handler
      // is the first 'end' handler for the parser.
      setTimeout(function() {
        next();
      }, 10);
    });
  } else {
    next();
  }
}

// The primary handler for the nTunes API.
nTunes.prototype.handleNTunesRequest = function(req, res, next) {
  var self = this,
    isValidApiRequest = false;
  req.parsedUrl = res.parsedUrl = Url.parse(req.url, true);

  req.parsedUrl.decodedPath = decodeURIComponent(req.parsedUrl.pathname);

  // Each "/" in the request URI represents selecting a resource, narrowing
  // down the previous selection, or possibly calling a command.
  req.parsedUrl.request = req.parsedUrl.decodedPath.split("/").slice(1);

  // First check for the case of a "command", since it's only valid with a
  // single token in the URI, and a POST method request.
  if (req.method == "POST" && req.parsedUrl.request.length == 1 && nCommand.REGEXP.test(req.parsedUrl.request[0])) {
    isValidApiRequest = true;

    var body = "";
    req.setEncoding("utf8");
    req.on("data", function(chunk) {
      body += chunk;
    });
    req.on("end", function() {
      req.body = querystring.parse(decodeURIComponent(body));
      self.doNTunesCommand(req.parsedUrl.request[0], req.body, res);
    });

  } else {
    // If it's not a command, then maybe it's a class/property lookup.
    // Attempt to resolve the url into a 'specifier'.
    var resolvedSpecifier;
    try {
      resolvedSpecifier = new nSpecifier(req.parsedUrl.decodedPath);
    } catch (e) {
      // If ' new nSpecifier' throws an error, then the user requested
      // an invalid specifier. nTunes should respond with a 400 status
      // code and an Error object.
      return self.sendNTunesResponse(res, 400, null, {
        error: e
      });
    }

    isValidApiRequest = true;

    // If this request is for a custom handler, then invoke the
    // custom callback.
    if (resolvedSpecifier.handler) {
      resolvedSpecifier.handler(req, res, next);

    } else {
      var as = resolvedSpecifier.vars;

      if (req.method == "POST") {
        var body = "";
        req.setEncoding("utf8");
        req.on("data", function(chunk) {
          body += chunk;
        });
        req.on("end", function() {
          req.body = querystring.parse(decodeURIComponent(body));
          as += "set " + resolvedSpecifier.finalVar + " to " + req.body.value + "\n";
          as += "get " + resolvedSpecifier.finalVar;
          self.doAppleScriptThenResponse(as, res);
        });

      } else if (req.method == "GET") {
        as += 'get ' + resolvedSpecifier.finalVar;
        self.doAppleScriptThenResponse(as, res);
      }
    }
  }

  if (!isValidApiRequest) {
    next();
  }
}

// Performs the passed AppleScript code against the "iTunes" application,
// then sends the response from AppleScript to the HTTP client, ending
// the request.
nTunes.prototype.doAppleScriptThenResponse = function(as, res) {
  var self= this;
  as = 'tell application "iTunes"\n' + as + "\nend tell";
  applescript.execString(as, function(err, stdout, stderr) {
    if (err) {
      var e = new Error(stderr);
      e.appleScript = as;
      e.exitCode = err;
      self.sendNTunesResponse(res, 500, null, {
        error: e
      });
    } else {
      self.sendNTunesResponse(res, 200, null, stdout);
    }
  });
}

// Called whenever the nTunes API is ready to send a response to the client.
// It's a single shared function so that we can do last minute things like
// convert the data to a different transfer format if the client requested.
//   i.e. checks for ?format=xml to convert to XML
nTunes.prototype.sendNTunesResponse = function(res, code, headers, body) {
  var format = res.parsedUrl.query && res.parsedUrl.query.format ? res.parsedUrl.query.format : 'json';

  if (body instanceof Buffer) {
    format = "buffer";
  } else if (res.parsedUrl.query && res.parsedUrl.query.unique && Array.isArray(body)) {
    body = helpers.arrayUniq(body);
  }

  headers = headers || {};
  headers['Content-Type'] = FORMAT_TO_CONTENT_TYPE[format];
  if (format == 'buffer') {
    headers['Content-Length'] = body.length;
  }

  res.writeHead(code, headers);
  // TODO: Implement body conversion to XML.
  res.end(format == 'buffer' ? body : JSON.stringify(body));
}

var FORMAT_TO_CONTENT_TYPE = {
  'buffer' : 'application/octet-stream',
  'json' : 'application/json',
  'xml': 'text/xml'
}

// Export the constructor itself since we're badass like that ☺
module.exports = nTunes;
<|endoftext|>


<commit_before>var app = require('http').createServer(function(request, response) {
  console.log('>>>>>>>>>>>>>>>>>>', request.headers.origin);
  var origin = (request.headers.origin || "*");
  var headers =   {
    "access-control-allow-origin": origin,
    "access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
    "access-control-allow-headers": "content-type, accept",
    "access-control-max-age": 10,
    "content-length": 0
  };

  response.end('CORS enabled.');
});
var port = process.env.OPENSHIFT_NODEJS_PORT || 3000;
var ip = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';

var io = require('socket.io').listen(app);
io.set('origins', '*:*');
app.listen(port, ip);

var request = require('request');
var xml2js = require('xml2js');
var parser = new xml2js.Parser();

console.log('app listening on ' + ip + ':' + port);

io.sockets.on('connection', function (socket) {
  console.log('on connection');
  socket.on('searchInput:changed', function (data) {
    var suggestions = {
      google: [],
      bing: []
    };
    var complete = {
      google: false,
      bing: false
    };

    var timeout = setTimeout(function() {
      complete.google = true;
      complete.bing = true;
      maybeEmit();
    }, 5000);

    function maybeEmit() {
      if (complete.google && complete.bing)  {
        clearTimeout(timeout);
        socket.emit('suggestions:received', suggestions);
      }
    }

    var getSuggestions = {
      google: function(search) {
        this.get('http://www.google.com/complete/search?output=toolbar&q=' + encodeURIComponent(search), 'google', function(data, next) {
          parser.parseString(data, function (err, result) {
            var suggestions = [];
            if (result.toplevel && result.toplevel.CompleteSuggestion) {
              suggestions = result.toplevel.CompleteSuggestion;
              for (var i = 0; i < suggestions.length; i++) {
                var suggestion = suggestions[i];
                if (suggestion && suggestion.suggestion &&
                  suggestion.suggestion[0] &&
                  suggestion.suggestion[0]['$'] && suggestion.suggestion[0]['$'].data) {

                  suggestions[i] = suggestion.suggestion[0]['$'].data;
                } else {
                  suggestions[i] = '';
                }
              }
            }
            next(suggestions);
          });
        });
      },
      bing: function(search) {
        this.get('http://api.bing.com/osjson.aspx?query=' + encodeURIComponent(search), 'bing', function(data, next) {
          var suggestions = [];
          data = JSON.parse(data);
          if (data[1]) {
            suggestions = data[1].slice(0, 10);
          }
          next(suggestions);
        });
      },
      getAll: function(search) {
        if (search) {
          this.google(search);
          this.bing(search);
        }
      },
      get: function(url, provider, alterData) {
        function done() {
          complete[provider] = true;
          maybeEmit();
        }

        request(url, function(err, res, body) {
          if (err) {
            done();
          }
          alterData(body, function(data) {
            suggestions[provider] = data;
            done();
          });
        });
      }
    };

    getSuggestions.getAll(data.search);

  });
});

<commit_msg>Still trying to fix this origins thing<commit_after>var app = require('http').createServer(function(request, response) {
  var allowedOrigins = [
    'localhost',
    'http://kent.doddsfamily.us'
  ];
  var origin = request.headers.origin;
  if (allowedOrigins.indexOf(origin) === -1) {
    console.log('>>>>>>>>>>>>>>>>> origin not allowed: ', origin);
    return;
  }
  var headers =   {
    "access-control-allow-origin": origin,
    "access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
    "access-control-allow-headers": "content-type, accept",
    "access-control-max-age": 10,
    "content-length": 0
  };

  response.end('CORS enabled.');
});
var port = process.env.OPENSHIFT_NODEJS_PORT || 3000;
var ip = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';

var io = require('socket.io').listen(app);
io.set('origins', '*:*');
app.listen(port, ip);

var request = require('request');
var xml2js = require('xml2js');
var parser = new xml2js.Parser();

console.log('app listening on ' + ip + ':' + port);

io.sockets.on('connection', function (socket) {
  console.log('on connection');
  socket.on('searchInput:changed', function (data) {
    var suggestions = {
      google: [],
      bing: []
    };
    var complete = {
      google: false,
      bing: false
    };

    var timeout = setTimeout(function() {
      complete.google = true;
      complete.bing = true;
      maybeEmit();
    }, 5000);

    function maybeEmit() {
      if (complete.google && complete.bing)  {
        clearTimeout(timeout);
        socket.emit('suggestions:received', suggestions);
      }
    }

    var getSuggestions = {
      google: function(search) {
        this.get('http://www.google.com/complete/search?output=toolbar&q=' + encodeURIComponent(search), 'google', function(data, next) {
          parser.parseString(data, function (err, result) {
            var suggestions = [];
            if (result.toplevel && result.toplevel.CompleteSuggestion) {
              suggestions = result.toplevel.CompleteSuggestion;
              for (var i = 0; i < suggestions.length; i++) {
                var suggestion = suggestions[i];
                if (suggestion && suggestion.suggestion &&
                  suggestion.suggestion[0] &&
                  suggestion.suggestion[0]['$'] && suggestion.suggestion[0]['$'].data) {

                  suggestions[i] = suggestion.suggestion[0]['$'].data;
                } else {
                  suggestions[i] = '';
                }
              }
            }
            next(suggestions);
          });
        });
      },
      bing: function(search) {
        this.get('http://api.bing.com/osjson.aspx?query=' + encodeURIComponent(search), 'bing', function(data, next) {
          var suggestions = [];
          data = JSON.parse(data);
          if (data[1]) {
            suggestions = data[1].slice(0, 10);
          }
          next(suggestions);
        });
      },
      getAll: function(search) {
        if (search) {
          this.google(search);
          this.bing(search);
        }
      },
      get: function(url, provider, alterData) {
        function done() {
          complete[provider] = true;
          maybeEmit();
        }

        request(url, function(err, res, body) {
          if (err) {
            done();
          }
          alterData(body, function(data) {
            suggestions[provider] = data;
            done();
          });
        });
      }
    };

    getSuggestions.getAll(data.search);

  });
});

<|endoftext|>


<commit_before>var
gulp = require('gulp'),
coffee = require('gulp-coffee'),
concat = require('gulp-concat'),
htmlbuild = require('gulp-htmlbuild'),
sass = require('gulp-sass'),
gutil = require('gulp-util');

build = './build/'

gulp.task('build', function () {
    // Coffee
    gulp.src('src/scripts/**/*.coffee')
        .pipe(coffee({bare: true}))
        .on('error', gutil.log)
        .pipe(concat('app.js'))
        .pipe(gulp.dest(build));

    // Index
    gulp.src('src/index.html')
        .pipe(htmlbuild({
            js: function (files, callback) {
                gulp.src(files)
                    .pipe(concat('lib.js'))
                    .pipe(gulp.dest(build));
                callback(null, ['lib.js']);
            }
        }))
        .pipe(gulp.dest(build));

    // Views
    gulp.src('src/views/*.html')
        .pipe(gulp.dest(build + 'views/'));

    // SASS
    gulp.src('src/styles/**/*.scss')
        .pipe(sass())
        .on('error', gutil.log)
        .pipe(concat('the.css'))
        .pipe(gulp.dest(build));

    // Icons
    gulp.src('src/styles/icons/*')
        .pipe(gulp.dest(build + 'icons/'))
});

gulp.task('default', function () {
    gulp.run('build');

    gulp.watch(['src/**'], function () {
        gulp.run('build');
    });
});
<commit_msg>add 'gh'<commit_after>var
gulp = require('gulp'),
coffee = require('gulp-coffee'),
concat = require('gulp-concat'),
htmlbuild = require('gulp-htmlbuild'),
sass = require('gulp-sass'),
gutil = require('gulp-util');

build = './build/'

gulp.task('build', function () {
    // Coffee
    gulp.src('src/scripts/**/*.coffee')
        .pipe(coffee({bare: true}))
        .on('error', gutil.log)
        .pipe(concat('app.js'))
        .pipe(gulp.dest(build));

    // Index
    gulp.src('src/index.html')
        .pipe(htmlbuild({
            js: function (files, callback) {
                gulp.src(files)
                    .pipe(concat('lib.js'))
                    .pipe(gulp.dest(build));
                callback(null, ['lib.js']);
            }
        }))
        .pipe(gulp.dest(build));

    // Views
    gulp.src('src/views/*.html')
        .pipe(gulp.dest(build + 'views/'));

    // SASS
    gulp.src('src/styles/**/*.scss')
        .pipe(sass())
        .on('error', gutil.log)
        .pipe(concat('the.css'))
        .pipe(gulp.dest(build));

    // Icons
    gulp.src('src/styles/icons/*')
        .pipe(gulp.dest(build + 'icons/'))
});

gulp.task('default', function () {
    gulp.run('build');

    gulp.watch(['src/**'], function () {
        gulp.run('build');
    });
});

gulp.task('gh', function () {
    gulp.run('build');
    gulp.src('build/**/*')
        .pipe(gulp.dest('../sc2-gh-pages/'))
});
<|endoftext|>


<commit_before>var vmSha3Test = require('../../../../tests/vmtests/vmSha3Test.json'),
  async = require('async'),
  VM = require('../../../lib/vm'),
  Account = require('../../../lib/account.js'),
  assert = require('assert'),
  levelup = require('levelup'),
  testUtils = require('../../testUtils'),
  rlp = require('rlp'),
  Trie = require('merkle-patricia-tree');

var stateDB = levelup('', {
      db: require('memdown')
  }),
  state = new Trie(stateDB);

describe('[Common]: vmSha3', function () {

  var tests = Object.keys(vmSha3Test);
  tests.forEach(function(testKey) {

  // testKey = 'sha3_3';
    var testData = vmSha3Test[testKey];

    it(testKey + ' setup the trie', function (done) {
      var keysOfPre = Object.keys(testData.pre),
        acctData,
        account;

      async.each(keysOfPre, function(key, callback) {
        acctData = testData.pre[key];

        account = new Account();
        account.nonce = testUtils.fromDecimal(acctData.nonce);
        account.balance = testUtils.fromDecimal(acctData.balance);
        state.put(new Buffer(key, 'hex'), account.serialize(), callback);
      }, done);
    });

    it(testKey + ' run code', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        acctData,
        account,
        runCodeData,
        vm = new VM(state);

      acctData = testData.pre[testData.exec.address];
      account = new Account();
      account.nonce = testUtils.fromDecimal(acctData.nonce);
      account.balance = testUtils.fromDecimal(acctData.balance);

      var bignum = require('bignum')
      var log = { info: console.log }
      vm.onStep = function (info, done) {
        log.info('vm', bignum(info.pc).toString(16) + ' Opcode: ' + info.opcode + ' Gas: ' + info.gasLeft.toString());

        info.stack.reverse();
        info.stack.forEach(function (item) {
          log.info('vm', '    ' + item.toString('hex'));
        });
        info.stack.reverse();

        done();
      };

      runCodeData = testUtils.makeRunCodeData(testData.exec, account, block);
      vm.runCode(runCodeData, function(err, results) {
        if (testKey === 'sha3_3') {
          assert(err)
          console.log('err: ', err)
          done();
          return;
        }

        assert(!err);
        assert(results.gasUsed.toNumber() === (testData.exec.gas - testData.gas));

        var keysOfPost = Object.keys(testData.post);
        async.each(keysOfPost, function(key, callback) {
          acctData = testData.post[key];

          var account = results.account;

          assert(testUtils.toDecimal(account.balance) === acctData.balance);
          assert(testUtils.toDecimal(account.nonce) === acctData.nonce);

          var storageKeys = Object.keys(acctData.storage);
          if (storageKeys.length > 0) {
            state.root = account.stateRoot.toString('hex');
            storageKeys.forEach(function(skey) {
              state.get(testUtils.address(skey), function(err, data) {
                assert(!err);

console.log('storage: ', rlp.decode(data).toString('hex'))

                assert(rlp.decode(data).toString('hex') === acctData.storage[skey].slice(2));
                callback();
              });
            });
          } else {
            callback();
          }
        }, done);
      });
    });
  });

});
<commit_msg>clean up<commit_after>var vmSha3Test = require('../../../../tests/vmtests/vmSha3Test.json'),
  async = require('async'),
  VM = require('../../../lib/vm'),
  Account = require('../../../lib/account.js'),
  assert = require('assert'),
  levelup = require('levelup'),
  testUtils = require('../../testUtils'),
  rlp = require('rlp'),
  Trie = require('merkle-patricia-tree');

var stateDB = levelup('', {
      db: require('memdown')
  }),
  state = new Trie(stateDB);

describe('[Common]: vmSha3', function () {

  var tests = Object.keys(vmSha3Test);
  tests.forEach(function(testKey) {
    var testData = vmSha3Test[testKey];

    it(testKey + ' setup the trie', function (done) {
      var keysOfPre = Object.keys(testData.pre),
        acctData,
        account;

      async.each(keysOfPre, function(key, callback) {
        acctData = testData.pre[key];

        account = new Account();
        account.nonce = testUtils.fromDecimal(acctData.nonce);
        account.balance = testUtils.fromDecimal(acctData.balance);
        state.put(new Buffer(key, 'hex'), account.serialize(), callback);
      }, done);
    });

    it(testKey + ' run code', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        acctData,
        account,
        runCodeData,
        vm = new VM(state);

      acctData = testData.pre[testData.exec.address];
      account = new Account();
      account.nonce = testUtils.fromDecimal(acctData.nonce);
      account.balance = testUtils.fromDecimal(acctData.balance);

      var bignum = require('bignum')
      var log = { info: console.log }
      vm.onStep = function (info, done) {
        log.info('vm', bignum(info.pc).toString(16) + ' Opcode: ' + info.opcode + ' Gas: ' + info.gasLeft.toString());

        info.stack.reverse();
        info.stack.forEach(function (item) {
          log.info('vm', '    ' + item.toString('hex'));
        });
        info.stack.reverse();

        done();
      };

      runCodeData = testUtils.makeRunCodeData(testData.exec, account, block);
      vm.runCode(runCodeData, function(err, results) {
        if (testKey === 'sha3_3') {
          assert(err)
          console.log('err: ', err)
          done();
          return;
        }

        assert(!err);
        assert(results.gasUsed.toNumber() === (testData.exec.gas - testData.gas));

        var keysOfPost = Object.keys(testData.post);
        async.each(keysOfPost, function(key, callback) {
          acctData = testData.post[key];

          var account = results.account;

          assert(testUtils.toDecimal(account.balance) === acctData.balance);
          assert(testUtils.toDecimal(account.nonce) === acctData.nonce);

          var storageKeys = Object.keys(acctData.storage);
          if (storageKeys.length > 0) {
            state.root = account.stateRoot.toString('hex');
            storageKeys.forEach(function(skey) {
              state.get(testUtils.address(skey), function(err, data) {
                assert(!err);
                assert(rlp.decode(data).toString('hex') === acctData.storage[skey].slice(2));
                callback();
              });
            });
          } else {
            callback();
          }
        }, done);
      });
    });
  });

});
<|endoftext|>


<commit_before>(function() {

    'use strict';

    angular.module('requisition-view', [
        'ngBootbox',
        'openlmis-templates',
        'requisition',
        'requisition-summary',
        'requisition-validation',
        'requisition-status-messages',
        'ui.bootstrap',
        'ui.router'
    ]);

})();
<commit_msg>OLMIS-1957: removed unused dependency from requisition view module<commit_after>(function() {

    'use strict';

    angular.module('requisition-view', [
        'ngBootbox',
        'openlmis-templates',
        'requisition',
        'requisition-summary',
        'requisition-validation',
        'requisition-status-messages',
        'ui.router'
    ]);

})();
<|endoftext|>


<commit_before>// truesight-goggles.user.js
// Copyright 2013 Patrick Meade
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
// ==UserScript==
// @name            truesight-goggles
// @version         0.4
// @updateURL       https://github.com/blinkdog/truesight-goggles/raw/master/src/main/webapp/js/truesight-goggles.user.js
// @namespace       http://pages.cs.wisc.edu/~meade/greasemonkey/
// @description     Enhance your experience on Paizo's website
// @match           http://paizo.com/*
// @match           http://*.paizo.com/*
// @match           https://paizo.com/*
// @match           https://*.paizo.com/*
// @require         http://code.jquery.com/jquery-1.9.1.min.js
// @require         http://code.jquery.com/ui/1.10.2/jquery-ui.js
// @require         https://userscripts.org/scripts/source/145813.user.js
// @resource        jQueryUiCss         http://code.jquery.com/ui/1.10.2/themes/overcast/jquery-ui.min.css
// @resource        jQueryUiThemeCss    http://code.jquery.com/ui/1.10.2/themes/overcast/jquery.ui.theme.css
// @resource        juiAnimatedOverlay  http://code.jquery.com/ui/1.10.2/themes/overcast/images/animated-overlay.gif
// @resource        juiBgInsetSoft      http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-bg_inset-soft_50_c9c9c9_1x100.png
// @resource        juiBgGlass35        http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-bg_glass_35_dddddd_1x400.png
// @resource        juiBgGlass60        http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-bg_glass_60_eeeeee_1x400.png
// @resource        juiBgGlass100       http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-bg_glass_100_f8f8f8_1x400.png
// @resource        juiBgInsetHard      http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-bg_inset-hard_75_999999_1x100.png
// @resource        juiBgFlat55ee       http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-bg_flat_55_eeeeee_40x100.png
// @resource        juiBgFlat55c0       http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-bg_flat_55_c0402a_40x100.png
// @resource        juiIcons99          http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-icons_999999_256x240.png
// @resource        juiIcons70          http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-icons_70b2e1_256x240.png
// @resource        juiIcons33          http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-icons_3383bb_256x240.png
// @resource        juiIcons45          http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-icons_454545_256x240.png
// @resource        juiIconsfb          http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-icons_fbc856_256x240.png
// @resource        juiBgFlat0ee        http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-bg_flat_0_eeeeee_40x100.png
// @resource        juiBgFlat0aa        http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-bg_flat_0_aaaaaa_40x100.png
// @grant           GM_getResourceText
// ==/UserScript==
//---------------------------------------------------------------------------

/**
 * Load the jQuery UI CSS and associated image resources.
 * @see http://stackoverflow.com/questions/11528541/why-doesnt-my-jquery-ui-script-execute-in-greasemonkey-it-runs-in-the-firebug
 */
var loadjQueryUi = function() {
    var juiAnimatedOverlay = GM_getResourceURL("juiAnimatedOverlay");
    var juiBgInsetSoft = GM_getResourceURL("juiBgInsetSoft");
    var juiBgGlass35 = GM_getResourceURL("juiBgGlass35");
    var juiBgGlass60 = GM_getResourceURL("juiBgGlass60");
    var juiBgGlass100 = GM_getResourceURL("juiBgGlass100");
    var juiBgInsetHard = GM_getResourceURL("juiBgInsetHard");
    var juiBgFlat55ee = GM_getResourceURL("juiBgFlat55ee");
    var juiBgFlat55c0 = GM_getResourceURL("juiBgFlat55c0");
    var juiIcons99 = GM_getResourceURL("juiIcons99");
    var juiIcons70 = GM_getResourceURL("juiIcons70");
    var juiIcons33 = GM_getResourceURL("juiIcons33");
    var juiIcons45 = GM_getResourceURL("juiIcons45");
    var juiIconsfb = GM_getResourceURL("juiIconsfb");
    var juiBgFlat0ee = GM_getResourceURL("juiBgFlat0ee");
    var juiBgFlat0aa = GM_getResourceURL("juiBgFlat0aa");

    var rewriteCss = function(css) {
        css = css.replace(/images\/animated-overlay\.gif/g, juiAnimatedOverlay);
        css = css.replace(/images\/ui-bg_inset-soft_50_c9c9c9_1x100\.png/g, juiBgInsetSoft);
        css = css.replace(/images\/ui-bg_glass_35_dddddd_1x400\.png/g, juiBgGlass35);
        css = css.replace(/images\/ui-bg_glass_60_eeeeee_1x400\.png/g, juiBgGlass60);
        css = css.replace(/images\/ui-bg_glass_100_f8f8f8_1x400\.png/g, juiBgGlass100);
        css = css.replace(/images\/ui-bg_inset-hard_75_999999_1x100\.png/g, juiBgInsetHard);
        css = css.replace(/images\/ui-bg_flat_55_eeeeee_40x100\.png/g, juiBgFlat55ee);
        css = css.replace(/images\/ui-bg_flat_55_c0402a_40x100\.png/g, juiBgFlat55c0);
        css = css.replace(/images\/ui-icons_999999_256x240\.png/g, juiIcons99);
        css = css.replace(/images\/ui-icons_70b2e1_256x240\.png/g, juiIcons70);
        css = css.replace(/images\/ui-icons_3383bb_256x240\.png/g, juiIcons33);
        css = css.replace(/images\/ui-icons_454545_256x240\.png/g, juiIcons45);
        css = css.replace(/images\/ui-icons_fbc856_256x240\.png/g, juiIconsfb);
        css = css.replace(/images\/ui-bg_flat_0_eeeeee_40x100\.png/g, juiBgFlat0ee);
        css = css.replace(/images\/ui-bg_flat_0_aaaaaa_40x100\.png/g, juiBgFlat0aa);
        return css;
    }

    GM_addStyle(rewriteCss(GM_getResourceText("jQueryUiCss")));
    GM_addStyle(rewriteCss(GM_getResourceText("jQueryUiThemeCss")));
}

/**
 * Reposition the Truesight Goggles icon. It will be placed half it's own
 * width and height from the lower left corner of the current window.
 */
var reposition = function() {
    var tg = $("#truesight-goggles");
    var tgi = $("#truesight-goggles-img");
    var win = $(window);
    tg.offset({
        left: window.scrollX + (tgi.width() * 0.5),
        top: window.scrollY + win.height() - (tgi.height() * 1.5)
    });
}

var linkUnderlineStyles = [
    "a:link { text-decoration: underline !important; }",
    "a:visited { text-decoration: underline !important; }",
    "a:active { text-decoration: underline !important; }",
    "a:hover { text-decoration: underline !important; }"
];

//---------------------------------------------------------------------------
// Lights, Camera, Action!
//---------------------------------------------------------------------------
$(document).ready(function() {
    // get our jQuery UI on!
    loadjQueryUi();
    // give the owl some style
    GM_addStyle([
        "#truesight-goggles { opacity:0.5; }",
        "#truesight-goggles:hover { opacity:1.0; }",
        "#truesight-goggles-dialog { display:none; }",
    ].join(""));
    // create the owl
    $('body').append([
'
',
    '',
'
',
'
',
    '
',
        '
',
            '
CSS
',
            '
About
',
        '
',
        '
',
            '<input id="checkLinkUnderline" type="checkbox"/> Underline All Links',
        '
',
        '
',
            '
another_mage\'s Truesight Goggles
License: AGPL v3+ Source: GitHub
',
            '
Thanks to:
',
            '
Cheapy
',
        '
',
    '
',
'
'
    ].join(""));
    // resize the owl
    $("#truesight-goggles-img").width(
        ($("#truesight-goggles-img").width() / 2)
    );
    // position the owl
    reposition();
    // reposition the owl when necessary
    $(window).scroll(reposition);
    $(window).resize(reposition);
    // tell the owl to pop up a friendly dialog when clicked
    $("#truesight-goggles-img").click(function() {
        $("#truesight-goggles-tabs").tabs();
        $("#truesight-goggles-dialog").dialog();
    });
    // tell the Underline All Links checkbox how to act
    $("#checkLinkUnderline").click(function() {
        var checkbox = $("#checkLinkUnderline")[0];
        if(checkbox.checked) {
            linkUnderlineStyles.forEach(function(element, index, array) {
                GM_addStyle(element);
            });
        } else {
            $("style").each(function(index, element) {
                if(linkUnderlineStyles.indexOf(element.innerHTML) != -1) {
                    $(this).remove();
                }
            });
        }
    });
});

//---------------------------------------------------------------------------
// end of script
<commit_msg>Added persistent configuration state, hyperlinking post URLs<commit_after>// truesight-goggles.user.js
// Copyright 2013 Patrick Meade
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
// ==UserScript==
// @name            truesight-goggles
// @version         0.5
// @updateURL       https://github.com/blinkdog/truesight-goggles/raw/master/src/main/webapp/js/truesight-goggles.user.js
// @namespace       http://pages.cs.wisc.edu/~meade/greasemonkey/
// @description     Enhance your experience on Paizo's website
// @match           http://paizo.com/*
// @match           http://*.paizo.com/*
// @match           https://paizo.com/*
// @match           https://*.paizo.com/*
// @require         http://code.jquery.com/jquery-1.9.1.min.js
// @require         http://code.jquery.com/ui/1.10.2/jquery-ui.js
// @require         https://userscripts.org/scripts/source/145813.user.js
// @resource        jQueryUiCss         http://code.jquery.com/ui/1.10.2/themes/overcast/jquery-ui.min.css
// @resource        jQueryUiThemeCss    http://code.jquery.com/ui/1.10.2/themes/overcast/jquery.ui.theme.css
// @resource        juiAnimatedOverlay  http://code.jquery.com/ui/1.10.2/themes/overcast/images/animated-overlay.gif
// @resource        juiBgInsetSoft      http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-bg_inset-soft_50_c9c9c9_1x100.png
// @resource        juiBgGlass35        http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-bg_glass_35_dddddd_1x400.png
// @resource        juiBgGlass60        http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-bg_glass_60_eeeeee_1x400.png
// @resource        juiBgGlass100       http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-bg_glass_100_f8f8f8_1x400.png
// @resource        juiBgInsetHard      http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-bg_inset-hard_75_999999_1x100.png
// @resource        juiBgFlat55ee       http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-bg_flat_55_eeeeee_40x100.png
// @resource        juiBgFlat55c0       http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-bg_flat_55_c0402a_40x100.png
// @resource        juiIcons99          http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-icons_999999_256x240.png
// @resource        juiIcons70          http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-icons_70b2e1_256x240.png
// @resource        juiIcons33          http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-icons_3383bb_256x240.png
// @resource        juiIcons45          http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-icons_454545_256x240.png
// @resource        juiIconsfb          http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-icons_fbc856_256x240.png
// @resource        juiBgFlat0ee        http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-bg_flat_0_eeeeee_40x100.png
// @resource        juiBgFlat0aa        http://code.jquery.com/ui/1.10.2/themes/overcast/images/ui-bg_flat_0_aaaaaa_40x100.png
// @grant           GM_getResourceText
// ==/UserScript==
//---------------------------------------------------------------------------

var linkUnderlineStyles = [
    "a:link { text-decoration: underline !important; }",
    "a:visited { text-decoration: underline !important; }",
    "a:active { text-decoration: underline !important; }",
    "a:hover { text-decoration: underline !important; }"
];

//---------------------------------------------------------------------------

var tsgConfig = {};

//---------------------------------------------------------------------------

var applyConfiguration = function() {
    doLinkUnderline(tsgConfig.checkLinkUnderline);
    doProcessPosts();
}

var collateAnchorTags = function(splitHtml) {
    var result = new Array();
    var index = 0;
    while(index < splitHtml.length) {
        if(isTag(splitHtml[index])) {
            if(isAnchor(splitHtml[index])) {
                result.push([
                    splitHtml[index],
                    splitHtml[index+1],
                    splitHtml[index+2]
                ].join(""));
                index += 3;
                continue;
            }
        }
        result.push(splitHtml[index]);
        index++;
    }
    return result;
}

var doLinkAutolink = function(element) {
    var index = 0;
    for(index=0; index<element.splitHTML.length; index++) {
        if(isTag(element.splitHTML[index]) === false) {
            element.splitHTML[index] = element.splitHTML[index].replace(
                /([A-Za-z]+\:\/\/[^<]+)/gm,
                '$1');
        }
    }
}

var doLinkUnderline = function(underline) {
    if(underline) {
        linkUnderlineStyles.forEach(function(element, index, array) {
            GM_addStyle(element);
        });
    } else {
        $("style").each(function(index, element) {
            if(linkUnderlineStyles.indexOf(element.innerHTML) != -1) {
                $(this).remove();
            }
        });
    }
}

var doProcessPosts = function() {
    $(".post itemscope").each(function(index, element) {
        if(false) {
            // remove the post instead of working with it
        }
        else {
            // reload the original text of the post
            element.innerHTML = element.savedInnerHTML;
            // split the HTML into tags and text
            element.splitHTML = splitHtml(element.innerHTML);
            // collate anchor tags into a single array element
            element.splitHTML = collateAnchorTags(element.splitHTML);
            // automatically linkify naked URLs
            if(tsgConfig.checkLinkAutolink) { doLinkAutolink(element); }
//            // visually mark something
//            $(this).after("
");
            // recombine the split html
            element.innerHTML = element.splitHTML.join("");
        }
    });
}

var isAnchor = function(text) {
    return (text[1] === 'a' || text[1] === 'A');
}

var isTag = function(text) {
    return (text[0] === '<');
}

var loadConfiguration = function() {
    // load the configuration from storage
    tsgConfig.checkLinkAutolink = (GM_getValue("checkLinkAutolink", "false") === "true");
    tsgConfig.checkLinkUnderline = (GM_getValue("checkLinkUnderline", "false") === "true");
    // update the dialog box
    $("#checkLinkAutolink")[0].checked = tsgConfig.checkLinkAutolink;
    $("#checkLinkUnderline")[0].checked = tsgConfig.checkLinkUnderline;
}

var loadPostText = function() {
    $(".post itemscope").each(function(index, element) {
        element.innerHTML = element.savedInnerHTML;
    });
}

/**
 * Load the jQuery UI CSS and associated image resources.
 * @see http://stackoverflow.com/questions/11528541/why-doesnt-my-jquery-ui-script-execute-in-greasemonkey-it-runs-in-the-firebug
 */
var loadjQueryUi = function() {
    var juiAnimatedOverlay = GM_getResourceURL("juiAnimatedOverlay");
    var juiBgInsetSoft = GM_getResourceURL("juiBgInsetSoft");
    var juiBgGlass35 = GM_getResourceURL("juiBgGlass35");
    var juiBgGlass60 = GM_getResourceURL("juiBgGlass60");
    var juiBgGlass100 = GM_getResourceURL("juiBgGlass100");
    var juiBgInsetHard = GM_getResourceURL("juiBgInsetHard");
    var juiBgFlat55ee = GM_getResourceURL("juiBgFlat55ee");
    var juiBgFlat55c0 = GM_getResourceURL("juiBgFlat55c0");
    var juiIcons99 = GM_getResourceURL("juiIcons99");
    var juiIcons70 = GM_getResourceURL("juiIcons70");
    var juiIcons33 = GM_getResourceURL("juiIcons33");
    var juiIcons45 = GM_getResourceURL("juiIcons45");
    var juiIconsfb = GM_getResourceURL("juiIconsfb");
    var juiBgFlat0ee = GM_getResourceURL("juiBgFlat0ee");
    var juiBgFlat0aa = GM_getResourceURL("juiBgFlat0aa");

    var rewriteCss = function(css) {
        css = css.replace(/images\/animated-overlay\.gif/g, juiAnimatedOverlay);
        css = css.replace(/images\/ui-bg_inset-soft_50_c9c9c9_1x100\.png/g, juiBgInsetSoft);
        css = css.replace(/images\/ui-bg_glass_35_dddddd_1x400\.png/g, juiBgGlass35);
        css = css.replace(/images\/ui-bg_glass_60_eeeeee_1x400\.png/g, juiBgGlass60);
        css = css.replace(/images\/ui-bg_glass_100_f8f8f8_1x400\.png/g, juiBgGlass100);
        css = css.replace(/images\/ui-bg_inset-hard_75_999999_1x100\.png/g, juiBgInsetHard);
        css = css.replace(/images\/ui-bg_flat_55_eeeeee_40x100\.png/g, juiBgFlat55ee);
        css = css.replace(/images\/ui-bg_flat_55_c0402a_40x100\.png/g, juiBgFlat55c0);
        css = css.replace(/images\/ui-icons_999999_256x240\.png/g, juiIcons99);
        css = css.replace(/images\/ui-icons_70b2e1_256x240\.png/g, juiIcons70);
        css = css.replace(/images\/ui-icons_3383bb_256x240\.png/g, juiIcons33);
        css = css.replace(/images\/ui-icons_454545_256x240\.png/g, juiIcons45);
        css = css.replace(/images\/ui-icons_fbc856_256x240\.png/g, juiIconsfb);
        css = css.replace(/images\/ui-bg_flat_0_eeeeee_40x100\.png/g, juiBgFlat0ee);
        css = css.replace(/images\/ui-bg_flat_0_aaaaaa_40x100\.png/g, juiBgFlat0aa);
        return css;
    }

    GM_addStyle(rewriteCss(GM_getResourceText("jQueryUiCss")));
    GM_addStyle(rewriteCss(GM_getResourceText("jQueryUiThemeCss")));
}

/**
 * Reposition the Truesight Goggles icon. It will be placed half it's own
 * width and height from the lower left corner of the current window.
 */
var reposition = function() {
    var tg = $("#truesight-goggles");
    var tgi = $("#truesight-goggles-img");
    var win = $(window);
    tg.offset({
        left: window.scrollX + (tgi.width() * 0.5),
        top: window.scrollY + win.height() - (tgi.height() * 1.5)
    });
}

var saveConfiguration = function() {
    GM_setValue("checkLinkAutolink", tsgConfig.checkLinkAutolink);
    GM_setValue("checkLinkUnderline", tsgConfig.checkLinkUnderline);
}

var savePostText = function() {
    $(".post itemscope").each(function(index, element) {
        element.savedInnerHTML = element.innerHTML;
    });
}

var splitHtml = function(innerHtml) {
    var result = new Array();
    var index = 0;
    while(index < innerHtml.length) {
        var nextLeft = innerHtml.indexOf("<", index);
        if(nextLeft === -1) {
            var last = innerHtml.substring(index);
            result.push(last);
            index = innerHtml.length;
        } else {
            var nextRight = innerHtml.indexOf(">", nextLeft+1);
            if(nextRight === -1) {
                throw "Unmatched < in innerHtml";
            } else {
                var before = innerHtml.substring(index, nextLeft);
                var tag = innerHtml.substring(nextLeft, nextRight+1);
                if(before.length > 0) { result.push(before); }
                result.push(tag);
                index = nextRight+1;
            }
        }
    }
    return result;
}

//---------------------------------------------------------------------------
// Lights, Camera, Action!
//---------------------------------------------------------------------------
$(document).ready(function() {
    // get our jQuery UI on!
    loadjQueryUi();
    // give the owl some style
    GM_addStyle([
        "#truesight-goggles { opacity:0.5; }",
        "#truesight-goggles:hover { opacity:1.0; }",
        "#truesight-goggles-dialog { display:none; }",
    ].join(""));
    // create the owl
    $('body').append([
'
',
    '',
'
',
'
',
    '
',
        '
',
            '
Display
',
            '
Posts
',
            '
About
',
        '
',
        '
',
            '<input id="checkLinkUnderline" type="checkbox"/> Underline All Links
',
        '
',
        '
',
            '<input id="checkLinkAutolink" type="checkbox"/> Hyperlink URLs
',
        '
',
        '
',
            '
another_mage\'s Truesight Goggles
License: AGPL v3+ Source: GitHub
',
            '
Thanks to:
',
            '
Cheapy
',
        '
',
    '
',
'
'
    ].join(""));
    // resize the owl
    $("#truesight-goggles-img").width(
        ($("#truesight-goggles-img").width() / 2)
    );
    // position the owl
    reposition();
    // reposition the owl when necessary
    $(window).scroll(reposition);
    $(window).resize(reposition);
    // tell the owl to pop up a friendly dialog when clicked
    $("#truesight-goggles-img").click(function() {
        $("#truesight-goggles-tabs").tabs();
        $("#truesight-goggles-dialog").dialog();
    });
    // tell the Hyperlink URLs checkbox how to act
    $("#checkLinkAutolink").click(function() {
        tsgConfig.checkLinkAutolink = $("#checkLinkAutolink")[0].checked;
        saveConfiguration();
        doProcessPosts();
    });
    // tell the Underline All Links checkbox how to act
    $("#checkLinkUnderline").click(function() {
        tsgConfig.checkLinkUnderline = $("#checkLinkUnderline")[0].checked;
        saveConfiguration();
        doLinkUnderline(tsgConfig.checkLinkUnderline);
    });
    // save post text, if any
    savePostText();
    // load and apply the configuration
    loadConfiguration();
    applyConfiguration();
});

//debugger;
//---------------------------------------------------------------------------
// end of script
<|endoftext|>


<commit_before>describe('Unit Test: people module', function() {
	var controller;
	var scope;
	var peopleService;
	var q;
	var deferred;

	beforeEach(module("people"));

	beforeEach(inject(function($controller, $rootScope, $q) {
		peopleService = {
			getPeople: function() {
				deferred = q.defer();
				return deferred.promise;
			}
		};
		scope = $rootScope.$new();
		q = $q;
		controller = $controller("PeopleController", {$scope: scope, PeopleService: peopleService})
		spyOn(peopleService, 'getPeople').andCallThrough();
	}));

	describe("PeopleController" ,function() {
		it("should fetch a list of people from a backend service", function() {
			controller.init();
			deferred.resolve();
			scope.$digest();
			expect(peopleService.getPeople).toHaveBeenCalled();
		})
	})

});<commit_msg>got jasmine spies working<commit_after>var peopleData = [
	{firstName: 'Annie', lastName: 'Kim', email: 'anniekim@maroptic.com' },
	{firstName: 'Jane', lastName: 'Doe', email: 'jdoe@maroptic.com' },
];
var personData = {firstName: 'Annie', lastName: 'Kim', email: 'anniekim@maroptic.com' };

describe('Unit Test: people module', function() {
	var $controller;
	var peopleCtrl;
	var $scope;
	var peopleService;

	beforeEach(module("people"));

	beforeEach(inject(function(_$controller_, $rootScope, $q, _PeopleService_) {
		$controller = _$controller_;
		$scope = $rootScope.$new();
		peopleService = _PeopleService_;

		spyOn(peopleService, 'getPeople').andCallFake(function() {
			return $q.when(peopleData);
		});

		spyOn(peopleService, 'getPerson').andCallFake(function() {
			return $q.when(personData);
		});

	}));

	function createController() {
		peopleCtrl = $controller('PeopleController', {$scope: $scope});
	}

	describe("PeopleController" ,function() {
		it("should fetch a list of people from a backend service and populate the peopleCtrl.people property", function() {
			createController();
			peopleCtrl.init(); //get the list of people by calling the peopleService
			$scope.$digest(); //run the digest cycle
			expect(peopleService.getPeople).toHaveBeenCalled();
			expect(peopleCtrl.people.length).not.toBe(0);
		});

		it("should populate the selectedPerson when selectPerson() is called", function() {
			createController();
			peopleCtrl.selectPerson(personData);
			$scope.$digest();
			expect(peopleCtrl.selectedPerson).not.toBe(undefined);
		})
	})
});<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var fs = require('fs');
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var markJSON = require('markit-json');
var docUtil = require('amazeui-doc-util');
var through = require('through2');
var Sequelize = require('sequelize');
var runSequence = require('run-sequence');
var del = require('del');
var pkg = require('./amazeui/package.json');

var paths = {
  mdDocs: './amazeui/docs/**/*.md',
  dist: {
    html: 'dist/AmazeUI.docset/Contents/Resources/Documents',
    assets: 'dist/AmazeUI.docset/Contents/Resources/Documents/assets/'
  },
  docsets: 'dist/AmazeUI.docset/Contents/',
  sqlite: 'dist/AmazeUI.docset/Contents/Resources/docSet.dsidx'
};

var tpl = fs.readFileSync('template/docsets/default.hbs', {
  encoding: 'utf8'
});

var sequelize = new Sequelize(null, null, null, {
  dialect: 'sqlite',
  storage: paths.sqlite
});

// Dash Docsets Search Index
var SearchIndex = sequelize.define('searchIndex', {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  name: {
    type: Sequelize.STRING
  },
  type: {
    type: Sequelize.STRING
  },
  path: {
    type: Sequelize.STRING
  }
}, {
  freezeTableName: true,
  timestamps: false
});

var createIndex = function(data) {
  sequelize.sync({force: true}).then(function() {
    SearchIndex.create({
      name: data.name,
      type: data.type,
      path: data.path
    }).then(function() {
      console.log('[CreateIndex] inserted: %s', data.path);
    }, function() {
      console.error('[CreateIndex] error: %s', data.path);
    });
  });
};

var setAsserts = function() {
  return through.obj(function(input, enc, callback) {
    var relative = input.relative.replace('.json', '');
    var data = JSON.parse(input.contents.toString());
    var assets = 'assets/';
    var type = 'Guide';
    if (relative.indexOf('/') > -1 ) {
      assets = '../' + assets;
    }

    if (relative.indexOf('javascript') > -1) {
      type = 'Plugin';
    } else if (relative.indexOf('styleguide') > -1) {
      type = 'Section';
    } else if (relative.indexOf('css') > -1) {
      type = 'Style';
    }

    if (relative !== 'getting-started') {
      createIndex({
        name: relative,
        type: type,
        path: relative + '.html'
      });
    }

    data.assets = assets;
    input.contents = new Buffer(JSON.stringify(data));
    this.push(input);
    callback();
  });
};

gulp.task('less', function() {
  return gulp.src('template/docsets/less/app.less')
    .pipe($.less())
    .pipe(gulp.dest(paths.dist.assets + 'css'));
});

gulp.task('markdown', function() {
  return gulp.src([
    paths.mdDocs,
    '!amazeui/docs/about/**/*',
    '!amazeui/docs/about.md',
    '!amazeui/docs/amaze.md',
    '!amazeui/docs/customize.md',
    '!amazeui/docs/javascript/share.md',
    '!amazeui/docs/javascript/pureview.md',
    '!amazeui/docs/css/mixins.md',
    '!amazeui/docs/css/variables.md'
  ])
    .pipe(markJSON(docUtil.markedOptions))
    .pipe(setAsserts())
    .pipe(docUtil.applyTemplate(tpl))
    .pipe($.rename(function(file) {
      file.extname = '.html';
      if (file.basename === 'getting-started') {
        file.basename = 'index';
      }
    }))
    .pipe(gulp.dest(paths.docsets + 'Resources/Documents'));
});

gulp.task('misc:info', function() {
  return gulp.src('template/dash/Info.plist')
    .pipe(gulp.dest(paths.docsets))
});

gulp.task('misc:icon', function() {
  return gulp.src('template/docsets/i/icon.png')
    .pipe(gulp.dest('dist/AmazeUI.docset/'));
});

gulp.task('misc:amui', function() {
  return gulp.src([
    '*/amazeui.min.css',
    '*/amazeui.min.js',
    '*/*.otf',
    '*/fontawesome*'
  ], {
    cwd: 'node_modules/amazeui/dist'
  })
    .pipe(gulp.dest(paths.dist.assets));
});

gulp.task('misc:jq', function() {
  return gulp.src('*.min.js', {
    cwd: 'node_modules/jquery/dist/cdn'
  })
    .pipe($.rename('jquery.min.js'))
    .pipe(gulp.dest(paths.dist.assets + 'js'));
});

gulp.task('misc', ['misc:info', 'misc:icon', 'misc:amui', 'misc:jq']);

gulp.task('clean', function(cb) {
  del('dist', cb);
});

gulp.task('zip', function(cb) {
  return gulp.src(['dist/**/*', '!dist/*.zip'])
    .pipe($.zip('AmazeUI.Docsets-' + pkg.version + '.zip'))
    .pipe(gulp.dest('dist'));
});

gulp.task('ghPages', function() {
  return gulp.src('dist/*.zip')
    .pipe($.ghPages())
});

// default task
gulp.task('default', function(cb) {
  runSequence('clean', 'less', ['misc', 'markdown'], 'zip', 'ghPages', cb);
});
<commit_msg>update gulp config<commit_after>'use strict';

var path = require('path');
var fs = require('fs');
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var markJSON = require('markit-json');
var docUtil = require('amazeui-doc-util');
var through = require('through2');
var Sequelize = require('sequelize');
var runSequence = require('run-sequence');
var del = require('del');
var pkg = require('./amazeui/package.json');

var paths = {
  mdDocs: './amazeui/docs/**/*.md',
  dist: {
    html: 'dist/AmazeUI.docset/Contents/Resources/Documents',
    assets: 'dist/AmazeUI.docset/Contents/Resources/Documents/assets/'
  },
  docsets: 'dist/AmazeUI.docset/Contents/',
  sqlite: 'dist/AmazeUI.docset/Contents/Resources/docSet.dsidx'
};

var tpl = fs.readFileSync('template/docsets/default.hbs', {
  encoding: 'utf8'
});

var sequelize = new Sequelize(null, null, null, {
  dialect: 'sqlite',
  storage: paths.sqlite
});

// Dash Docsets Search Index
var SearchIndex = sequelize.define('searchIndex', {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  name: {
    type: Sequelize.STRING
  },
  type: {
    type: Sequelize.STRING
  },
  path: {
    type: Sequelize.STRING
  }
}, {
  freezeTableName: true,
  timestamps: false
});

var createIndex = function(data) {
  sequelize.sync().then(function() {
    SearchIndex.create({
      name: data.name,
      type: data.type,
      path: data.path
    }).then(function() {
      console.log('[CreateIndex] inserted: %s', data.path);
    }, function() {
      console.error('[CreateIndex] error: %s', data.path);
    });
  });
};

var setAsserts = function() {
  return through.obj(function(input, enc, callback) {
    var relative = input.relative.replace('.json', '');
    var data = JSON.parse(input.contents.toString());
    var assets = 'assets/';
    var type = 'Guide';
    if (relative.indexOf('/') > -1 ) {
      assets = '../' + assets;
    }

    if (relative.indexOf('styleguide') > -1) {
      type = 'Section';
    } else if (relative.indexOf('javascript') > -1) {
      type = 'Plugin';
    } else if (relative.indexOf('css') > -1) {
      type = 'Style';
    }

    if (relative !== 'getting-started') {
      createIndex({
        name: relative,
        type: type,
        path: relative + '.html'
      });
    }

    data.assets = assets;
    input.contents = new Buffer(JSON.stringify(data));
    this.push(input);
    callback();
  });
};

gulp.task('less', function() {
  return gulp.src('template/docsets/less/app.less')
    .pipe($.less())
    .pipe(gulp.dest(paths.dist.assets + 'css'));
});

gulp.task('markdown', function() {
  return gulp.src([
    paths.mdDocs,
    '!amazeui/docs/about/**/*',
    '!amazeui/docs/about.md',
    '!amazeui/docs/amaze.md',
    '!amazeui/docs/customize.md',
    '!amazeui/docs/javascript/share.md',
    '!amazeui/docs/javascript/pureview.md',
    '!amazeui/docs/css/mixins.md',
    '!amazeui/docs/css/variables.md',
    '!amazeui/docs/getting-started/layouts.md',
    '!amazeui/docs/getting-started/team.md'
  ])
    .pipe(markJSON(docUtil.markedOptions))
    .pipe(setAsserts())
    .pipe(docUtil.applyTemplate(tpl))
    .pipe($.rename(function(file) {
      file.extname = '.html';
      if (file.basename === 'getting-started') {
        file.basename = 'index';
      }
    }))
    .pipe(gulp.dest(paths.docsets + 'Resources/Documents'));
});

gulp.task('misc:info', function() {
  return gulp.src('template/dash/Info.plist')
    .pipe(gulp.dest(paths.docsets))
});

gulp.task('misc:icon', function() {
  return gulp.src('template/docsets/i/icon.png')
    .pipe(gulp.dest('dist/AmazeUI.docset/'));
});

gulp.task('misc:amui', function() {
  return gulp.src([
    '*/amazeui.min.css',
    '*/amazeui.min.js',
    '*/*.otf',
    '*/fontawesome*'
  ], {
    cwd: 'node_modules/amazeui/dist'
  })
    .pipe(gulp.dest(paths.dist.assets));
});

gulp.task('misc:jq', function() {
  return gulp.src('*.min.js', {
    cwd: 'node_modules/jquery/dist/cdn'
  })
    .pipe($.rename('jquery.min.js'))
    .pipe(gulp.dest(paths.dist.assets + 'js'));
});

gulp.task('misc', ['misc:info', 'misc:icon', 'misc:amui', 'misc:jq']);

gulp.task('clean', function(cb) {
  del('dist', cb);
});

gulp.task('zip', function(cb) {
  return gulp.src(['dist/**/*', '!dist/*.zip'])
    .pipe($.zip('AmazeUI.Docsets-' + pkg.version + '.zip'))
    .pipe(gulp.dest('dist'));
});

gulp.task('deploy', function() {
  return gulp.src('dist/*.zip')
    .pipe($.ghPages())
});

gulp.task('watch', function() {
  gulp.watch('amazeui/docs/**/*', ['markdown']);
});

// default task
gulp.task('default', function(cb) {
  runSequence('clean', 'less', ['misc', 'markdown'], 'watch', cb);
});
<|endoftext|>


<commit_before>/**
 * WebSocket transport. Needed because browsers can't handle TCP sockets
 * so we use separate WebSocket server to proxy messages into TCP data
 * packets. Available for both Node.js and Browser platforms.
 * **NOTE**: `WsTransport` is exported as a module.
 * @example var WsTransport = require("bitmessage/lib/net/ws");
 * @module bitmessage/net/ws
 */

"use strict";

var objectAssign = Object.assign || require("object-assign");
var inherits = require("inherits");
var WebSocket = require("ws");  // jshint ignore:line
var assert = require("../_util").assert;
var PPromise = require("../platform").Promise;
var structs = require("../structs");
var messages = require("../messages");
var BaseTransport = require("./base");

var WebSocketServer = WebSocket.Server;
var getmsg = BaseTransport._getmsg;
var unmap = BaseTransport._unmap;

/**
 * WebSocket transport class. Implements
 * [base transport interface]{@link
 * module:bitmessage/net/base.BaseTransport}.
 * @param {Object=} opts - Transport options
 * @param {Array} opts.seeds - Bootstrap nodes (none by default)
 * @param {Object} opts.services -
 * [Service features]{@link module:bitmessage/structs.ServicesBitfield}
 * provided by this node (`NODE_NETWORK` by default)
 * @param {(Array|string|Buffer)} opts.userAgent -
 * [User agent]{@link module:bitmessage/user-agent} of this node
 * (bitmessage's by default)
 * @param {number[]} opts.streamNumbers - Streams accepted by this node
 * (1 by default)
 * @param {number} opts.port - Incoming port of this node, makes sence
 * only on Node platform (18444 by default)
 * @constructor
 * @static
 */
function WsTransport(opts) {
  WsTransport.super_.call(this);
  objectAssign(this, opts);
  this.seeds = this.seeds || [];
  this.port = this.port || 18444;
}

inherits(WsTransport, BaseTransport);

WsTransport.prototype._sendVersion = function() {
  return this.send(messages.version.encode({
    services: this.services,
    userAgent: this.userAgent,
    streamNumbers: this.streamNumbers,
    port: this.port,
    remoteHost: this._client._socket.remoteAddress,
    remotePort: this._client._socket.remotePort,
  }));
};

WsTransport.prototype._handleTimeout = function() {
  var client = this._client;
  // TODO(Kagami): We may also want to close connection if it wasn't
  // established within minute.
  client._socket.setTimeout(20000);
  client._socket.on("timeout", function() {
    client.close();
  });
  this.on("established", function() {
    // Raise timeout up to 10 minutes per spec.
    // TODO(Kagami): Send ping frame every 5 minutes as PyBitmessage.
    client._socket.setTimeout(600000);
  });
};

WsTransport.prototype._setupClient = function(client, incoming) {
  var self = this;
  self._client = client;
  var verackSent = false;
  var verackReceived = false;
  var established = false;

  client.on("open", function() {
    // NOTE(Kagami): This handler shouldn't be called at all for
    // incoming connections but let's be sure.
    if (!incoming) {
      // NOTE(Kagami): We may set timeout only after connection was
      // opened because socket may not yet be available when
      // `_setupClient` is called.
      self._handleTimeout();
      self.emit("open");
      self._sendVersion();
    }
  });

  client.on("message", function(data, flags) {
    var decoded;
    if (!flags.binary) {
      // TODO(Kagami): Send `error` message and ban node for some time
      // if there were too many errors?
      return self.emit("warning", new Error("Peer sent non-binary data"));
    }
    try {
      decoded = structs.message.decode(data);
    } catch (err) {
      return self.emit("warning", new Error(
        "Message decoding error: " + err.message
      ));
    }
    self.emit("message", decoded.command, decoded.payload, decoded);
  });

  // High-level message processing.
  self.on("message", function(command) {
    if (!established) {
      // TODO: Process version data.
      // TODO: Disconnect if proto version < 3.
      if (command === "version") {
        if (verackSent) {
          return;
        }
        self.send("verack");
        verackSent = true;
        if (incoming) {
          self._sendVersion();
        } else if (verackReceived) {
          established = true;
          self.emit("established");
        }
      } else if (command === "verack") {
        verackReceived = true;
        if (verackSent) {
          established = true;
          self.emit("established");
        }
      }
    }
  });

  client.on("error", function(err) {
    self.emit("error", err);
  });

  client.on("close", function() {
    self.emit("close");
    delete self._client;
  });
};

WsTransport.prototype.bootstrap = function() {
  return PPromise.resolve([].concat(this.seeds));
};

/**
 * Connect to a WebSocket node. Connection arguments are the same as for
 * [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket).
 */
WsTransport.prototype.connect = function(address, protocols, options) {
  assert(!this._client, "Already connected");
  assert(!this._server, "Already listening");
  // `new` doesn't work with `apply`, so passing all possible arguments
  // manually.
  this._setupClient(new WebSocket(address, protocols, options));
};

/**
 * Listen for incoming WebSocket connections. Listen arguments are the
 * same as for
 * [WebSocketServer](https://github.com/websockets/ws#server-example).
 * Available only for Node platform.
 */
WsTransport.prototype.listen = function(options, callback) {
  assert(!this._client, "Already connected");
  assert(!this._server, "Already listening");

  var self = this;
  var server = self._server = new WebSocketServer(options, callback);

  server.on("connection", function(client) {
    var opts = objectAssign({}, self);
    delete opts._server;
    var transport = new self.constructor(opts);
    var incoming = true;
    transport._setupClient(client, incoming);
    transport._handleTimeout();
    var addr = client._socket.remoteAddress;
    var port = client._socket.remotePort;
    self.emit("connection", transport, unmap(addr), port);
  });

  server.on("error", function(err) {
    self.emit("error", err);
  });
};

WsTransport.prototype.send = function() {
  if (this._client) {
    // TODO(Kagami): `mask: true` doesn't work with Chromium 40. File a
    // bug to ws bugtracker.
    this._client.send(getmsg(arguments), {binary: true});
  } else {
    throw new Error("Not connected");
  }
};

WsTransport.prototype.broadcast = function() {
  var data = getmsg(arguments);
  if (this._server) {
    this._server.clients.forEach(function(client) {
      client.send(data, {binary: true});
    });
  } else {
    throw new Error("Not listening");
  }
};

WsTransport.prototype.close = function() {
  if (this._client) {
    this._client.close();
  } else if (this._server) {
    // `ws` server terminates immediately without any events.
    this._server.close();
    this.emit("close");
    delete this._server;
  }
};

module.exports = WsTransport;
<commit_msg>Emit "close" for ws transport<commit_after>/**
 * WebSocket transport. Needed because browsers can't handle TCP sockets
 * so we use separate WebSocket server to proxy messages into TCP data
 * packets. Available for both Node.js and Browser platforms.
 * **NOTE**: `WsTransport` is exported as a module.
 * @example var WsTransport = require("bitmessage/lib/net/ws");
 * @module bitmessage/net/ws
 */

"use strict";

var objectAssign = Object.assign || require("object-assign");
var inherits = require("inherits");
var WebSocket = require("ws");  // jshint ignore:line
var assert = require("../_util").assert;
var PPromise = require("../platform").Promise;
var structs = require("../structs");
var messages = require("../messages");
var BaseTransport = require("./base");

var WebSocketServer = WebSocket.Server;
var getmsg = BaseTransport._getmsg;
var unmap = BaseTransport._unmap;

/**
 * WebSocket transport class. Implements
 * [base transport interface]{@link
 * module:bitmessage/net/base.BaseTransport}.
 * @param {Object=} opts - Transport options
 * @param {Array} opts.seeds - Bootstrap nodes (none by default)
 * @param {Object} opts.services -
 * [Service features]{@link module:bitmessage/structs.ServicesBitfield}
 * provided by this node (`NODE_NETWORK` by default)
 * @param {(Array|string|Buffer)} opts.userAgent -
 * [User agent]{@link module:bitmessage/user-agent} of this node
 * (bitmessage's by default)
 * @param {number[]} opts.streamNumbers - Streams accepted by this node
 * (1 by default)
 * @param {number} opts.port - Incoming port of this node, makes sence
 * only on Node platform (18444 by default)
 * @constructor
 * @static
 */
function WsTransport(opts) {
  WsTransport.super_.call(this);
  objectAssign(this, opts);
  this.seeds = this.seeds || [];
  this.port = this.port || 18444;
}

inherits(WsTransport, BaseTransport);

WsTransport.prototype._sendVersion = function() {
  return this.send(messages.version.encode({
    services: this.services,
    userAgent: this.userAgent,
    streamNumbers: this.streamNumbers,
    port: this.port,
    remoteHost: this._client._socket.remoteAddress,
    remotePort: this._client._socket.remotePort,
  }));
};

WsTransport.prototype._handleTimeout = function() {
  var client = this._client;
  // TODO(Kagami): We may also want to close connection if it wasn't
  // established within minute.
  client._socket.setTimeout(20000);
  client._socket.on("timeout", function() {
    client.close();
  });
  this.on("established", function() {
    // Raise timeout up to 10 minutes per spec.
    // TODO(Kagami): Send ping frame every 5 minutes as PyBitmessage.
    client._socket.setTimeout(600000);
  });
};

WsTransport.prototype._setupClient = function(client, incoming) {
  var self = this;
  self._client = client;
  var verackSent = false;
  var verackReceived = false;
  var established = false;

  client.on("open", function() {
    // NOTE(Kagami): This handler shouldn't be called at all for
    // incoming connections but let's be sure.
    if (!incoming) {
      // NOTE(Kagami): We may set timeout only after connection was
      // opened because socket may not yet be available when
      // `_setupClient` is called.
      self._handleTimeout();
      self.emit("open");
      self._sendVersion();
    }
  });

  client.on("message", function(data, flags) {
    var decoded;
    if (!flags.binary) {
      // TODO(Kagami): Send `error` message and ban node for some time
      // if there were too many errors?
      return self.emit("warning", new Error("Peer sent non-binary data"));
    }
    try {
      decoded = structs.message.decode(data);
    } catch (err) {
      return self.emit("warning", new Error(
        "Message decoding error: " + err.message
      ));
    }
    self.emit("message", decoded.command, decoded.payload, decoded);
  });

  // High-level message processing.
  self.on("message", function(command) {
    if (!established) {
      // TODO: Process version data.
      // TODO: Disconnect if proto version < 3.
      if (command === "version") {
        if (verackSent) {
          return;
        }
        self.send("verack");
        verackSent = true;
        if (incoming) {
          self._sendVersion();
        } else if (verackReceived) {
          established = true;
          self.emit("established");
        }
      } else if (command === "verack") {
        verackReceived = true;
        if (verackSent) {
          established = true;
          self.emit("established");
        }
      }
    }
  });

  client.on("error", function(err) {
    self.emit("error", err);
  });

  client.on("close", function() {
    self.emit("close");
    delete self._client;
  });
};

WsTransport.prototype.bootstrap = function() {
  return PPromise.resolve([].concat(this.seeds));
};

/**
 * Connect to a WebSocket node. Connection arguments are the same as for
 * [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket).
 */
WsTransport.prototype.connect = function(address, protocols, options) {
  assert(!this._client, "Already connected");
  assert(!this._server, "Already listening");
  // `new` doesn't work with `apply`, so passing all possible arguments
  // manually.
  this._setupClient(new WebSocket(address, protocols, options));
};

/**
 * Listen for incoming WebSocket connections. Listen arguments are the
 * same as for
 * [WebSocketServer](https://github.com/websockets/ws#server-example).
 * Available only for Node platform.
 */
WsTransport.prototype.listen = function(options, callback) {
  assert(!this._client, "Already connected");
  assert(!this._server, "Already listening");

  var self = this;
  var server = self._server = new WebSocketServer(options, callback);

  server.on("connection", function(client) {
    var opts = objectAssign({}, self);
    delete opts._server;
    var transport = new self.constructor(opts);
    var incoming = true;
    transport._setupClient(client, incoming);
    transport._handleTimeout();
    var addr = client._socket.remoteAddress;
    var port = client._socket.remotePort;
    self.emit("connection", transport, unmap(addr), port);
  });

  server.on("error", function(err) {
    self.emit("error", err);
  });

  // `ws` doesn't emit "close" event by default.
  server._server.on("close", function() {
    self.emit("close");
    delete self._server;
  });
};

WsTransport.prototype.send = function() {
  if (this._client) {
    // TODO(Kagami): `mask: true` doesn't work with Chromium 40. File a
    // bug to ws bugtracker.
    this._client.send(getmsg(arguments), {binary: true});
  } else {
    throw new Error("Not connected");
  }
};

WsTransport.prototype.broadcast = function() {
  var data = getmsg(arguments);
  if (this._server) {
    this._server.clients.forEach(function(client) {
      client.send(data, {binary: true});
    });
  } else {
    throw new Error("Not listening");
  }
};

WsTransport.prototype.close = function() {
  if (this._client) {
    this._client.close();
  } else if (this._server) {
    this._server.close();
  }
};

module.exports = WsTransport;
<|endoftext|>


<commit_before>/*jslint node: true, esversion: 6 */
'use strict';

var http = require('http');
var Router = require('router');
var finalhandler = require('finalhandler');
var to_rss = require('./to_rss');

var router = new Router();
router.get('/comptop', function (req, res) {
    var title = 'Computational Topology Message Board';
    var description = 'RSS feed of the computational topology message board';
    var muut = new to_rss.Muut(
        'comptop', 'dave@cs.unc.edu', title, description
    );
    to_rss.muutToRss(muut,res);
});

function requestHandler(req, res) {
    var done = finalhandler(req, res);
    router(req, res, done);
}

http.createServer(requestHandler).listen(8080);
<commit_msg>Specify port<commit_after>/*jslint node: true, esversion: 6 */
'use strict';

var http = require('http');
var Router = require('router');
var finalhandler = require('finalhandler');
var to_rss = require('./to_rss');

var router = new Router();
router.get('/comptop', function (req, res) {
    var title = 'Computational Topology Message Board';
    var description = 'RSS feed of the computational topology message board';
    var muut = new to_rss.Muut(
        'comptop', 'dave@cs.unc.edu', title, description
    );
    to_rss.muutToRss(muut,res);
});

function requestHandler(req, res) {
    var done = finalhandler(req, res);
    router(req, res, done);
}

var port = process.env.PORT || 8080;
console.log("port is " + port);
http.createServer(requestHandler).listen(8080);
<|endoftext|>


<commit_before>angular.module('sislegisapp').controller(
		'ModalEncaminhamentosController',
		function($scope, $rootScope, $http, $filter, $routeParams, $location, $modalInstance, toaster, proposicao,
				TipoEncaminhamentoResource, ProposicaoResource, EncaminhamentoProposicaoResource, EncaminhamentoProposicaoHttp, UsuarioResource,
				ComentarioResource, BACKEND, $confirm) {

			var self = this;
			$scope.disabled = false;
			$scope.$location = $location;

			$scope.proposicao = proposicao || new ProposicaoResource();
			$scope.tipoEncaminhamento = new TipoEncaminhamentoResource();
			$scope.encaminhamentoProposicao = new EncaminhamentoProposicaoResource();
			$scope.listaEncaminhamento = TipoEncaminhamentoResource.queryAll() || [];

			$scope.getUsuarios = function(val) {
				return $http.get(BACKEND + '/usuarios/find', {
					params : {
						nome : val
					}
				}).then(function(response) {
					return response.data.map(function(item) {
						return item;
					});
				});
			};

			$scope.ok = function() {
				$modalInstance.close($scope.proposicao);
			};

			$scope.cancel = function() {
				$modalInstance.dismiss('cancel');
			};

			$scope.isClean = function() {
				return angular.equals(self.original, $scope.encaminhamentoProposicao);
			};

			$scope.openUpdate = function(item) {
				$scope.encaminhamentoProposicao = new EncaminhamentoProposicaoResource(item);
			};

            $rootScope.$on('updateEncaminhamentos', function(event) {
                    EncaminhamentoProposicaoResource.findByProposicao({
                        ProposicaoId : $scope.proposicao.id
                    }, function(data) {
                        $scope.proposicao.listaEncaminhamentoProposicao = data;
                        $scope.encaminhamentoProposicao = new EncaminhamentoProposicaoResource();
                        $scope.tipoEncaminhamento = new TipoEncaminhamentoResource();
                    });

            });

            $scope.finalizar = function( encaminhamento ){
                var successCallback = function() {
                    toaster.pop('success', 'Encaminhamento finalizado com sucesso.');
                    $rootScope.$emit('updateEncaminhamentos');
                };
                var errorCallback = function() {
                    toaster.pop('error', 'Falha ao finalizar o encaminhamento.');
                    $rootScope.$emit('updateEncaminhamentos');
                };

                var finalizarTarefa = function() {
                    EncaminhamentoProposicaoHttp.finalizar(encaminhamento).then(successCallback, errorCallback);
                };

                if(!encaminhamento.descricaoComentario){
                    $confirm({text: 'Deseja fechar o encaminhamento sem comentário?', title: 'Finalização de encaminhamento', ok: 'Sim', cancel: 'Não'})
                        .then(finalizarTarefa);
                }else{
                    finalizarTarefa();
                }

            };

			$scope.update = function() {
				$scope.encaminhamentoProposicao.proposicao = new ProposicaoResource();
				$scope.encaminhamentoProposicao.proposicao.id = $scope.proposicao.id;

				var successCallback = function() {
					EncaminhamentoProposicaoResource.findByProposicao({
						ProposicaoId : $scope.proposicao.id
					}, function(data) {
						$scope.proposicao.listaEncaminhamentoProposicao = data;
						$scope.encaminhamentoProposicao = new EncaminhamentoProposicaoResource();
						$scope.tipoEncaminhamento = new TipoEncaminhamentoResource();
						toaster.pop('success', 'Encaminhamento atualizado com sucesso');
					});
				};
				var errorCallback = function() {
					$scope.encaminhamentoProposicao = new EncaminhamentoProposicaoResource();
					toaster.pop('error', 'Falha ao realizar operação.');
				};
				$scope.encaminhamentoProposicao.$update({
					EncaminhamentoProposicaoId : $scope.encaminhamentoProposicao.id
				}, successCallback, errorCallback);
			};

			$scope.save = function() {

				$scope.encaminhamentoProposicao.proposicao = new ProposicaoResource();
				$scope.encaminhamentoProposicao.proposicao.id = $scope.proposicao.id;
				if ($scope.encaminhamentoProposicao.dataHoraLimite != null) {
					$scope.encaminhamentoProposicao.dataHoraLimite = $scope.encaminhamentoProposicao.dataHoraLimite
							.getTime();
				}

				var successCallback = function(data, responseHeaders) {
					EncaminhamentoProposicaoResource.findByProposicao({
						ProposicaoId : $scope.proposicao.id
					}, function(data) {
						$scope.proposicao.listaEncaminhamentoProposicao = data;
						$scope.proposicao.totalEncaminhamentos++;
						$scope.encaminhamentoProposicao = new EncaminhamentoProposicaoResource();
						$scope.tipoEncaminhamento = new TipoEncaminhamentoResource();
						$rootScope.$emit('updateEncaminhamentos');
						toaster.pop('success', 'Encaminhamento inserido com sucesso');
					});
				};
				var errorCallback = function() {
					toaster.pop('error', 'Falha ao realizar operação.');
				};
				EncaminhamentoProposicaoResource.save($scope.encaminhamentoProposicao, successCallback, errorCallback);
			};

			// CALENDARIO
			$scope.setCalendar = function() {
				$scope.openCalendar = function($event) {
					$event.preventDefault();
					$event.stopPropagation();

					$scope.opened = true;
				};

				$scope.dateOptions = {
					formatYear : 'yy',
					startingDay : 1
				};

				$scope.format = 'dd/MM/yyyy';
			}

			$scope.setCalendar();

		});
<commit_msg>Hotfix para fechar o modal de encaminhamento<commit_after>angular.module('sislegisapp').controller(
		'ModalEncaminhamentosController',
		function($scope, $rootScope, $http, $filter, $routeParams, $location, $modalInstance, toaster, proposicao,
				TipoEncaminhamentoResource, ProposicaoResource, EncaminhamentoProposicaoResource, EncaminhamentoProposicaoHttp, UsuarioResource,
				ComentarioResource, BACKEND, $confirm) {

			var self = this;
			$scope.disabled = false;
			$scope.$location = $location;

			$scope.proposicao = proposicao || new ProposicaoResource();
			$scope.tipoEncaminhamento = new TipoEncaminhamentoResource();
			$scope.encaminhamentoProposicao = new EncaminhamentoProposicaoResource();
			$scope.listaEncaminhamento = TipoEncaminhamentoResource.queryAll() || [];

			$scope.getUsuarios = function(val) {
				return $http.get(BACKEND + '/usuarios/find', {
					params : {
						nome : val
					}
				}).then(function(response) {
					return response.data.map(function(item) {
						return item;
					});
				});
			};

			$scope.ok = function() {
                $modalInstance.close($scope.proposicao.listaEncaminhamentoProposicao);
			};

			$scope.cancel = function() {
				$modalInstance.dismiss('cancel');
			};

			$scope.isClean = function() {
				return angular.equals(self.original, $scope.encaminhamentoProposicao);
			};

			$scope.openUpdate = function(item) {
				$scope.encaminhamentoProposicao = new EncaminhamentoProposicaoResource(item);
			};

            $rootScope.$on('updateEncaminhamentos', function(event) {
                    EncaminhamentoProposicaoResource.findByProposicao({
                        ProposicaoId : $scope.proposicao.id
                    }, function(data) {
                        $scope.proposicao.listaEncaminhamentoProposicao = data;
                        $scope.encaminhamentoProposicao = new EncaminhamentoProposicaoResource();
                        $scope.tipoEncaminhamento = new TipoEncaminhamentoResource();
                    });

            });

            $scope.finalizar = function( encaminhamento ){
                var successCallback = function() {
                    toaster.pop('success', 'Encaminhamento finalizado com sucesso.');
                    $rootScope.$emit('updateEncaminhamentos');
                };
                var errorCallback = function() {
                    toaster.pop('error', 'Falha ao finalizar o encaminhamento.');
                    $rootScope.$emit('updateEncaminhamentos');
                };

                var finalizarTarefa = function() {
                    EncaminhamentoProposicaoHttp.finalizar(encaminhamento).then(successCallback, errorCallback);
                };

                if(!encaminhamento.descricaoComentario){
                    $confirm({text: 'Deseja fechar o encaminhamento sem comentário?', title: 'Finalização de encaminhamento', ok: 'Sim', cancel: 'Não'})
                        .then(finalizarTarefa);
                }else{
                    finalizarTarefa();
                }

            };

			$scope.update = function() {
				$scope.encaminhamentoProposicao.proposicao = new ProposicaoResource();
				$scope.encaminhamentoProposicao.proposicao.id = $scope.proposicao.id;

				var successCallback = function() {
					EncaminhamentoProposicaoResource.findByProposicao({
						ProposicaoId : $scope.proposicao.id
					}, function(data) {
						$scope.proposicao.listaEncaminhamentoProposicao = data;
						$scope.encaminhamentoProposicao = new EncaminhamentoProposicaoResource();
						$scope.tipoEncaminhamento = new TipoEncaminhamentoResource();
						toaster.pop('success', 'Encaminhamento atualizado com sucesso');
					});
				};
				var errorCallback = function() {
					$scope.encaminhamentoProposicao = new EncaminhamentoProposicaoResource();
					toaster.pop('error', 'Falha ao realizar operação.');
				};
				$scope.encaminhamentoProposicao.$update({
					EncaminhamentoProposicaoId : $scope.encaminhamentoProposicao.id
				}, successCallback, errorCallback);
			};

			$scope.save = function() {

				$scope.encaminhamentoProposicao.proposicao = new ProposicaoResource();
				$scope.encaminhamentoProposicao.proposicao.id = $scope.proposicao.id;
				if ($scope.encaminhamentoProposicao.dataHoraLimite != null) {
					$scope.encaminhamentoProposicao.dataHoraLimite = $scope.encaminhamentoProposicao.dataHoraLimite
							.getTime();
				}

				var successCallback = function(data, responseHeaders) {
					EncaminhamentoProposicaoResource.findByProposicao({
						ProposicaoId : $scope.proposicao.id
					}, function(data) {
						$scope.proposicao.listaEncaminhamentoProposicao = data;
						$scope.proposicao.totalEncaminhamentos++;
						$scope.encaminhamentoProposicao = new EncaminhamentoProposicaoResource();
						$scope.tipoEncaminhamento = new TipoEncaminhamentoResource();
						$rootScope.$emit('updateEncaminhamentos');
						toaster.pop('success', 'Encaminhamento inserido com sucesso');
					});
				};
				var errorCallback = function() {
					toaster.pop('error', 'Falha ao realizar operação.');
				};
				EncaminhamentoProposicaoResource.save($scope.encaminhamentoProposicao, successCallback, errorCallback);
			};

			// CALENDARIO
			$scope.setCalendar = function() {
				$scope.openCalendar = function($event) {
					$event.preventDefault();
					$event.stopPropagation();

					$scope.opened = true;
				};

				$scope.dateOptions = {
					formatYear : 'yy',
					startingDay : 1
				};

				$scope.format = 'dd/MM/yyyy';
			}

			$scope.setCalendar();

		});
<|endoftext|>