<commit_before>(function () {
  "use strict";

  var _ = require('lodash');
  var debugModule;
  try {
    debugModule = require('debug');
  } catch( e ) {
    // debug module not found, ignore and use a no-op
    debugModule = function(name) { return function() {}; };
  }
  var debug = {
      main: debugModule('pg-spice'),
      parsed: debugModule('pg-spice:parsed'),
      params: debugModule('pg-spice:params'),
      sql: debugModule('pg-spice:sql')
  };

  var defaults = {
    enableParseCache: true,
    allowMultipleParamTypes: false,
    trimDebugSql: process.env.PG_SPICE_TRIM_DEBUG_SQL === 'true'
  };
  var globals = {
    isPatched: false,
    options: defaults
  };
  var parseCache = {};

  var PARAMETER_SEPARATORS = ['"', '\'', ':', '&', ',', ';', '(', ')', '|', '=', '+', '-', '*', '%', '/', '\\', '<', '>', '^'];
  var SKIPS = [{start: "'", stop: "'"},
               {start: "\"", stop: "\""},
               {start: "--", stop: "\n"},
               {start: "/*", stop: "*/"}];
  var START_SKIP = ["'", "\"", "--", "/*"];
  var STOP_SKIP  = ["'", "\"", "\n", "*/"];

  function skipCommentsAndQuotes(sql, position) {
    var i, j, m, n, match, offset, endMatch, endPos;
    for(i=0;i<START_SKIP.length;i++) {
      if( sql[position] == START_SKIP[i][0] ) {
        match = true;
        for(j=1;j<START_SKIP[i].length;j++) {
          if( sql[position+j] != START_SKIP[i][j] ) {
            match = false;
            break;
          }
        }
        if( match ) {
          offset = START_SKIP[i].length;
          for(m=position+offset;m<sql.length;m++) {
            if( sql[m] == STOP_SKIP[i][0] ) {
              endMatch = true;
              endPos = m;
              for(n=1;n<STOP_SKIP[i].length;n++) {
                if( (m+n) >= sql.length ) {
                  // multi char skip not properly closed
                  return sql.length;
                }
                if( sql[m+n] != STOP_SKIP[i][n] ) {
                  endMatch = false;
                  break;
                }
                endPos = m + n;
              }
              if( endMatch ) {
                return endPos + 1;
              }
            }
          }
          // comment or qutoe not closed properly
          return sql.length;
        }
      }
    }
    return position;
  }

  function isParamSeparator(c) {
    if( /\s/.test(c) ) {
      return true;
    }
    for(var i=0;i<PARAMETER_SEPARATORS.length;i++) {
      if( PARAMETER_SEPARATORS[i] == c ) {
        return true;
      }
    }
    return false;
  }

  function parseSql(stmt) {
    var ret;
    if( globals.options.enableParseCache ) {
      ret = parseCache[stmt];
      if( ret ) {
        return ret;
      }
    }
    ret = _parseSql(stmt);
    if( globals.options.enableParseCache ) {
      parseCache[stmt] = ret;
    }
    return ret;
  }

  /**
   * Parses sql for named parameters
   *
   * Returns a list of named parameters found in the sql
   *   sql - the parsed sql with parameters replaced with $X placeholders
   *   originalSql - the original sql passed in as a parameter
   *   params[] - list of parsed parameters
   *
   * Each entry of params[] has the following properties:
   *   name - the name of the parameter
   *   indexes[] - the list of indexes, one-orgin, of the parameter
   */
  function _parseSql(stmt) {
    var params = [];
    var i = 0, j;
    if( !_.isString(stmt) ) {
      throw new Error("stmt argument must be a string, given: " + typeof(stmt));
    }
    while( i < stmt.length ) {
      var skipToPosition = i;
      while( i < stmt.length ) {
        skipToPosition = skipCommentsAndQuotes(stmt, i);
        if( i == skipToPosition ) {
          break;
        } else {
          i = skipToPosition;
        }
      }
      if( i>= stmt.length ) {
        break;
      }
      var c = stmt[i];
      if( c == ':' || c == '&' || c == '$' ) {
        j = i + 1;
        if( j < stmt.length && c == ':' && stmt[j] == ':' ) {
          // Postgres-style "::" cast (skip)
          i = i + 2;
          continue;
        }
        if( j < stmt.length && c == ':' && stmt[j] == '{' ) {
          // :{foobar} style parameter
          while( j < stmt.length && '}' != stmt[j] ) {
            j++;
            if( ':' == stmt[j] || '{' == stmt[j] ) {
              throw new Error("Parameter name contains invalid character '" +
                     stmt[j] +
                     "' at position " + i + " in statement " + stmt);
            }
          }
          if( j >= stmt.length ) {
            throw new Error("Non-terminated named parameter declaration" +
                   " at position " + i + " in statement " + stmt);
          }
          if( (j-i) > 3 ) {
            params.push({
              name: stmt.substring(i+2, j),
              start: i,
              end: j+1,
              type: ':{}'
            });
          }
          j++;
        } else {
          // :foobar or $foobar style parameter
          while( j < stmt.length && !isParamSeparator(stmt[j]) ) {
            j++;
          }
          if( (j-i) > 1 ) {
           params.push({
              name: stmt.substring(i+1, j),
              start: i,
              end: j,
              type: stmt[i]
            });
          }
        }
        i = j - 1;
      } else {
        if( c == '\\' ) {
          j = i + 1;
          if( j < stmt.length && stmt[j] == ':' ) {
            // escaped ":" (skip)
            i = i + 2;
            continue;
          }
        }
        if( c == '?' ) {
          // unamed param?
        }
        if( c == '$' ) {
          // unamed param?
        }
      }
      i++;
    }
    var ret = {
      "sql": stmt,
      "originalSql": stmt,
      "params": [],
      "numParams": params.length,
      "numDistinctParams": 0
    };
    var param;
    var namedParam;
    var paramTypes = {};
    var namedParams = {};
    for(i=0;i<params.length;i++) {
      param = params[i];
      paramTypes[param.type] = (paramTypes[param.type] || 0) + 1;
      if( /[0-9]+/.test(param.name) ) {
        throw new Error("You cannot mix named and numbered parameters." +
            " Check parameter '" + param.name + "' at position " + param.start +
            " in statement: " + stmt);
      }
      namedParam = namedParams[param.name];
      if( !namedParam ) {
        // increment before we use it so it's 1-origin
        ret.numDistinctParams++;
        namedParam = {
          // :foo
          "name": param.name,
          // the $N order it appears in the sql
          "index": ret.numDistinctParams,
          // all the $N spots replaced that it appears
          "indexes": []
        };
        namedParams[param.name] = namedParam;
        // Add them in order of appearance
        ret.params.push(namedParam);
      }
      namedParam.indexes.push(i+1);
    }

    if( !globals.options.allowMultipleParamTypes ) {
      if( _.size(_.keys(paramTypes)) > 1 ) {
        throw new Error("You cannot mix multiple types of named parameters in statement: " + stmt);
      }
    }

    // Loop backwards so the start/end stay accurrate:
    for(i=params.length-1;i>=0;i--) {
      param = params[i];
      namedParam = namedParams[param.name];
      // "SELECT :foo FROM bar" ==> "SELECT " + $1 + " FROM bar"
      ret.sql = ret.sql.substring(0,param.start) +
                "$" + namedParam.index +
                ret.sql.substring(param.end);
    }
    return ret;
  }

  /**
   * Converts parameter values from object to an array. Parameter value
   * indexes come from the parsedSql object and a given parameter may
   * appear in multiple positions.
   */
  function convertParamValues(parsedSql, values) {
    var ret = [];
    _.each(parsedSql.params, function(param) {
      if( !_.has(values, param.name) ) {
        throw new Error("No value found for parameter: " + param.name);
      }
      ret.push(values[param.name]);
    });
    return ret;
  }

  function filterDebugSQL(sql) {
    if( globals.options.trimDebugSql ) {
      sql = sql || "";
      return sql.replaceAll(/\W+/g, " ");
    }
    return sql;
  }

  function patch(pg, options) {
    if( globals.isPatched ) {
      debug.main('Already patched, skipping');
      return;
    }
    globals.isPatched = true;
    globals.options = _.defaults(options || {}, defaults);
    debug.main('Patching pg module with options:', globals.options);

    // Add named parameter support to Client.query:
    var origQuery = pg.Client.prototype.query;
    pg.Client.prototype.query = function(config, values, callback) {
      var sql;
      if( _.isString(config) ) {
        sql = config;
      } else if( _.isObject(config) && _.has(config, 'text') ) {
        sql = config.text;
      }
      if( sql ) {
        debug.sql(filterDebugSql(sql));
      }
      if( arguments.length === 3 && !_.isArray(values) && _.isObject(values) ) {
        try {
          if( !sql ) {
            throw new Error("First parameter of query() must be a string or config object with a name property");
          }
          var parsedSql = parseSql(sql);
          debug.main("parsed sql:", filterDebugSql(parsedSql));
          var params = convertParamValues(parsedSql, values);
          debug.main("parsed params:", params);
          return origQuery.apply(this, [parsedSql.sql, params, callback]);
        } catch( err ) {
          if( callback ) {
            return callback(err);
          } else {
            return;
          }
        }
      }
      return origQuery.apply(this, arguments);
    };
  }

  module.exports = {
    "patch": patch,
    // For testing:
    "parseSql": parseSql,
    "convertParamValues": convertParamValues
  };
})();
<commit_msg>Fix case for filterDebugSQL call<commit_after>(function () {
  "use strict";

  var _ = require('lodash');
  var debugModule;
  try {
    debugModule = require('debug');
  } catch( e ) {
    // debug module not found, ignore and use a no-op
    debugModule = function(name) { return function() {}; };
  }
  var debug = {
      main: debugModule('pg-spice'),
      parsed: debugModule('pg-spice:parsed'),
      params: debugModule('pg-spice:params'),
      sql: debugModule('pg-spice:sql')
  };

  var defaults = {
    enableParseCache: true,
    allowMultipleParamTypes: false,
    trimDebugSql: process.env.PG_SPICE_TRIM_DEBUG_SQL === 'true'
  };
  var globals = {
    isPatched: false,
    options: defaults
  };
  var parseCache = {};

  var PARAMETER_SEPARATORS = ['"', '\'', ':', '&', ',', ';', '(', ')', '|', '=', '+', '-', '*', '%', '/', '\\', '<', '>', '^'];
  var SKIPS = [{start: "'", stop: "'"},
               {start: "\"", stop: "\""},
               {start: "--", stop: "\n"},
               {start: "/*", stop: "*/"}];
  var START_SKIP = ["'", "\"", "--", "/*"];
  var STOP_SKIP  = ["'", "\"", "\n", "*/"];

  function skipCommentsAndQuotes(sql, position) {
    var i, j, m, n, match, offset, endMatch, endPos;
    for(i=0;i<START_SKIP.length;i++) {
      if( sql[position] == START_SKIP[i][0] ) {
        match = true;
        for(j=1;j<START_SKIP[i].length;j++) {
          if( sql[position+j] != START_SKIP[i][j] ) {
            match = false;
            break;
          }
        }
        if( match ) {
          offset = START_SKIP[i].length;
          for(m=position+offset;m<sql.length;m++) {
            if( sql[m] == STOP_SKIP[i][0] ) {
              endMatch = true;
              endPos = m;
              for(n=1;n<STOP_SKIP[i].length;n++) {
                if( (m+n) >= sql.length ) {
                  // multi char skip not properly closed
                  return sql.length;
                }
                if( sql[m+n] != STOP_SKIP[i][n] ) {
                  endMatch = false;
                  break;
                }
                endPos = m + n;
              }
              if( endMatch ) {
                return endPos + 1;
              }
            }
          }
          // comment or qutoe not closed properly
          return sql.length;
        }
      }
    }
    return position;
  }

  function isParamSeparator(c) {
    if( /\s/.test(c) ) {
      return true;
    }
    for(var i=0;i<PARAMETER_SEPARATORS.length;i++) {
      if( PARAMETER_SEPARATORS[i] == c ) {
        return true;
      }
    }
    return false;
  }

  function parseSql(stmt) {
    var ret;
    if( globals.options.enableParseCache ) {
      ret = parseCache[stmt];
      if( ret ) {
        return ret;
      }
    }
    ret = _parseSql(stmt);
    if( globals.options.enableParseCache ) {
      parseCache[stmt] = ret;
    }
    return ret;
  }

  /**
   * Parses sql for named parameters
   *
   * Returns a list of named parameters found in the sql
   *   sql - the parsed sql with parameters replaced with $X placeholders
   *   originalSql - the original sql passed in as a parameter
   *   params[] - list of parsed parameters
   *
   * Each entry of params[] has the following properties:
   *   name - the name of the parameter
   *   indexes[] - the list of indexes, one-orgin, of the parameter
   */
  function _parseSql(stmt) {
    var params = [];
    var i = 0, j;
    if( !_.isString(stmt) ) {
      throw new Error("stmt argument must be a string, given: " + typeof(stmt));
    }
    while( i < stmt.length ) {
      var skipToPosition = i;
      while( i < stmt.length ) {
        skipToPosition = skipCommentsAndQuotes(stmt, i);
        if( i == skipToPosition ) {
          break;
        } else {
          i = skipToPosition;
        }
      }
      if( i>= stmt.length ) {
        break;
      }
      var c = stmt[i];
      if( c == ':' || c == '&' || c == '$' ) {
        j = i + 1;
        if( j < stmt.length && c == ':' && stmt[j] == ':' ) {
          // Postgres-style "::" cast (skip)
          i = i + 2;
          continue;
        }
        if( j < stmt.length && c == ':' && stmt[j] == '{' ) {
          // :{foobar} style parameter
          while( j < stmt.length && '}' != stmt[j] ) {
            j++;
            if( ':' == stmt[j] || '{' == stmt[j] ) {
              throw new Error("Parameter name contains invalid character '" +
                     stmt[j] +
                     "' at position " + i + " in statement " + stmt);
            }
          }
          if( j >= stmt.length ) {
            throw new Error("Non-terminated named parameter declaration" +
                   " at position " + i + " in statement " + stmt);
          }
          if( (j-i) > 3 ) {
            params.push({
              name: stmt.substring(i+2, j),
              start: i,
              end: j+1,
              type: ':{}'
            });
          }
          j++;
        } else {
          // :foobar or $foobar style parameter
          while( j < stmt.length && !isParamSeparator(stmt[j]) ) {
            j++;
          }
          if( (j-i) > 1 ) {
           params.push({
              name: stmt.substring(i+1, j),
              start: i,
              end: j,
              type: stmt[i]
            });
          }
        }
        i = j - 1;
      } else {
        if( c == '\\' ) {
          j = i + 1;
          if( j < stmt.length && stmt[j] == ':' ) {
            // escaped ":" (skip)
            i = i + 2;
            continue;
          }
        }
        if( c == '?' ) {
          // unamed param?
        }
        if( c == '$' ) {
          // unamed param?
        }
      }
      i++;
    }
    var ret = {
      "sql": stmt,
      "originalSql": stmt,
      "params": [],
      "numParams": params.length,
      "numDistinctParams": 0
    };
    var param;
    var namedParam;
    var paramTypes = {};
    var namedParams = {};
    for(i=0;i<params.length;i++) {
      param = params[i];
      paramTypes[param.type] = (paramTypes[param.type] || 0) + 1;
      if( /[0-9]+/.test(param.name) ) {
        throw new Error("You cannot mix named and numbered parameters." +
            " Check parameter '" + param.name + "' at position " + param.start +
            " in statement: " + stmt);
      }
      namedParam = namedParams[param.name];
      if( !namedParam ) {
        // increment before we use it so it's 1-origin
        ret.numDistinctParams++;
        namedParam = {
          // :foo
          "name": param.name,
          // the $N order it appears in the sql
          "index": ret.numDistinctParams,
          // all the $N spots replaced that it appears
          "indexes": []
        };
        namedParams[param.name] = namedParam;
        // Add them in order of appearance
        ret.params.push(namedParam);
      }
      namedParam.indexes.push(i+1);
    }

    if( !globals.options.allowMultipleParamTypes ) {
      if( _.size(_.keys(paramTypes)) > 1 ) {
        throw new Error("You cannot mix multiple types of named parameters in statement: " + stmt);
      }
    }

    // Loop backwards so the start/end stay accurrate:
    for(i=params.length-1;i>=0;i--) {
      param = params[i];
      namedParam = namedParams[param.name];
      // "SELECT :foo FROM bar" ==> "SELECT " + $1 + " FROM bar"
      ret.sql = ret.sql.substring(0,param.start) +
                "$" + namedParam.index +
                ret.sql.substring(param.end);
    }
    return ret;
  }

  /**
   * Converts parameter values from object to an array. Parameter value
   * indexes come from the parsedSql object and a given parameter may
   * appear in multiple positions.
   */
  function convertParamValues(parsedSql, values) {
    var ret = [];
    _.each(parsedSql.params, function(param) {
      if( !_.has(values, param.name) ) {
        throw new Error("No value found for parameter: " + param.name);
      }
      ret.push(values[param.name]);
    });
    return ret;
  }

  function filterDebugSQL(sql) {
    if( globals.options.trimDebugSql ) {
      sql = sql || "";
      return sql.replaceAll(/\W+/g, " ");
    }
    return sql;
  }

  function patch(pg, options) {
    if( globals.isPatched ) {
      debug.main('Already patched, skipping');
      return;
    }
    globals.isPatched = true;
    globals.options = _.defaults(options || {}, defaults);
    debug.main('Patching pg module with options:', globals.options);

    // Add named parameter support to Client.query:
    var origQuery = pg.Client.prototype.query;
    pg.Client.prototype.query = function(config, values, callback) {
      var sql;
      if( _.isString(config) ) {
        sql = config;
      } else if( _.isObject(config) && _.has(config, 'text') ) {
        sql = config.text;
      }
      if( sql ) {
        debug.sql(filterDebugSQL(sql));
      }
      if( arguments.length === 3 && !_.isArray(values) && _.isObject(values) ) {
        try {
          if( !sql ) {
            throw new Error("First parameter of query() must be a string or config object with a name property");
          }
          var parsedSql = parseSql(sql);
          debug.main("parsed sql:", filterDebugSQL(parsedSql));
          var params = convertParamValues(parsedSql, values);
          debug.main("parsed params:", params);
          return origQuery.apply(this, [parsedSql.sql, params, callback]);
        } catch( err ) {
          if( callback ) {
            return callback(err);
          } else {
            return;
          }
        }
      }
      return origQuery.apply(this, arguments);
    };
  }

  module.exports = {
    "patch": patch,
    // For testing:
    "parseSql": parseSql,
    "convertParamValues": convertParamValues
  };
})();
<|endoftext|>


<commit_before>// /index.js
/*jslint node: true */
'use strict';

var fs = require('fs'),
  express = require('express'),
  multer  = require('multer'),
  _ = require('underscore'),
  storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, 'uploads');
    },
    filename: function (req, file, cb) {
      console.log(file);
      var fileData = 'data/images.json',
        filename = file.fieldname + '-' + Date.now() + '.' + _.last(file.originalname.split('.'));
      fs.readFile(fileData, 'utf8', function (err, data) {
        if (err) {
          data = {
            images: []
          }
        } else {
          data = JSON.parse(data);
        }
        data.images.push(filename);
        console.log(data);
        fs.writeFile(fileData, JSON.stringify(data), function (err) {
          if (err) {
            throw err;
          }
          console.log('It\'s saved!');
          cb(null, filename);
        });
      });

    }
  }),
  upload = multer({ storage: storage }),
  app = express();

app.post('/send-image', upload.single('image'), function (req, res, next) {
  res.redirect('/');
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
});

app.use(express.static('public'));
app.use(express.static('data'));
app.use(express.static('uploads'));

app.listen(3000);<commit_msg>get images<commit_after>// /index.js
/*jslint node: true */
'use strict';

var fs = require('fs'),
  express = require('express'),
  multer  = require('multer'),
  _ = require('underscore'),
  storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, 'uploads');
    },
    filename: function (req, file, cb) {
      console.log(file);
      var fileData = 'data/images.json',
        filename = file.fieldname + '-' + Date.now() + '.' + _.last(file.originalname.split('.'));
      fs.readFile(fileData, 'utf8', function (err, data) {
        if (err) {
          data = {
            images: []
          }
        } else {
          data = JSON.parse(data);
        }
        data.images.push(filename);
        console.log(data);
        fs.writeFile(fileData, JSON.stringify(data), function (err) {
          if (err) {
            throw err;
          }
          console.log('It\'s saved!');
          cb(null, filename);
        });
      });

    }
  }),
  upload = multer({ storage: storage }),
  app = express();

app.post('/send-image', upload.single('image'), function (req, res, next) {
  res.redirect('/');
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
});

app.use(express.static('public'));
app.use(express.static('data'));
app.use(express.static('uploads'));

app.get('/images/:size/:image', function (req, res, next) {
  var size = req.param('size'),
    image = req.param('image');
  console.log('although this matches');
  next();
});

app.listen(3000);<|endoftext|>


<commit_before>if (typeof phantom === "undefined") {
  spawn = require("child_process").spawn

  n = function(a,b,c,d) {
    for(b in a) {
      for(c=a=0;d=b.charCodeAt(c++);a%=934)a+=c*d;
      n[(a+360).toString(36)]=b
    }
  }

  module.exports = function(code, objs, cb) {
    var args = [__filename].concat(objs)
      , phantom = spawn("phantomjs", args, {cwd: __dirname})
      , data = ""

    objs
      .slice(0).reverse()
      .forEach(function(scope) {
        code = "n(" + scope + ");" + code
      })

    phantom.stdout.on("data", function(chunk){ data += chunk })
    phantom.stderr.on('data', function(chunk){ cb(chunk); phantom.kill() })

    phantom.on("exit", function(){
      JSON.parse(data).forEach(n)

      for (var key in n) code = code
        .replace(RegExp("\\." + n[key] + "\\b", "g"), "[n." + key + "]")
        .replace(RegExp("'"   + n[key] + "'"  , "g"), "n."  + key      )
        .replace(RegExp('"'   + n[key] + '"'  , "g"), "n."  + key      )

      code = "n=function(a,b,c,d){for(b in a){for(c=a=0;d=b.charCodeAt(c++);a%=934)a+=c*d;n[(a+360).toString(36)]=b}};" + code

      cb(null, code)
    })
  }
}

else {
  var args = phantom.args
    .map(eval)
    .map(function(obj) {
      var key, keys = {}
      for (key in obj) keys[key] = true
      return keys
    })

  console.log(JSON.stringify(args))

  phantom.exit()
}<commit_msg>toString for use with buffers<commit_after>if (typeof phantom === "undefined") {
  spawn = require("child_process").spawn

  n = function(a,b,c,d) {
    for(b in a) {
      for(c=a=0;d=b.charCodeAt(c++);a%=934)a+=c*d;
      n[(a+360).toString(36)]=b
    }
  }

  module.exports = function(code, objs, cb) {
    var args = [__filename].concat(objs)
      , phantom = spawn("phantomjs", args, {cwd: __dirname})
      , data = ""

    code = code.toString()

    objs
      .slice(0).reverse()
      .forEach(function(scope) {
        code = "n(" + scope + ");" + code
      })

    phantom.stdout.on("data", function(chunk){ data += chunk })
    phantom.stderr.on('data', function(chunk){ cb(chunk); phantom.kill() })

    phantom.on("exit", function(){
      JSON.parse(data).forEach(n)

      for (var key in n) code = code
        .replace(RegExp("\\." + n[key] + "\\b", "g"), "[n." + key + "]")
        .replace(RegExp("'"   + n[key] + "'"  , "g"), "n."  + key      )
        .replace(RegExp('"'   + n[key] + '"'  , "g"), "n."  + key      )

      code = "n=function(a,b,c,d){for(b in a){for(c=a=0;d=b.charCodeAt(c++);a%=934)a+=c*d;n[(a+360).toString(36)]=b}};" + code

      cb(null, code)
    })
  }
}

else {
  var args = phantom.args
    .map(eval)
    .map(function(obj) {
      var key, keys = {}
      for (key in obj) keys[key] = true
      return keys
    })

  console.log(JSON.stringify(args))

  phantom.exit()
}<|endoftext|>


<commit_before>'use strict';
const app = require('app');
const BrowserWindow = require('browser-window');
const path = require('path')
const fs = require('fs')

// report crashes to the Electron project
require('crash-reporter').start();

// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();

// WHITELABELING OPTIONS
var options = {
	page_title: 'Aufbau' // What do you want to display in the menu bar?
}

function createMainWindow () {
	const win = new BrowserWindow({
		width: 1280,
		height: 768,
		resizable: true,
		title: options.page_title
	});

	// Set the download directory to being off of the user's home folder
	var tilde_downloads = path.join(app.getHomeDir(), 'Downloads')
	win.webContents.session.setDownloadPath(tilde_downloads)

	// Whenever we finish loading a page, inject some javascript into it to add our back button
	// Don't do this if we're on the main page, though
	win.webContents.on('did-finish-load', function (webContents) {
		var page_title = webContents.sender.getTitle()
		var index_path
		var home_btn_css
		var home_btn_js
		if (page_title != 'Aufbau home') {
			// Add css
			home_btn_css = fs.readFileSync(path.join(__dirname, 'home-btn.css'), 'utf-8')
			webContents.sender.insertCSS(home_btn_css)

			// Add home button
			index_path = path.join(__dirname, 'www', 'index.html')
			home_btn_js = fs.readFileSync(path.join(__dirname, 'home-btn.jst'), 'utf-8').replace('{{index_path}}', index_path)
			webContents.sender.executeJavaScript(home_btn_js)
		}
	})

	win.loadUrl(`file://${__dirname}/www/index.html`);
	win.on('closed', onClosed);

	return win;
}

function onClosed() {
	// deref the window
	// for multiple windows store them in an array
	mainWindow = null;
}

// prevent window being GC'd
let mainWindow;

app.on('window-all-closed', function () {
	if (process.platform !== 'darwin') {
		app.quit();
	}
});

app.on('activate-with-no-open-windows', function () {
	if (!mainWindow) {
		mainWindow = createMainWindow();
	}
});

app.on('ready', function () {
	var Menu = require('menu');
	var menu_template = require('./menus.js')(BrowserWindow)
	var menu = Menu.buildFromTemplate(menu_template);
	Menu.setApplicationMenu(menu);

	mainWindow = createMainWindow();
});
<commit_msg>remove ;<commit_after>'use strict'
const app = require('app')
const BrowserWindow = require('browser-window')
const path = require('path')
const fs = require('fs')

// report crashes to the Electron project
require('crash-reporter').start()

// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')()

// WHITELABELING OPTIONS
var options = {
	page_title: 'Aufbau' // What do you want to display in the menu bar?
}

function createMainWindow () {
	const win = new BrowserWindow({
		width: 1280,
		height: 768,
		resizable: true,
		title: options.page_title
	})

	// Set the download directory to being off of the user's home folder
	var tilde_downloads = path.join(app.getHomeDir(), 'Downloads')
	win.webContents.session.setDownloadPath(tilde_downloads)

	// Whenever we finish loading a page, inject some javascript into it to add our back button
	// Don't do this if we're on the main page, though
	win.webContents.on('did-finish-load', function (webContents) {
		var page_title = webContents.sender.getTitle()
		var index_path
		var home_btn_css
		var home_btn_js
		if (page_title != 'Aufbau home') {
			// Add css
			home_btn_css = fs.readFileSync(path.join(__dirname, 'home-btn.css'), 'utf-8')
			webContents.sender.insertCSS(home_btn_css)

			// Add home button
			index_path = path.join(__dirname, 'www', 'index.html')
			home_btn_js = fs.readFileSync(path.join(__dirname, 'home-btn.jst'), 'utf-8').replace('{{index_path}}', index_path)
			webContents.sender.executeJavaScript(home_btn_js)
		}
	})

	win.loadUrl(`file://${__dirname}/www/index.html`)
	win.on('closed', onClosed)

	return win
}

function onClosed() {
	// deref the window
	// for multiple windows store them in an array
	mainWindow = null
}

// prevent window being GC'd
let mainWindow

app.on('window-all-closed', function () {
	if (process.platform !== 'darwin') {
		app.quit()
	}
})

app.on('activate-with-no-open-windows', function () {
	if (!mainWindow) {
		mainWindow = createMainWindow()
	}
})

app.on('ready', function () {
	var Menu = require('menu')
	var menu_template = require('./menus.js')(BrowserWindow)
	var menu = Menu.buildFromTemplate(menu_template)
	Menu.setApplicationMenu(menu)

	mainWindow = createMainWindow()
})
<|endoftext|>


<commit_before>var Heap = require('heap')
var ndarray = require('ndarray')
var vec3 = require('gl-vec3')
var vec4 = require('gl-vec4')
var normals = require('normals').faceNormals
var ops = require('ndarray-ops')
var solve = require('ndarray-linear-solve')
var removeOrphans = require('remove-orphan-vertices')

module.exports = function(positions, cells, faceNormals, threshold) {
  if (!threshold) {
    threshold = 0;
  }

  if (!faceNormals) {
    faceNormals = normals(cells, positions);
  }

  var n = positions.length;
  var vertices = positions.map(function(p, i) {
    return {
      position: p,
      index: i,
      pairs: [],
      error: null
    }
  });

  cells.map(function(cell) {
    for (var i = 0; i < 2; i++) {
      var j = (i + 1) % 3;
      var v1 = cell[i];
      var v2 = cell[j];
      // consistent ordering to prevent double entries
      if (v1 < v2) {
        vertices[v1].pairs.push(v2);
      } else {
        vertices[v2].pairs.push(v1);
      }
    }
  });

  if (threshold > 0) {
    for (var i = 0; i < n; i++) {
      for (var j = i - 1; j >= 0; j--) {
        if (vec3.distance(cells[i], cells[j]) < threshold) {
          if (i < j) {
            vertices[i].pairs.push(vertices[j]);
          } else {
            vertices[j].pairs.push(vertices[i]);
          }
        }
      }
    }
  }

  cells.map(function(cell, cellId) {
    var normal = faceNormals[cellId];
    // [a, b, c, d] where plane is defined by a*x+by+cz+d=0
    // choose the first vertex WLOG
    var pointOnTri = positions[cell[0]];
    var plane = [normal[0], normal[1], normal[2], -vec3.dot(normal, pointOnTri)];

    cell.map(function(vertexId) {
      var errorQuadric = ndarray(new Float32Array(4 * 4), [4, 4]);
      for (var i = 0; i < 4; i++) {
        for (var j = i; j >= 0; j--) {
          var value = plane[i] * plane[j];
          errorQuadric.set(i, j, value);
          if (i != j) {
            errorQuadric.set(j, i, value);
          }
        }
      }

      if (vertices[vertexId].error) {
        var existingQuadric = vertices[vertexId].error;
        ops.add(existingQuadric, existingQuadric, errorQuadric);
        vertices[vertexId].error = existingQuadric;
      } else {
        vertices[vertexId].error = errorQuadric;
      }
    })
  });

  function vertexError(vertex, quadratic) {
    var xformed = new Array(4);
    vec4.transformMat4(xformed, vertex, quadratic);
    return vec4.dot(vertex, xformed);
  };

  function optimalPosition(v1, v2) {
    var q1 = v1.error;
    var q2 = v2.error;
    var costMatrix = ndarray(new Float32Array(4 * 4), [4, 4]);
    ops.add(costMatrix, q1, q2);
    var mat4Cost = Array.from(costMatrix.data);
    var optimal = ndarray(new Float32Array(4));
    var toInvert = costMatrix;
    toInvert.set(0, 3, 0);
    toInvert.set(1, 3, 0);
    toInvert.set(2, 3, 0);
    toInvert.set(3, 3, 1);
    var solved = solve(optimal, toInvert, ndarray([0, 0, 0, 1]));

    if (!solved) {
      var v1Homogenous = Array.from(v1.position);
      v1Homogenous.push(1);
      var v2Homogenous = Array.from(v2.position);
      v2Homogenous.push(1);
      var midpoint = vec3.add(new Array(3), v1.position, v2.position);
      vec3.scale(midpoint, midpoint, 0.5);
      midpoint.push(1);
      var v1Error = vertexError(v1Homogenous, mat4Cost);
      var v2Error = vertexError(v2Homogenous, mat4Cost);
      var midpointError = vertexError(midpoint, mat4Cost);
      var minimum = Math.min([v1Error, v2Error, midpointError]);
      if (v1Error == minimum) {
        optimal = v1Homogenous;
      } else if (v2Error == minimum) {
        optimal = v2Homogenous;
      } else {
        optimal = midpoint;
      }
    } else {
      optimal = optimal.data;
    }

    var error = vertexError(optimal, mat4Cost);
    return {vertex: optimal.slice(0, 3), error: error};
  };

  var costs = new Heap(function(a, b) {
    return a.cost - b.cost;
  });

  var edges = []
  vertices.map(function(v1) {
    v1.pairs.map(function(v2Index) {
      var v2 = vertices[v2Index];
      var optimal = optimalPosition(v1, v2);

      var edge = {
        pair: [v1.index, v2Index],
        cost: optimal.error,
        optimalPosition: optimal.vertex
      };

      costs.push(edge);
      // to update costs
      edges.push(edge);
    });
  });

  return function(targetCount) {
    var n = positions.length;
    var newCells = Array.from(cells);
    var deletedCount = 0;

    while (n - deletedCount > targetCount) {
      var leastCost = costs.pop();
      var i1 = leastCost.pair[0];
      var i2 = leastCost.pair[1];
      if (i1 == i2) {
        // edge has already been collapsed
        continue;
      }
      vertices[i1].position = leastCost.optimalPosition;

      for (var i = newCells.length - 1; i >= 0; i--) {
        var cell = newCells[i];
        if (cell.indexOf(i2) != -1) {
          if (cell.indexOf(i1) != -1) {
            // Delete cells with zero area, as v1 == v2 now
            newCells.splice(i, 1);
          }

          cell[cell.indexOf(i2)] = i1;
        }
      }

      var v1 = vertices[i1];
      edges.map(function(edge) {
        if (edge.pair.indexOf(i1) != -1 && edge.pair.indexOf(i2) != -1) {
          edge.pair[edge.pair.indexOf(i2)] = i1;
          return;
        }

        if (edge.pair.indexOf(i1) != -1) {
          var optimal = optimalPosition(v1, vertices[(edge.pair.indexOf(i2) + 1) % 2]);
          edge.optimalPosition = optimal.vertex;
          edge.cost = optimal.error;
        }

        if (edge.pair.indexOf(i2) != -1) {
          // use v1 as that is the new position of v2
          var optimal = optimalPosition(v1, vertices[(edge.pair.indexOf(i2) + 1) % 2]);
          edge.pair[edge.pair.indexOf(i2)] = i1;
          edge.optimalPosition = optimal.vertex;
          edge.cost = optimal.error;
        }
      });

      costs.heapify();
      deletedCount++;
    }

    return removeOrphans(newCells, vertices.map(p => p.position));
  };
}
<commit_msg>Fix indexing-into-wrong-array issue. Should fix https://github.com/ataber/mesh-simplify/issues/2<commit_after>var Heap = require('heap')
var ndarray = require('ndarray')
var vec3 = require('gl-vec3')
var vec4 = require('gl-vec4')
var normals = require('normals').faceNormals
var ops = require('ndarray-ops')
var solve = require('ndarray-linear-solve')
var removeOrphans = require('remove-orphan-vertices')

module.exports = function(positions, cells, faceNormals, threshold) {
  if (!threshold) {
    threshold = 0;
  }

  if (!faceNormals) {
    faceNormals = normals(cells, positions);
  }

  var n = positions.length;
  var vertices = positions.map(function(p, i) {
    return {
      position: p,
      index: i,
      pairs: [],
      error: null
    }
  });

  cells.map(function(cell) {
    for (var i = 0; i < 2; i++) {
      var j = (i + 1) % 3;
      var v1 = cell[i];
      var v2 = cell[j];
      // consistent ordering to prevent double entries
      if (v1 < v2) {
        vertices[v1].pairs.push(v2);
      } else {
        vertices[v2].pairs.push(v1);
      }
    }
  });

  if (threshold > 0) {
    for (var i = 0; i < n; i++) {
      for (var j = i - 1; j >= 0; j--) {
        if (vec3.distance(cells[i], cells[j]) < threshold) {
          if (i < j) {
            vertices[i].pairs.push(vertices[j]);
          } else {
            vertices[j].pairs.push(vertices[i]);
          }
        }
      }
    }
  }

  cells.map(function(cell, cellId) {
    var normal = faceNormals[cellId];
    // [a, b, c, d] where plane is defined by a*x+by+cz+d=0
    // choose the first vertex WLOG
    var pointOnTri = positions[cell[0]];
    var plane = [normal[0], normal[1], normal[2], -vec3.dot(normal, pointOnTri)];

    cell.map(function(vertexId) {
      var errorQuadric = ndarray(new Float32Array(4 * 4), [4, 4]);
      for (var i = 0; i < 4; i++) {
        for (var j = i; j >= 0; j--) {
          var value = plane[i] * plane[j];
          errorQuadric.set(i, j, value);
          if (i != j) {
            errorQuadric.set(j, i, value);
          }
        }
      }

      if (vertices[vertexId].error) {
        var existingQuadric = vertices[vertexId].error;
        ops.add(existingQuadric, existingQuadric, errorQuadric);
        vertices[vertexId].error = existingQuadric;
      } else {
        vertices[vertexId].error = errorQuadric;
      }
    })
  });

  function vertexError(vertex, quadratic) {
    var xformed = new Array(4);
    vec4.transformMat4(xformed, vertex, quadratic);
    return vec4.dot(vertex, xformed);
  };

  function optimalPosition(v1, v2) {
    var q1 = v1.error;
    var q2 = v2.error;
    var costMatrix = ndarray(new Float32Array(4 * 4), [4, 4]);
    ops.add(costMatrix, q1, q2);
    var mat4Cost = Array.from(costMatrix.data);
    var optimal = ndarray(new Float32Array(4));
    var toInvert = costMatrix;
    toInvert.set(0, 3, 0);
    toInvert.set(1, 3, 0);
    toInvert.set(2, 3, 0);
    toInvert.set(3, 3, 1);
    var solved = solve(optimal, toInvert, ndarray([0, 0, 0, 1]));

    if (!solved) {
      var v1Homogenous = Array.from(v1.position);
      v1Homogenous.push(1);
      var v2Homogenous = Array.from(v2.position);
      v2Homogenous.push(1);
      var midpoint = vec3.add(new Array(3), v1.position, v2.position);
      vec3.scale(midpoint, midpoint, 0.5);
      midpoint.push(1);
      var v1Error = vertexError(v1Homogenous, mat4Cost);
      var v2Error = vertexError(v2Homogenous, mat4Cost);
      var midpointError = vertexError(midpoint, mat4Cost);
      var minimum = Math.min([v1Error, v2Error, midpointError]);
      if (v1Error == minimum) {
        optimal = v1Homogenous;
      } else if (v2Error == minimum) {
        optimal = v2Homogenous;
      } else {
        optimal = midpoint;
      }
    } else {
      optimal = optimal.data;
    }

    var error = vertexError(optimal, mat4Cost);
    return {vertex: optimal.slice(0, 3), error: error};
  };

  var costs = new Heap(function(a, b) {
    return a.cost - b.cost;
  });

  var edges = []
  vertices.map(function(v1) {
    v1.pairs.map(function(v2Index) {
      var v2 = vertices[v2Index];
      var optimal = optimalPosition(v1, v2);

      var edge = {
        pair: [v1.index, v2Index],
        cost: optimal.error,
        optimalPosition: optimal.vertex
      };

      costs.push(edge);
      // to update costs
      edges.push(edge);
    });
  });

  return function(targetCount) {
    var n = positions.length;
    var newCells = Array.from(cells);
    var deletedCount = 0;

    while (n - deletedCount > targetCount) {
      var leastCost = costs.pop();
      var i1 = leastCost.pair[0];
      var i2 = leastCost.pair[1];
      if (i1 == i2) {
        // edge has already been collapsed
        continue;
      }
      vertices[i1].position = leastCost.optimalPosition;

      for (var i = newCells.length - 1; i >= 0; i--) {
        var cell = newCells[i];
        if (cell.indexOf(i2) != -1) {
          if (cell.indexOf(i1) != -1) {
            // Delete cells with zero area, as v1 == v2 now
            newCells.splice(i, 1);
          }

          cell[cell.indexOf(i2)] = i1;
        }
      }

      var v1 = vertices[i1];
      edges.map(function(edge, i) {
        var edgeIndex1 = edge.pair.indexOf(i1);
        var edgeIndex2 = edge.pair.indexOf(i2);

        if (edgeIndex1 != -1 && edgeIndex2 != -1) {
          edge.pair[edgeIndex2] = i1;
          return;
        }

        if (edge.pair.indexOf(i1) != -1) {
          var optimal = optimalPosition(v1, vertices[edge.pair[(edgeIndex1 + 1) % 2]]);
          edge.optimalPosition = optimal.vertex;
          edge.cost = optimal.error;
        }

        if (edge.pair.indexOf(i2) != -1) {
          // use v1 as that is the new position of v2
          var optimal = optimalPosition(v1, vertices[edge.pair[(edgeIndex2 + 1) % 2]]);
          edge.pair[edgeIndex2] = i1;
          edge.optimalPosition = optimal.vertex;
          edge.cost = optimal.error;
        }
      });

      costs.heapify();
      deletedCount++;
    }

    return removeOrphans(newCells, vertices.map(p => p.position));
  };
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var json2xml = require('json2xml');
var xml2json = require('xml2json');
var client = require('request');

module.exports = MyVirtualMerchant;

function MyVirtualMerchant(options) {
  this.merchant_id = options.merchant_id;
  this.user_id = options.user_id;
  this.ssl_pin = options.ssl_pin;
  this.test_mode = options.test_mode || false;
  this.endpoints = this.resolveEndpoints();
}

MyVirtualMerchant.prototype.resolveEndpoints = function () {
  return (this.test_mode) ? {
    process: 'https://demo.myvirtualmerchant.com/VirtualMerchantDemo/process.do',
    process_batch: 'https://demo.myvirtualmerchant.com/VirtualMerchantDemo/processBatch.do',
    process_xml: 'https://demo.myvirtualmerchant.com/VirtualMerchantDemo/processxml.do',
    account_xml: 'https://demo.myvirtualmerchant.com/VirtualMerchantDemo/accountxml.do'
  } : {
    process: 'https://demo.myvirtualmerchant.com/VirtualMerchant/process.do',
    process_batch: 'https://demo.myvirtualmerchant.com/VirtualMerchant/processBatch.do',
    process_xml: 'https://demo.myvirtualmerchant.com/VirtualMerchant/processxml.do',
    account_xml: 'https://demo.myvirtualmerchant.com/VirtualMerchant/accountxml.do'
  };
};

MyVirtualMerchant.prototype.signRequest = function (request) {
  return _.extend(request, {
    ssl_merchant_id: this.merchant_id,
    ssl_user_id: this.user_id,
    ssl_pin: this.ssl_pin
  });
};

MyVirtualMerchant.prototype.processRequest = function (request, callback) {
  client.post(this.endpoints.process_xml, {
    form: {
      xmldata: json2xml({
        txn: this.signRequest(request)
      })
    }
  }, function (error, response, body) {
    try {
      var result = JSON.parse(xml2json.toJson(body)).txn;
      if (result.errorMessage)
        return callback && callback(result);
      return callback && callback(error, result);
    } catch (e) {
      return callback && callback(result);
    }
  });
};

MyVirtualMerchant.prototype.doPurchase = function (data, callback) {
  this.processRequest({
    ssl_transaction_type: 'ccsale',
    ssl_card_number: data.card_number,
    ssl_avs_address: 7300,
    ssl_avs_zip: 12345,
    ssl_exp_date: data.exp_date,
    ssl_cvv2cvc2: 123,
    ssl_amount: data.amount
  }, callback);
};

MyVirtualMerchant.prototype.doRefund = function (data, callback) {
  this.processRequest({
    ssl_transaction_type: 'ccreturn',
    ssl_txn_id: data.txn_id,
    ssl_amount: data.amount
  }, callback);
};

MyVirtualMerchant.prototype.doVoid = function (data, callback) {
  this.processRequest({
    ssl_transaction_type: 'ccvoid',
    ssl_txn_id: data.txn_id
  }, callback);
};
<commit_msg>Giving more details to the gateway during purchase transaction.<commit_after>'use strict';

var _ = require('lodash');
var json2xml = require('json2xml');
var xml2json = require('xml2json');
var client = require('request');

module.exports = MyVirtualMerchant;

function MyVirtualMerchant(options) {
  this.merchant_id = options.merchant_id;
  this.user_id = options.user_id;
  this.ssl_pin = options.ssl_pin;
  this.test_mode = options.test_mode || false;
  this.endpoints = this.resolveEndpoints();
}

MyVirtualMerchant.prototype.resolveEndpoints = function () {
  return (this.test_mode) ? {
    process: 'https://demo.myvirtualmerchant.com/VirtualMerchantDemo/process.do',
    process_batch: 'https://demo.myvirtualmerchant.com/VirtualMerchantDemo/processBatch.do',
    process_xml: 'https://demo.myvirtualmerchant.com/VirtualMerchantDemo/processxml.do',
    account_xml: 'https://demo.myvirtualmerchant.com/VirtualMerchantDemo/accountxml.do'
  } : {
    process: 'https://demo.myvirtualmerchant.com/VirtualMerchant/process.do',
    process_batch: 'https://demo.myvirtualmerchant.com/VirtualMerchant/processBatch.do',
    process_xml: 'https://demo.myvirtualmerchant.com/VirtualMerchant/processxml.do',
    account_xml: 'https://demo.myvirtualmerchant.com/VirtualMerchant/accountxml.do'
  };
};

MyVirtualMerchant.prototype.signRequest = function (request) {
  return _.extend(request, {
    ssl_merchant_id: this.merchant_id,
    ssl_user_id: this.user_id,
    ssl_pin: this.ssl_pin
  });
};

MyVirtualMerchant.prototype.processRequest = function (request, callback) {
  client.post(this.endpoints.process_xml, {
    form: {
      xmldata: json2xml({
        txn: this.signRequest(request)
      })
    }
  }, function (error, response, body) {
    try {
      var result = JSON.parse(xml2json.toJson(body)).txn;
      if (result.errorMessage)
        return callback && callback(result);
      return callback && callback(error, result);
    } catch (e) {
      return callback && callback(result);
    }
  });
};

MyVirtualMerchant.prototype.doPurchase = function (order, prospect, creditcard, callback) {
  this.processRequest({
    ssl_transaction_type: 'ccsale',
    ssl_card_number: creditcard.number.trim().replace(/ /g,''),
    ssl_exp_date: creditcard.expiration.split(' / ').join(''),
    ssl_cvv2cvc2_indicator: 1,
    ssl_customer_code: prospect.id,
    ssl_cvv2cvc2: creditcard.cvv2,
    ssl_verify: 'Y',
    ssl_amount: order.converted_amount,
    ssl_first_name: prospect.firstname,
    ssl_last_name: prospect.lastname,
    ssl_avs_address: prospect.billing.address,
    ssl_avs_zip: prospect.billing.zipcode,
    ssl_description: 'React CRM - Prospect #' + prospect.id + ' - Website:' //TODO
  }, callback);
};

MyVirtualMerchant.prototype.doRefund = function (data, callback) {
  this.processRequest({
    ssl_transaction_type: 'ccreturn',
    ssl_txn_id: data.txn_id,
    ssl_amount: data.amount
  }, callback);
};

MyVirtualMerchant.prototype.doVoid = function (data, callback) {
  this.processRequest({
    ssl_transaction_type: 'ccvoid',
    ssl_txn_id: data.txn_id
  }, callback);
};
<|endoftext|>


<commit_before>require('./lib/number');
require('./lib/string');
module.exports = require('./lib/type-info');

<commit_msg>+ Object, Boolean, Function Type<commit_after>require('./lib/number');
require('./lib/string');
require('./lib/object');
require('./lib/function');
require('./lib/boolean');
module.exports = require('./lib/type-info');

<|endoftext|>


<commit_before>const SerialPort = require("serialport");

class GQGeiger {
	constructor(port, baud){
		this.geigerPort = new SerialPort(port, {baudrate: baud});
		this.queue = [];
		this.geigerPort.on('data', function(data) {
			const cD = this.queue.shift();
			cD.internalCallback(externalCallback, data);
		});
	}

	processCPM(callback, buffer){
		cpm = buffer.readUInt16BE(0);
		callback(null, cpm);
	}
	getCPM(callback){
		this.geigerPort.write(new Buffer("<GETCPM>>", 'ascii'), function(err, results){
			if(err){
				callback(err, null);
				return;
			}
			this.queue.push({internalCallback: this.processCPM, externalCallback: callback});
		});
	}
}

module.exports = GQGeiger;<commit_msg>JavaScript scope is strange?<commit_after>const SerialPort = require("serialport");

class GQGeiger {
	constructor(port, baud){
		this.geigerPort = new SerialPort(port, {baudrate: baud});
		this.queue = [];
		const tempThis = this;
		this.geigerPort.on('data', function(data) {
			const cD = tempThis.queue.shift();
			cD.internalCallback(cD.externalCallback, data);
		});
	}

	processCPM(callback, buffer){
		const cpm = buffer.readUInt16BE(0);
		callback(null, cpm);
	}
	getCPM(callback){
		const tempThis = this;
		this.geigerPort.write(new Buffer("<GETCPM>>", 'ascii'), function(err, results){
			if(err){
				callback(err, null);
				return;
			}
			tempThis.queue.push({internalCallback: tempThis.processCPM, externalCallback: callback});
		});
	}
}

module.exports = GQGeiger;<|endoftext|>


<commit_before>#!/usr/bin/env node --harmony

var fs           = require('fs');
var program      = require('commander');
var readlineSync = require('readline-sync');

var appHubId;
var appHubSecret;
var buildFilename = 'AppHubBuild.zip';

program
  .version('1.0.0')
  .option('-c, --configure', 'Configure AppHub ID and Secret key')
  .parse(process.argv);

// If run without any .apphub file then run setup.
fs.readFile( './.apphub', function ( error, data ) {
  if (error) {
    if (error.code != 'ENOENT') {
      console.log('There was a problem with checking your .apphub file for credentials:');
      console.log(error.message);
      process.exit(1);
    }

    // If missing file, no problem, we'll kick off the Setup function to create it.
    setup();
  }
  else {
    // If .apphub exists, try and get values.
    appHubData = JSON.parse(data);

    console.log('.apphub file exists! Reading credentials.');

    appHubId     = appHubData.appHubId;
    appHubSecret = appHubData.appHubSecret;
  }

  build();
});

var setup = function() {

  appHubId     = readlineSync.question('AppHub App ID: ');
  appHubSecret = readlineSync.question('AppHub App Secret: ');

  console.log('');

  appHubCredentialsAsJSON = JSON.stringify( { "appHubId": appHubId, "appHubSecret": appHubSecret } );

  fs.writeFile( './.apphub', appHubCredentialsAsJSON, { mode: 0600 }, function (error) {
    if (error) {
      console.log('There was an error saving your AppHub config to file.');
      console.log(error.message);
      process.exit(1);
    }
  });

  console.log('AppHub configuration saved to .apphub for future deploys.');
  console.log('');
};

var build = function() {
  console.log('Building...');

  buildResult = require('child_process').execSync( './node_modules/.bin/apphub build --verbose -o ' + buildFilename ).toString();

  console.log(buildResult);
  console.log('');
  console.log('BUILD SUCCESSFUL!');
  console.log('');

  deploy();
};

var deploy = function() {
  console.log('Deploying...');
  console.log('');

  // var curl = require('curlrequest');

  // var curlOptions = {
  //   method: 'PUT',
  //   headers: {
  //     'X-AppHub-Application-ID': appHubId,
  //     'X-AppHub-Application-Secret': appHubSecret,
  //     'Content-Type': 'application/zip'
  //   },
  //   url: 'https://api.apphub.io/v1/upload',
  //   'upload-file': buildFilename,
  // };

  // curl.request( curlOptions, function (err, stdout, meta) {
  //   console.log('%s %s', meta.cmd, meta.args.join(' '));
  // });
  // curlCommand =  'curl -X PUT';
  // curlCommand += ' -H "X-AppHub-Application-ID: ' + appHubId + '"';
  // curlCommand += ' -H "X-AppHub-Application-Secret: ' + appHubSecret + '"';
  // curlCommand += ' -H "Content-Type: application/zip"';
  // curlCommand += ' -L https://api.apphub.io/v1/upload';
  // // curlCommand += ' --include'; // Includes the HTTP header in the output.
  // curlCommand += ' --verbose';
  // curlCommand += ' --upload-file ./' + buildFilename;
  // curlCommand += ' https://api.apphub.io/v1/upload';

  try {
    getUrlForPutCommand =  'curl -X GET';
    getUrlForPutCommand += ' -H "X-AppHub-Application-ID: ' + appHubId + '"';
    getUrlForPutCommand += ' -H "X-AppHub-Application-Secret: ' + appHubSecret + '"';
    getUrlForPutCommand += ' -H "Content-Type: application/zip"';
    getUrlForPutCommand += ' -L https://api.apphub.io/v1/upload';
    getUrlForPutCommand += ' | python -c \'import json,sys;obj=json.load(sys.stdin);print obj["data"]["s3_url"]\'';

    urlForPut = require('child_process').execSync( getUrlForPutCommand ).toString().trim();

    console.log('urlForPut:');
    console.log(urlForPut);

    putCommand  = 'curl -X PUT';
    putCommand += ' -H "Content-Type: application/zip"';
    putCommand += ' -L "' + urlForPut + '"';
    putCommand += ' --upload-file ' + buildFilename;

    console.log('putCommand:');
    console.log(putCommand);

    putResponse = require('child_process').execSync( putCommand ).toString().trim();

    console.log( putResponse );
    console.log('');
    console.log("DEPLOY SUCCESSFUL!");

    process.exit(0);
  }
  catch(error) {
    console.log('');
    console.log('There was a problem uploading the build:');
    console.log(error);

    process.exit(1);
  }

  // buildURL = 'https://dashboard.apphub.io/projects/' + appHubId;

  // console.log('Deployed Successfully to AppHub.');
  // console.log('You can view the build at ' + buildURL);

  //       process.exit(0);
  // request
  //   .put('https://api.apphub.io/v1/upload')
  //   .set('X-AppHub-Application-ID', appHubId)
  //   .set('X-AppHub-Application-Secret', appHubSecret)
  //   .set('Content-Type', 'application/zip')
  //   .attach('', buildFilename)
  //   .end(function (err, res) {
  //     console.log( res.req );

  //     if (!err && res.ok) {
  //       buildURL = 'https://dashboard.apphub.io/projects/' + appHubId;

  //       console.log('Deployed Successfully to AppHub.');
  //       console.log('You can view the build at ' + buildURL);

  //       process.exit(0);
  //     }

  //     var errorMessage;
  //     if (res && res.status === 401) {
  //       errorMessage = "Authentication failed! Bad username/password?";
  //     } else if (err) {
  //       errorMessage = err;
  //     } else {
  //       errorMessage = res.text;
  //     }
  //     console.error(errorMessage);
  //     process.exit(1);
  //   });
};
<commit_msg>Remove build file after successful deploy.<commit_after>#!/usr/bin/env node --harmony

var fs           = require('fs');
var path         = require('path');
var program      = require('commander');
var readlineSync = require('readline-sync');

var APP_HUB_ID;
var APP_HUB_SECRET;
var BUILD_FILE_NAME = 'AppHubBuild_' + Date.now() + '.zip';
var BUILD_FILE_PATH = path.resolve('./', BUILD_FILE_NAME);
var BUILD_URL_BASE  = 'https://dashboard.apphub.io/projects/';

program
  .version('1.0.0')
  .option('-c, --configure', 'Configure AppHub ID and Secret key')
  .parse(process.argv);

// If run without any .apphub file then run setup.
fs.readFile( './.apphub', function ( error, data ) {
  if (error) {
    if (error.code != 'ENOENT') {
      console.log('There was a problem with checking your .apphub file for credentials:');
      console.log(error.message);
      process.exit(1);
    }

    // If missing file, no problem, we'll kick off the Setup function to create it.
    setup();
  }
  else {
    // If .apphub exists, try and get values.
    appHubData = JSON.parse(data);

    console.log('.apphub file exists! Reading credentials.');

    APP_HUB_ID     = appHubData.appHubId;
    APP_HUB_SECRET = appHubData.appHubSecret;
  }

  build();
});

var setup = function() {

  APP_HUB_ID     = readlineSync.question('AppHub App ID: ');
  APP_HUB_SECRET = readlineSync.question('AppHub App Secret: ');

  console.log('');

  appHubCredentialsAsJSON = JSON.stringify( { "appHubId": APP_HUB_ID, "appHubSecret": APP_HUB_SECRET } );

  fs.writeFile( './.apphub', appHubCredentialsAsJSON, { mode: 0600 }, function (error) {
    if (error) {
      console.log('There was an error saving your AppHub config to file.');
      console.log(error.message);
      process.exit(1);
    }
  });

  console.log('AppHub configuration saved to .apphub for future deploys.');
  console.log('');
};

var build = function() {
  console.log('Building...');

  buildResult = require('child_process').execSync( './node_modules/.bin/apphub build --verbose -o ' + BUILD_FILE_NAME ).toString();

  console.log(buildResult);
  console.log('');
  console.log('BUILD SUCCESSFUL!');
  console.log('');

  deploy();
};

var deploy = function() {
  console.log('Deploying...');
  console.log('');

  // var curl = require('curlrequest');

  // var curlOptions = {
  //   method: 'PUT',
  //   headers: {
  //     'X-AppHub-Application-ID': APP_HUB_ID,
  //     'X-AppHub-Application-Secret': APP_HUB_SECRET,
  //     'Content-Type': 'application/zip'
  //   },
  //   url: 'https://api.apphub.io/v1/upload',
  //   'upload-file': BUILD_FILE_NAME,
  // };

  // curl.request( curlOptions, function (err, stdout, meta) {
  //   console.log('%s %s', meta.cmd, meta.args.join(' '));
  // });
  // curlCommand =  'curl -X PUT';
  // curlCommand += ' -H "X-AppHub-Application-ID: ' + APP_HUB_ID + '"';
  // curlCommand += ' -H "X-AppHub-Application-Secret: ' + APP_HUB_SECRET + '"';
  // curlCommand += ' -H "Content-Type: application/zip"';
  // curlCommand += ' -L https://api.apphub.io/v1/upload';
  // // curlCommand += ' --include'; // Includes the HTTP header in the output.
  // curlCommand += ' --verbose';
  // curlCommand += ' --upload-file ./' + BUILD_FILE_NAME;
  // curlCommand += ' https://api.apphub.io/v1/upload';

  try {
    getUrlForPutCommand =  'curl -X GET';
    getUrlForPutCommand += ' -H "X-AppHub-Application-ID: ' + APP_HUB_ID + '"';
    getUrlForPutCommand += ' -H "X-AppHub-Application-Secret: ' + APP_HUB_SECRET + '"';
    getUrlForPutCommand += ' -H "Content-Type: application/zip"';
    getUrlForPutCommand += ' -L https://api.apphub.io/v1/upload';
    getUrlForPutCommand += ' | python -c \'import json,sys;obj=json.load(sys.stdin);print obj["data"]["s3_url"]\'';

    urlForPut = require('child_process').execSync( getUrlForPutCommand ).toString().trim();

    console.log('urlForPut:');
    console.log(urlForPut);

    putCommand  = 'curl -X PUT';
    putCommand += ' -H "Content-Type: application/zip"';
    putCommand += ' -L "' + urlForPut + '"';
    putCommand += ' --upload-file ' + BUILD_FILE_NAME;

    console.log('putCommand:');
    console.log(putCommand);

    putResponse = require('child_process').execSync( putCommand ).toString().trim();

    console.log( putResponse );
    console.log('');
    console.log("DEPLOY SUCCESSFUL!");
  }
  catch(error) {
    console.log('');
    console.log('There was a problem uploading the build:');
    console.log(error);

    process.exit(1);
  }

  try {
    console.log('');
    console.log('Removing Build File...');
    console.log('');

    console.log('BUILD_FILE_PATH: ')
    console.log(BUILD_FILE_PATH);

    fs.unlinkSync(BUILD_FILE_PATH)

    console.log('BUILD FILE REMOVED!');
    console.log('');

  }
  catch(error) {
    console.log('');
    console.log('There was a problem removing the build file: ' + BUILD_FILE_PATH);
    console.log('');
    console.log(error);

    process.exit(1);
  }

  console.log('');
  console.log('SUCCESSFULLY BUILT AND DEPLOYED TO APPHUB!')
  console.log('');

  var buildURL = BUILD_URL_BASE + APP_HUB_ID;
  console.log('You can see your build here: ' + buildURL);

  console.log('');
  process.exit(0);

  // console.log('Deployed Successfully to AppHub.');
  // console.log('You can view the build at ' + buildURL);

  //       process.exit(0);
  // request
  //   .put('https://api.apphub.io/v1/upload')
  //   .set('X-AppHub-Application-ID', APP_HUB_ID)
  //   .set('X-AppHub-Application-Secret', APP_HUB_SECRET)
  //   .set('Content-Type', 'application/zip')
  //   .attach('', BUILD_FILE_NAME)
  //   .end(function (err, res) {
  //     console.log( res.req );

  //     if (!err && res.ok) {
  //       buildURL = 'https://dashboard.apphub.io/projects/' + APP_HUB_ID;

  //       console.log('Deployed Successfully to AppHub.');
  //       console.log('You can view the build at ' + buildURL);

  //       process.exit(0);
  //     }

  //     var errorMessage;
  //     if (res && res.status === 401) {
  //       errorMessage = "Authentication failed! Bad username/password?";
  //     } else if (err) {
  //       errorMessage = err;
  //     } else {
  //       errorMessage = res.text;
  //     }
  //     console.error(errorMessage);
  //     process.exit(1);
  //   });
};
<|endoftext|>


<commit_before>// get-schema by angleman, MIT
// Get Redshift / postgres schema for a table

function GetSchema(client) {
	self = this

	function query(tablename, fields, callback) {
		fields = (typeof fields == 'string') ? fields : fields.join(',')
		qry    = 'SELECT ' + fields + " FROM information_schema.columns WHERE table_name='" + tablename + "'"
		client.query(qry, callback)
	}

	self.get = function(tablename, callback) {
		function extractColumns(err, result) {
			if (result && result.rows) {
				rows = result.rows
				result = []
				for (i = 0; i < rows.length; i++) {
					row = rows[i]
					type = row['data_type']
					switch (type) {
					case 'character varying': type = 'varchar'; break
					case 'character':         type = 'char';    break
					case 'double precision':  type = 'float';   break
					default:
						type = row['data_type'].split(' ')[0]
					}
					json = '{"'+row['column_name'] + '": "' + type + '"}'
					row  = JSON.parse(json)
					result.push(row)
				}
			}
			callback(err, result)
		}
		query(tablename, 'column_name, data_type, character_maximum_length', extractColumns)
	}

	self.getCreateTypes = function(tablename, callback) {
		function extractColumns(err, result) {
			if (result && result.rows) {
				rows = result.rows
				result = []
				for (i = 0; i < rows.length; i++) {
					row = rows[i]
					type = row['data_type']
					switch (type) {
					case 'character varying': type = 'varchar(' + row['character_maximum_length'] + ')'; break
					case 'character':         type = 'char(' + row['character_maximum_length'] + ')';    break
					case 'double precision':  type = 'float';   break
					default:
						type = row['data_type'].split(' ')[0]
					}
					json = '{"'+row['column_name'] + '": "' + type + '"}'
					row  = JSON.parse(json)
					result.push(row)
				}
			}
			callback(err, result)
		}
		query(tablename, 'column_name, data_type, character_maximum_length', extractColumns)
	}

	self.getColumns = function(tablename, callback) {
		function extractColumns(err, result) {
			if (result && result.rows) {
				rows = result.rows
				result = []
				for (i = 0; i < rows.length; i++) {
					row = rows[i]
					result.push(row['column_name'])
				}
			}
			callback(err, result)
		}
		query(tablename, 'column_name', extractColumns)
	}

	return this
}

module.exports = GetSchema<commit_msg>fix self reference<commit_after>// get-schema by angleman, MIT
// Get Redshift / postgres schema for a table

function GetSchema(client) {
	self = this

	function query(tablename, fields, callback) {
		fields = (typeof fields == 'string') ? fields : fields.join(',')
		qry    = 'SELECT ' + fields + " FROM information_schema.columns WHERE table_name='" + tablename + "'"
		client.query(qry, callback)
	}

	self.get = function(tablename, callback) {
		function extractColumns(err, result) {
			if (result && result.rows) {
				rows = result.rows
				result = []
				for (i = 0; i < rows.length; i++) {
					row = rows[i]
					type = row['data_type']
					switch (type) {
					case 'character varying': type = 'varchar'; break
					case 'character':         type = 'char';    break
					case 'double precision':  type = 'float';   break
					default:
						type = row['data_type'].split(' ')[0]
					}
					json = '{"'+row['column_name'] + '": "' + type + '"}'
					row  = JSON.parse(json)
					result.push(row)
				}
			}
			callback(err, result)
		}
		query(tablename, 'column_name, data_type, character_maximum_length', extractColumns)
	}

	self.getCreateTypes = function(tablename, callback) {
		function extractColumns(err, result) {
			if (result && result.rows) {
				rows = result.rows
				result = []
				for (i = 0; i < rows.length; i++) {
					row = rows[i]
					type = row['data_type']
					switch (type) {
					case 'character varying': type = 'varchar(' + row['character_maximum_length'] + ')'; break
					case 'character':         type = 'char(' + row['character_maximum_length'] + ')';    break
					case 'double precision':  type = 'float';   break
					default:
						type = row['data_type'].split(' ')[0]
					}
					json = '{"'+row['column_name'] + '": "' + type + '"}'
					row  = JSON.parse(json)
					result.push(row)
				}
			}
			callback(err, result)
		}
		query(tablename, 'column_name, data_type, character_maximum_length', extractColumns)
	}

	self.getColumns = function(tablename, callback) {
		function extractColumns(err, result) {
			if (result && result.rows) {
				rows = result.rows
				result = []
				for (i = 0; i < rows.length; i++) {
					row = rows[i]
					result.push(row['column_name'])
				}
			}
			callback(err, result)
		}
		query(tablename, 'column_name', extractColumns)
	}

	return self
}

module.exports = GetSchema<|endoftext|>


<commit_before>/**
 * Based on Stylish reporter from Sindre Sorhus
 */
'use strict';

var chalk = require('chalk'),
  stripAnsi = require('strip-ansi'),
  table = require('text-table'),
  extend = require('extend');

var path = require('path');

var process = require('./process');
var minimist = require('minimist');
var clsc = require('coalescy');

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

/**
 * Given a word and a count, append an s if count is not one.
 * @param {string} word A word in its singular form.
 * @param {int} count A number controlling whether word should be pluralized.
 * @returns {string} The original word with an s on the end if count is not one.
 */
function pluralize(word, count) {
  return (count === 1 ? word : word + 's');
}

var parseBoolEnvVar = function(varName) {
  var env = process.env || { };
  return env[varName] === 'true';
};

var subtleLog = function(args) {
  return parseBoolEnvVar('EFF_NO_GRAY') ? args : chalk.gray(args);
};

var getEnvVar = function(varName) {
  var env = process.env || { };
  return env[varName] || false;
};

var getFileLink = function(_path, line, column) {
  var scheme = getEnvVar('EFF_EDITOR_SCHEME');
  if (scheme === false) {
    return false;
  }
  return scheme.replace('{file}', encodeURIComponent(_path)).replace('{line}', line).replace('{column}', column);
};

var getKeyLink = function(key) {
  var noLinkRules = parseBoolEnvVar('EFF_NO_LINK_RULES');
  var url = key.indexOf('/') > -1 ? 'https://google.com/#q=' : 'http://eslint.org/docs/rules/';
  return (!noLinkRules) ? chalk.underline(subtleLog(url + chalk.white(encodeURIComponent(key)))) : chalk.white(key);
};

var printSummary = function(hash, title, method) {
  var res = '\n\n' + chalk[method](title + ':\n');
  res += table(
    Object.keys(hash).sort(function(a, b) {
      return hash[a] > hash[b] ? -1 : 1;
    }).map(function(key) {
      return [
        '',
        hash[key],
        getKeyLink(key)
      ];
    }), {
      align: [
        '',
        'r',
        'l'
      ],
      stringLength: function(str) {
        return stripAnsi(str).length;
      }
    });
  return res;
};

//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------

module.exports = function(results) {

  var output = '\n',
    total = 0,
    errors = 0,
    warnings = 0,
    summaryColor = 'yellow';

  results = results || [];

  var entries = [];

  var absolutePathsToFile = parseBoolEnvVar('EFF_ABSOLUTE_PATHS');

  var restArgs = process.argv.slice(process.argv.indexOf('--') + 1);
  var parsedArgs = minimist(restArgs);

  var groupByIssue = parsedArgs['eff-by-issue'];
  var filterRule = parsedArgs['eff-filter'];

  absolutePathsToFile = clsc(parsedArgs['eff-absolute-paths'], absolutePathsToFile);

  var errorsHash = { };
  var warningsHash = { };

  results.forEach(function(result) {
    var messages = result.messages || [];
    entries = entries.concat(messages.map(function(message) {
      return extend({
        filePath: absolutePathsToFile ? path.resolve(result.filePath) : path.relative('.', result.filePath)
      }, message);
    }));
  });

  entries.sort(function(a, b) {
    if (a.severity > b.severity) {
      return 1;
    }
    if (a.severity < b.severity) {
      return -1;
    }

    if (groupByIssue) {
      if (a.ruleId > b.ruleId) {
        return 1;
      }
      if (a.ruleId < b.ruleId) {
        return -1;
      }
    }

    var pathSort = a.filePath.localeCompare(b.filePath);
    if (pathSort) {
      return pathSort;
    }

    if (a.line > b.line) {
      return 1;
    }
    if (a.line < b.line) {
      return -1;
    }

    if (a.column > b.column) {
      return 1;
    }
    if (a.column < b.column) {
      return -1;
    }

    return 0;
  });

  output += table(
        entries.reduce(function(seq, message) {
          var messageType;

          if (filterRule) {
            if (message.ruleId !== filterRule) {
              return seq;
            }
          }

          if (message.fatal || message.severity === 2) {
            messageType = chalk.red('✘');
            summaryColor = 'red';
            errorsHash[message.ruleId] = (errorsHash[message.ruleId] || 0) + 1;
            errors++;
          } else {
            messageType = chalk.yellow('⚠');
            warningsHash[message.ruleId] = (warningsHash[message.ruleId] || 0) + 1;
            warnings++;
          }

          var line = message.line || 0;
          var column = message.column || 0;

          var arrow = '';
          var hasSource = message.source !== undefined && message.source.length < 1000;
          if (hasSource) {
            for (var i = 0; i < message.column; i++) {
              if (message.source.charAt(i) === '\t') {
                arrow += '\t';
              } else {
                arrow += ' ';
              }
            }
            arrow += '^';
          }

          var filePath = message.filePath;
          var link = getFileLink(filePath, line, column);
          var filename = subtleLog(filePath + ':' + line + ':' + column);

          seq.push([
            '',
            messageType + '  ' + getKeyLink(message.ruleId || ''),
            message.message.replace(/\.$/, ''),
            '$MARKER$  ' + (link === false ? chalk.underline(filename) : filename) +
              (link === false ? '' : '$MARKER$  ' + chalk.underline(subtleLog(link))) + '$MARKER$  ' +
              (hasSource ? subtleLog(message.source) + '$MARKER$  ' + subtleLog(arrow) : '') + '$MARKER$'
          ]);
          return seq;
        }, []), {
          align: [
            '',
            'l',
            'l',
            'l'
          ],
          stringLength: function(str) {
            return stripAnsi(str).length;
          }
        }).replace(/\$MARKER\$/g, '\n') + '\n\n';

  total = entries.length;

  if (total > 0) {
    output += chalk[summaryColor].bold([
      '✘ ',
      total,
      pluralize(' problem', total),
      ' (',
      errors,
      pluralize(' error', errors),
      ', ',
      warnings,
      pluralize(' warning', warnings),
      ')\n'
    ].join(''));

    if (errors > 0) {
      output += printSummary(errorsHash, 'Errors', 'red');
    }

    if (warnings > 0) {
      output += printSummary(warningsHash, 'Warnings', 'yellow');
    }
  }

  if (process.env.FORCE_ITERM_HINT === 'true' || (process.stdout.isTTY && !process.env.CI)) {
    output = '\u001B]1337;CurrentDir=' + process.cwd() + '\u0007' + output;
  }

  return total > 0 ? output : '';
};
<commit_msg>Fix trailing color in new lines<commit_after>/**
 * Based on Stylish reporter from Sindre Sorhus
 */
'use strict';

var chalk = require('chalk'),
  stripAnsi = require('strip-ansi'),
  table = require('text-table'),
  extend = require('extend');

var path = require('path');

var process = require('./process');
var minimist = require('minimist');
var clsc = require('coalescy');

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

/**
 * Given a word and a count, append an s if count is not one.
 * @param {string} word A word in its singular form.
 * @param {int} count A number controlling whether word should be pluralized.
 * @returns {string} The original word with an s on the end if count is not one.
 */
function pluralize(word, count) {
  return (count === 1 ? word : word + 's');
}

var parseBoolEnvVar = function(varName) {
  var env = process.env || { };
  return env[varName] === 'true';
};

var subtleLog = function(args) {
  return parseBoolEnvVar('EFF_NO_GRAY') ? args : chalk.gray(args);
};

var getEnvVar = function(varName) {
  var env = process.env || { };
  return env[varName] || false;
};

var getFileLink = function(_path, line, column) {
  var scheme = getEnvVar('EFF_EDITOR_SCHEME');
  if (scheme === false) {
    return false;
  }
  return scheme.replace('{file}', encodeURIComponent(_path)).replace('{line}', line).replace('{column}', column);
};

var getKeyLink = function(key) {
  var noLinkRules = parseBoolEnvVar('EFF_NO_LINK_RULES');
  var url = key.indexOf('/') > -1 ? 'https://google.com/#q=' : 'http://eslint.org/docs/rules/';
  return (!noLinkRules) ? chalk.underline(subtleLog(url + chalk.white(encodeURIComponent(key)))) : chalk.white(key);
};

var printSummary = function(hash, title, method) {
  var res = '\n\n' + chalk[method](title + ':') + chalk.white('\n');
  res += table(
    Object.keys(hash).sort(function(a, b) {
      return hash[a] > hash[b] ? -1 : 1;
    }).map(function(key) {
      return [
        '',
        hash[key],
        getKeyLink(key)
      ];
    }), {
      align: [
        '',
        'r',
        'l'
      ],
      stringLength: function(str) {
        return stripAnsi(str).length;
      }
    });
  return res;
};

//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------

module.exports = function(results) {

  var output = '\n',
    total = 0,
    errors = 0,
    warnings = 0,
    summaryColor = 'yellow';

  results = results || [];

  var entries = [];

  var absolutePathsToFile = parseBoolEnvVar('EFF_ABSOLUTE_PATHS');

  var restArgs = process.argv.slice(process.argv.indexOf('--') + 1);
  var parsedArgs = minimist(restArgs);

  var groupByIssue = parsedArgs['eff-by-issue'];
  var filterRule = parsedArgs['eff-filter'];

  absolutePathsToFile = clsc(parsedArgs['eff-absolute-paths'], absolutePathsToFile);

  var errorsHash = { };
  var warningsHash = { };

  results.forEach(function(result) {
    var messages = result.messages || [];
    entries = entries.concat(messages.map(function(message) {
      return extend({
        filePath: absolutePathsToFile ? path.resolve(result.filePath) : path.relative('.', result.filePath)
      }, message);
    }));
  });

  entries.sort(function(a, b) {
    if (a.severity > b.severity) {
      return 1;
    }
    if (a.severity < b.severity) {
      return -1;
    }

    if (groupByIssue) {
      if (a.ruleId > b.ruleId) {
        return 1;
      }
      if (a.ruleId < b.ruleId) {
        return -1;
      }
    }

    var pathSort = a.filePath.localeCompare(b.filePath);
    if (pathSort) {
      return pathSort;
    }

    if (a.line > b.line) {
      return 1;
    }
    if (a.line < b.line) {
      return -1;
    }

    if (a.column > b.column) {
      return 1;
    }
    if (a.column < b.column) {
      return -1;
    }

    return 0;
  });

  output += table(
        entries.reduce(function(seq, message) {
          var messageType;

          if (filterRule) {
            if (message.ruleId !== filterRule) {
              return seq;
            }
          }

          if (message.fatal || message.severity === 2) {
            messageType = chalk.red('✘');
            summaryColor = 'red';
            errorsHash[message.ruleId] = (errorsHash[message.ruleId] || 0) + 1;
            errors++;
          } else {
            messageType = chalk.yellow('⚠');
            warningsHash[message.ruleId] = (warningsHash[message.ruleId] || 0) + 1;
            warnings++;
          }

          var line = message.line || 0;
          var column = message.column || 0;

          var arrow = '';
          var hasSource = message.source !== undefined && message.source.length < 1000;
          if (hasSource) {
            for (var i = 0; i < message.column; i++) {
              if (message.source.charAt(i) === '\t') {
                arrow += '\t';
              } else {
                arrow += ' ';
              }
            }
            arrow += '^';
          }

          var filePath = message.filePath;
          var link = getFileLink(filePath, line, column);
          var filename = subtleLog(filePath + ':' + line + ':' + column);

          seq.push([
            '',
            messageType + '  ' + getKeyLink(message.ruleId || ''),
            message.message.replace(/\.$/, ''),
            '$MARKER$  ' + (link === false ? chalk.underline(filename) : filename) +
              (link === false ? '' : '$MARKER$  ' + chalk.underline(subtleLog(link))) + '$MARKER$  ' +
              (hasSource ? subtleLog(message.source) + '$MARKER$  ' + subtleLog(arrow) : '') + '$MARKER$'
          ]);
          return seq;
        }, []), {
          align: [
            '',
            'l',
            'l',
            'l'
          ],
          stringLength: function(str) {
            return stripAnsi(str).length;
          }
        }).replace(/\$MARKER\$/g, '\n') + '\n\n';

  total = entries.length;

  if (total > 0) {
    output += chalk[summaryColor].bold([
      '✘ ',
      total,
      pluralize(' problem', total),
      ' (',
      errors,
      pluralize(' error', errors),
      ', ',
      warnings,
      pluralize(' warning', warnings),
      ')'
    ].join('')) + chalk.white('\n');

    if (errors > 0) {
      output += printSummary(errorsHash, 'Errors', 'red');
    }

    if (warnings > 0) {
      output += printSummary(warningsHash, 'Warnings', 'yellow');
    }
  }

  if (process.env.FORCE_ITERM_HINT === 'true' || (process.stdout.isTTY && !process.env.CI)) {
    output = '\u001B]1337;CurrentDir=' + process.cwd() + '\u0007' + output;
  }

  return total > 0 ? output : '';
};
<|endoftext|>


<commit_before>'use strict';
var WebSocket = require('ws');
var ProtoBuf = require('protobufjs');
var util = require('util');
var os = require('os');
var builder = ProtoBuf.loadProtoFile('./krpc.proto');
var proto = builder.build();

var sock = new WebSocket('ws://127.0.0.1:50000');
sock.binaryType = 'arraybuffer';

sock.onopen = () => {
    let clientName = "node-test";
    let clientId = new Buffer('1');
    let connectionRequest = new proto.krpc.schema.ConnectionRequest(clientName, clientId);
    sock.send(connectionRequest.toArrayBuffer());
};

sock.onmessage = messageReceived;

function messageReceived(event) {
    let resp;
    try {
        resp = proto.krpc.schema.Response.decode(event.data);
    }
    catch (err) {
        var parsedMessage;
        try {
            var buf = Buffer.from(event.data);
            parsedMessage = buf.toString('utf8');
        }
        catch (parsingError) {
            parsedMessage = "Error parsing binary data :" + parsingError;
        }
        throw new Error(util.format(err.message, os.EOL, parsedMessage));

    }
    console.log(resp);
}
<commit_msg>trying various approaches.<commit_after>'use strict';
var WebSocket = require('ws');
var ProtoBuf = require('protobufjs');
var util = require('util');
var os = require('os');
var builder = ProtoBuf.loadProtoFile('./krpc.proto');
var proto = builder.build();
var socket = new WebSocket('ws://127.0.0.1:50000');
socket.binaryType = 'arraybuffer';
var rpcHelloMessage = new Buffer('KRPC-RPC');

socket.onopen = connectionOpened;
function connectionOpened() {
    //getStatus(); // Error: Illegal wire type for unknown field 7 in Message .krpc.schema.Response#decode: 7
    //sendHello(); // messageReceived never gets called

    //sendConnectionRequest();
    /*
     Error: Illegal offset: 0 <= 757 (+1) <= 757
     Error receiving message
     Service node-test not found
     at KRPC.Service.Services.GetProcedureSignature (System.String service, System.String procedure) [0x00000] in <filename unknown>:0
     at KRPC.Server.ProtocolBuffers.MessageExtensions.ToMessage (KRPC.Schema.KRPC.Request request) [0x00000] in <filename unknown>:0
     at KRPC.Server.WebSockets.RPCStream.Read (KRPC.Service.Messages.Request& request, System.Byte[] data, Int32 offset, Int32 length) [0x00000] in <filename unknown>:0
     at KRPC.Server.Message.RPCStream.Poll () [0x00000] in <filename unknown>:0
     at KRPC.Server.Message.RPCStream.get_DataAvailable () [0x00000] in <filename unknown>:0
     at KRPC.Core.PollRequests (IList`1 yieldedContinuations) [0x00000] in <filename unknown>:0
     at WebSocket.messageReceived (C:\Development\krpc-node\index.js:49:15)
     at WebSocket.onMessage (C:\Development\krpc-node\node_modules\ws\lib\WebSocket.js:442:14)
     at emitTwo (events.js:106:13)
     at WebSocket.emit (events.js:191:7)
     at Receiver.onbinary (C:\Development\krpc-node\node_modules\ws\lib\WebSocket.js:848:10)
     at C:\Development\krpc-node\node_modules\ws\lib\Receiver.js:628:18
     at Receiver.applyExtensions (C:\Development\krpc-node\node_modules\ws\lib\Receiver.js:371:5)
     at C:\Development\krpc-node\node_modules\ws\lib\Receiver.js:604:14
     at Receiver.flush (C:\Development\krpc-node\node_modules\ws\lib\Receiver.js:347:3)
     at Receiver.finish (C:\Development\krpc-node\node_modules\ws\lib\Receiver.js:633:12)
     */

    //getServices();
    /*
     Error: Illegal wire type for unknown field 28636 in Message .krpc.schema.Response#decode: 6
     ��
     �{
     UI�
     AddCanvasdUICanvas"�<doc>
     <summary>
     Add a new canvas.
     </summary>
     <remarks>
     If you want to add UI elements to KSPs stock UI canvas, use <see cref="M:UI.StockCanvas" />.
     </remarks>
     </doc>�
     Message
     content
     duration
     */

    //getClients();
    /*
     Error: Illegal wire type for unknown field 4 in Message .krpc.schema.Response#decode: 6
     &$
     "
     3-n��X7I��R�J�R

     */

    //getCurrentGameScene();
    /*
     Error: Illegal offset: 0 <= 4 (+1) <= 4

     at WebSocket.messageReceived (C:\Development\krpc-node\index.js:115:15)
     at WebSocket.onMessage (C:\Development\krpc-node\node_modules\ws\lib\WebSocket.js:442:14)
     at emitTwo (events.js:106:13)
     at WebSocket.emit (events.js:191:7)
     at Receiver.onbinary (C:\Development\krpc-node\node_modules\ws\lib\WebSocket.js:848:10)
     at C:\Development\krpc-node\node_modules\ws\lib\Receiver.js:628:18
     at Receiver.applyExtensions (C:\Development\krpc-node\node_modules\ws\lib\Receiver.js:371:5)
     at C:\Development\krpc-node\node_modules\ws\lib\Receiver.js:604:14
     at Receiver.flush (C:\Development\krpc-node\node_modules\ws\lib\Receiver.js:347:3)
     at Receiver.finish (C:\Development\krpc-node\node_modules\ws\lib\Receiver.js:633:12)
     */
    getStatus();
}

function sendHello() {
    socket.send(toArrayBuffer(rpcHelloMessage));
}

function sendConnectionRequest() {
    let clientName = "node-test";
    let connectionRequest = new proto.krpc.schema.ConnectionRequest(clientName);
    socket.send(connectionRequest.toArrayBuffer());
}
function getStatus() {
    let req = new proto.krpc.schema.Request('KRPC', 'GetStatus');
    socket.send(req.toArrayBuffer());
}

function getServices() {
    let req = new proto.krpc.schema.Request('KRPC', 'GetServices');
    socket.send(req.toArrayBuffer());
}

function getClients() {
    let req = new proto.krpc.schema.Request('KRPC', 'get_Clients');
    socket.send(req.toArrayBuffer());
}

function getCurrentGameScene() {
    let req = new proto.krpc.schema.Request('KRPC', 'get_CurrentGameScene');
    socket.send(req.toArrayBuffer());
}

socket.onmessage = messageReceived;

function messageReceived(event) {
    let resp;
    try {
        resp = proto.krpc.schema.Response.decode(event.data);
    }
    catch (err) {
        var parsedMessage;
        try {
            var buf = Buffer.from(event.data);
            parsedMessage = buf.toString('utf8');
        }
        catch (parsingError) {
            parsedMessage = "Error parsing binary data :" + parsingError;
        }
        throw new Error(util.format(err.message, os.EOL, parsedMessage));
    }
    console.log(resp);
}

function toArrayBuffer(buf) {
    var ab = new ArrayBuffer(buf.length);
    var view = new Uint8Array(ab);
    for (var i = 0; i < buf.length; ++i) {
        view[i] = buf[i];
    }
    return ab;
}

function toBuffer(ab) {
    var buf = new Buffer(ab.byteLength);
    var view = new Uint8Array(ab);
    for (var i = 0; i < buf.length; ++i) {
        buf[i] = view[i];
    }
    return buf;
}<|endoftext|>