<commit_before>'use babel';
'use strict';

var fs = require('fs');
var path = require('path');
var XRegExp = require('xregexp').XRegExp;
var GoogleAnalytics = require('./google-analytics');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var _ = require('lodash');

module.exports = (function () {

  function ErrorMatcher() {
    this.regex = null;
    this.cwd = null;
    this.stdout = null;
    this.stderr = null;
    this.currentMatch = [];
    this.firstMatchId = null;

    atom.commands.add('atom-workspace', 'build:error-match', this.match.bind(this));
    atom.commands.add('atom-workspace', 'build:error-match-first', this.matchFirst.bind(this));
  }

  util.inherits(ErrorMatcher, EventEmitter);

  ErrorMatcher.prototype._gotoNext = function () {
    if (0 === this.currentMatch.length) {
      return;
    }

    this._goto(this.currentMatch[0].id);
  };

  ErrorMatcher.prototype._goto = function (id) {
    var match = _.findWhere(this.currentMatch, { id: id });
    if (!match) {
      return this.emit('error', 'Can\'t find match with id ' + id);
    }

    // rotate to next match
    while (this.currentMatch[0] !== match) {
      this.currentMatch.push(this.currentMatch.shift());
    }
    this.currentMatch.push(this.currentMatch.shift());

    if (!match.file) {
      return this.emit('error', 'Did not match any file. Don\'t know what to open.');
    }

    if (!path.isAbsolute(match.file)) {
      match.file = this.cwd + path.sep + match.file;
    }

    var row = match.line ? match.line - 1 : 0; /* Because atom is zero-based */
    var col =  match.col ? match.col - 1 : 0; /* Because atom is zero-based */

    fs.exists(match.file, function (exists) {
      if (!exists) {
        return this.emit('error', 'Matched file does not exist: ' + match.file);
      }
      atom.workspace.open(match.file, {
        initialLine: row,
        initialColumn: col,
        searchAllPanes: true
      });
      this.emit('scroll', match.type, match.id);
    }.bind(this));
  };

  ErrorMatcher.prototype._parse = function () {
    this.currentMatch = [];
    var matchFunction = function (match, i) {
      match.type = 'error';
      match.id = 'error-' + regexIndex + '-' + i;
      this.push(match);
    };
    for (var regexIndex in this.regex) {
      XRegExp.forEach(this.output, this.regex[regexIndex], matchFunction, this.currentMatch);
    }

    this.currentMatch.sort(function(a, b) {
      return a.index - b.index;
    });

    this.firstMatchId = (this.currentMatch.length > 0) ? this.currentMatch[0].id : null;

    var output = '';
    var lastEnd = 0;
    for (var matchIndex in this.currentMatch) {
      var match = this.currentMatch[matchIndex];

      if (match.index < lastEnd) {
        // overlapping matches, only highlight first
        continue;
      }

      output += _.escape(this.output.substr(lastEnd, match.index - lastEnd));
      output += util.format('%s', match.type, match.id, _.escape(match[0]));
      lastEnd = match.index + match[0].length;
    }
    output += _.escape(this.output.substr(lastEnd));

    this.emit('replace', output, this._goto.bind(this));
  };

  ErrorMatcher.prototype.set = function (regex, cwd, output) {
    if (!regex) {
      regex = [];
    }
    regex = (regex instanceof Array) ? regex : [ regex ];

    this.regex = _.compact(regex.map(function(r) {
      try {
        return XRegExp(r);
      } catch (err) {
        this.emit('error', 'Error parsing regex. ' + err.message);
        return null;
      }
    }.bind(this)));

    this.cwd = cwd;
    this.output = output;
    this.currentMatch = [];

    this._parse();
  };

  ErrorMatcher.prototype.match = function () {
    GoogleAnalytics.sendEvent('errorMatch', 'match');

    this._gotoNext();
  };

  ErrorMatcher.prototype.matchFirst = function () {
    GoogleAnalytics.sendEvent('errorMatch', 'first');

    if (this.firstMatchId) {
      this._goto(this.firstMatchId);
    }
  };

  return ErrorMatcher;
})();
<commit_msg>ErrorMatcher: Defensive array loops<commit_after>'use babel';
'use strict';

var fs = require('fs');
var path = require('path');
var XRegExp = require('xregexp').XRegExp;
var GoogleAnalytics = require('./google-analytics');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var _ = require('lodash');

module.exports = (function () {

  function ErrorMatcher() {
    this.regex = null;
    this.cwd = null;
    this.stdout = null;
    this.stderr = null;
    this.currentMatch = [];
    this.firstMatchId = null;

    atom.commands.add('atom-workspace', 'build:error-match', this.match.bind(this));
    atom.commands.add('atom-workspace', 'build:error-match-first', this.matchFirst.bind(this));
  }

  util.inherits(ErrorMatcher, EventEmitter);

  ErrorMatcher.prototype._gotoNext = function () {
    if (0 === this.currentMatch.length) {
      return;
    }

    this._goto(this.currentMatch[0].id);
  };

  ErrorMatcher.prototype._goto = function (id) {
    var match = _.findWhere(this.currentMatch, { id: id });
    if (!match) {
      return this.emit('error', 'Can\'t find match with id ' + id);
    }

    // rotate to next match
    while (this.currentMatch[0] !== match) {
      this.currentMatch.push(this.currentMatch.shift());
    }
    this.currentMatch.push(this.currentMatch.shift());

    if (!match.file) {
      return this.emit('error', 'Did not match any file. Don\'t know what to open.');
    }

    if (!path.isAbsolute(match.file)) {
      match.file = this.cwd + path.sep + match.file;
    }

    var row = match.line ? match.line - 1 : 0; /* Because atom is zero-based */
    var col =  match.col ? match.col - 1 : 0; /* Because atom is zero-based */

    fs.exists(match.file, function (exists) {
      if (!exists) {
        return this.emit('error', 'Matched file does not exist: ' + match.file);
      }
      atom.workspace.open(match.file, {
        initialLine: row,
        initialColumn: col,
        searchAllPanes: true
      });
      this.emit('scroll', match.type, match.id);
    }.bind(this));
  };

  ErrorMatcher.prototype._parse = function () {
    this.currentMatch = [];
    var self = this;
    var matchFunction = function (match, i, string, regex) {
      match.type = 'error';
      match.id = 'error-' + self.regex.indexOf(regex) + '-' + i;
      this.push(match);
    };
    this.regex.forEach((regex) => {
      XRegExp.forEach(this.output, regex, matchFunction, this.currentMatch);
    });

    this.currentMatch.sort(function(a, b) {
      return a.index - b.index;
    });

    this.firstMatchId = (this.currentMatch.length > 0) ? this.currentMatch[0].id : null;

    var output = '';
    var lastEnd = 0;
    for (let match of this.currentMatch) {
      if (match.index < lastEnd) {
        // overlapping matches, only highlight first
        continue;
      }

      output += _.escape(this.output.substr(lastEnd, match.index - lastEnd));
      output += util.format('%s', match.type, match.id, _.escape(match[0]));
      lastEnd = match.index + match[0].length;
    }
    output += _.escape(this.output.substr(lastEnd));

    this.emit('replace', output, this._goto.bind(this));
  };

  ErrorMatcher.prototype.set = function (regex, cwd, output) {
    if (!regex) {
      regex = [];
    }
    regex = (regex instanceof Array) ? regex : [ regex ];

    this.regex = _.compact(regex.map(function(r) {
      try {
        return XRegExp(r);
      } catch (err) {
        this.emit('error', 'Error parsing regex. ' + err.message);
        return null;
      }
    }.bind(this)));

    this.cwd = cwd;
    this.output = output;
    this.currentMatch = [];

    this._parse();
  };

  ErrorMatcher.prototype.match = function () {
    GoogleAnalytics.sendEvent('errorMatch', 'match');

    this._gotoNext();
  };

  ErrorMatcher.prototype.matchFirst = function () {
    GoogleAnalytics.sendEvent('errorMatch', 'first');

    if (this.firstMatchId) {
      this._goto(this.firstMatchId);
    }
  };

  return ErrorMatcher;
})();
<|endoftext|>


<commit_before>var fs = require("fs")

function most_wanted(size,templates,threshold_percentage){
    var total_count = 0;
    var res = [];
    for(var j = 0; j < templates.length; j++){
        total_count += templates[j].count;
    }
    for(var j = 0; j < templates.length; j++){
        if(((templates[j].count*100)/total_count) > threshold_percentage){
            res.push(templates[j]);
            console.log(templates[j].count+' --- '+templates[j].template_str);
        }
    }
    return res;
}

module.exports = function(size,templates,use_fold){
    var suffix = '';
    if((use_fold != undefined) && (use_fold == 'fold')){
        suffix = '_f_';
    }
    else if((use_fold != undefined) && (use_fold == 'tfold')){
        suffix = '_tf_';
    }
    var filename = '../train/data'+suffix+size +'.txt';
    fs.exists(filename, function(exists) {
        if (exists) {
            fs.readFile(filename, function (err, data) {
                if (err) throw err;
                console.log(data.toString());
                var file_text = data.toString();
                var file_arr=file_text.split("\n");
                var s='';
                while((str = file_arr.pop()) != undefined){
                    var reg = /\d/;

                    if(reg.test(str[0])){
                        var sub_str = str.split(" --- ");
                        var template = {count: parseInt(sub_str[0]), template_str: sub_str[1]};
                        templates.push(template);
                        console.log(template.count);
                        console.log(template.template_str);
                    }
                }
            });
        } else {
            console.log('File "'+filename+'" not exist');
        }
    });

    return templates;
}
<commit_msg>no message<commit_after>var fs = require("fs")

function most_wanted(size,templates,threshold_percentage){
    var total_count = 0;
    var res = [];
    for(var j = 0; j < templates.length; j++){
        total_count += templates[j].count;
    }
    for(var j = 0; j < templates.length; j++){
        if(((templates[j].count*100)/total_count) > threshold_percentage){
            res.push(templates[j]);
            console.log(templates[j].count+' --- '+templates[j].template_str);
        }
    }
    return res;
}

module.exports = function(size,templates,use_fold){
    var suffix = '';
    if((use_fold != undefined) && (use_fold == 'fold')){
        suffix = '_f_';
    }
    else if((use_fold != undefined) && (use_fold == 'tfold')){
        suffix = '_tf_';
    }
    var filename = '../train/data'+suffix+size +'.txt';
    fs.exists(filename, function(exists) {
        if (exists) {
            fs.readFile(filename, function (err, data) {
                if (err) throw err;
                console.log(data.toString());
                var file_text = data.toString();
                var file_arr=file_text.split("\n");
                var s='';
                while((str = file_arr.pop()) != undefined){
                    var reg = /\d/;

                    if(reg.test(str[0])){
                        var sub_str = str.split(" --- ");
                        var temp_arr = sub_str[1].split(",");
                        var template = {count: parseInt(sub_str[0]), template_str: sub_str[1], template_arr: temp_arr };
                        templates.push(template);
                        console.log(template.count);
                        console.log(template.template_str);
                        console.log(template.template_arr);
                    }
                }
            });
        } else {
            console.log('File "'+filename+'" not exist');
        }
    });

    return templates;
}
<|endoftext|>


<commit_before>const fs        = require('fs');
const extractor = require('./extractor-composite');

function dep2linecolor(pDep) {
    if (pDep.coreModule){
        return "\"#999999\"";
    }

    return "black";
}

function toEntities(pDependencies) {
    return Object.keys(pDependencies).reduce(
        (pEntities, pDependency) => pEntities.concat(`\"${pDependency}\" [color=black, fontcolor=black]\n    `),
    "");
}

function renderEdgesForDependant(pDep, pDependencies) {
    return pDependencies[pDep].reduce(
        (pAll, pThing) =>
            pAll.concat(
                `\"${pDep}\" -> \"${pThing.resolved}\" [color=${dep2linecolor(pThing)}]\n    `
            ),
    "");
}

function toEdges(pDependencies) {
    return Object.keys(pDependencies).reduce(
        (pEdges, pDependency) =>
            pEdges.concat(`${renderEdgesForDependant(pDependency, pDependencies)}`),
    "");
}

function toDiGraph(pDependencies) {
    return `
digraph {
    ordering=out
    rankdir=LR
    splines=true
    overlap=false
    node [shape=box, style="rounded, filled",
          color="#999999", fillcolor="#ffffdd", fontcolor="#999999",
          fontname=Helvetica, fontsize=9]
    edge [color=black, arrowhead=vee, fontname="Helvetica", fontsize="9"]

    ${toEntities(pDependencies)}

    ${toEdges(pDependencies)}
}
`;
}

function getDependencyStrings(pDirOrFile, pOptions) {
    if (pOptions.flatDefine){
        throw new Error(
            "Flat define (-d) + rendering as a dot graph (-G) won't work. Did you mean to do one of those?\n"
        );
    }

    if (fs.statSync(pDirOrFile).isDirectory()){
        return toDiGraph(extractor.extractRecursiveDir(pDirOrFile, pOptions));
    } else {
        return toDiGraph(extractor.extractRecursive(pDirOrFile, pOptions));
    }
}

exports.getDependencyStrings = getDependencyStrings;
<commit_msg>also uses the 'do not delete this line' mechanism for overwriting dot output<commit_after>"use strict";
const fs        = require('fs');
const extractor = require('./extractor-composite');

function dep2linecolor(pDep) {
    if (pDep.coreModule){
        return "\"#999999\"";
    }

    return "black";
}

function toEntities(pDependencies) {
    return Object.keys(pDependencies).reduce(
        (pEntities, pDependency) => pEntities.concat(`\"${pDependency}\" [color=black, fontcolor=black]\n    `),
    "");
}

function renderEdgesForDependant(pDep, pDependencies) {
    return pDependencies[pDep].reduce(
        (pAll, pThing) =>
            pAll.concat(
                `\"${pDep}\" -> \"${pThing.resolved}\" [color=${dep2linecolor(pThing)}]\n    `
            ),
    "");
}

function toEdges(pDependencies) {
    return Object.keys(pDependencies).reduce(
        (pEdges, pDependency) =>
            pEdges.concat(`${renderEdgesForDependant(pDependency, pDependencies)}`),
    "");
}

function toDiGraph(pDependencies) {
    return `digraph {
    ordering=out
    rankdir=LR
    splines=true
    overlap=false
    node [shape=box, style="rounded, filled",
          color="#999999", fillcolor="#ffffdd", fontcolor="#999999",
          fontname=Helvetica, fontsize=9]
    edge [color=black, arrowhead=vee, fontname="Helvetica", fontsize="9"]

    ${toEntities(pDependencies)}

    ${toEdges(pDependencies)}
}
`;
}

function getDependencyStrings(pDirOrFile, pOptions) {
    let lDelimiter = "";

    if (pOptions.flatDefine){
        throw new Error(
            "Flat define (-d) + rendering as a dot graph (-G) won't work. Did you mean to do one of those?\n"
        );
    }
    if (!pOptions.append){
        lDelimiter = `\n${pOptions.delimiter}\n\n`;
    }

    if (fs.statSync(pDirOrFile).isDirectory()){
        return lDelimiter + toDiGraph(extractor.extractRecursiveDir(pDirOrFile, pOptions));
    } else {
        return lDelimiter + toDiGraph(extractor.extractRecursive(pDirOrFile, pOptions));
    }
}

exports.getDependencyStrings = getDependencyStrings;
<|endoftext|>


<commit_before>"use strict";

var m      = require("mithril"),
    assign = require("lodash.assign"),
    get    = require("lodash.get"),

    hide  = require("./hide"),
    id    = require("./id"),
    label = require("./label"),

    css = require("./types.css");

module.exports = function(type) {
    return {
        controller : function(options) {
            var ctrl = this,
                val  = get(options.field, "attrs.value");

            ctrl.id = id(options);

            // tivac/anthracite#96
            // If this is a new item (never been updated) set the default value
            // Don't want to use that value on every render because it is bad UX,
            // the user becomes unable to clear out the field
            if(val) {
                options.root.child("updated_at").on("value", function(snap) {
                    if(snap.exists()) {
                        return;
                    }

                    options.update(options.path, val);

                    m.redraw();
                });
            }
        },

        view : function(ctrl, options) {
            var field  = options.field,
                hidden = hide(options);

            if(hidden) {
                return hidden;
            }

            return m("div", { class : options.class },
                label(ctrl, options),
                m("input", assign({}, field.attrs || {}, {
                        // attrs
                        id       : ctrl.id,
                        type     : type || "text",
                        class    : css[type || "text"],
                        value    : options.data || "",
                        required : field.required ? "required" : null,

                        // events
                        oninput : m.withAttr("value", options.update(options.path))
                    }
                ))
            );
        }
    };
};
<commit_msg>Fix schema view when default number value is defined<commit_after>"use strict";

var m      = require("mithril"),
    assign = require("lodash.assign"),
    get    = require("lodash.get"),

    hide  = require("./hide"),
    id    = require("./id"),
    label = require("./label"),

    css = require("./types.css");

module.exports = function(type) {
    return {
        controller : function(options) {
            var ctrl = this,
                val  = get(options.field, "attrs.value");

            ctrl.id = id(options);

            // tivac/anthracite#96
            // If this is a new item (never been updated) set the default value
            // Don't want to use that value on every render because it is bad UX,
            // the user becomes unable to clear out the field
            if(val && options.root) {
                options.root.child("updated_at").on("value", function(snap) {
                    if(snap.exists()) {
                        return;
                    }

                    options.update(options.path, val);

                    m.redraw();
                });
            }
        },

        view : function(ctrl, options) {
            var field  = options.field,
                hidden = hide(options);

            if(hidden) {
                return hidden;
            }

            return m("div", { class : options.class },
                label(ctrl, options),
                m("input", assign({}, field.attrs || {}, {
                        // attrs
                        id       : ctrl.id,
                        type     : type || "text",
                        class    : css[type || "text"],
                        value    : options.data || "",
                        required : field.required ? "required" : null,

                        // events
                        oninput : m.withAttr("value", options.update(options.path))
                    }
                ))
            );
        }
    };
};
<|endoftext|>


<commit_before>// Load in our dependencies
var assert = require('assert');
var path = require('path');
var spawn = require('child_process').spawn;
var async = require('async');
var concat = require('concat-stream');
var Tempfile = require('temporary/lib/file');
var phantomLocation = require('which').sync('phantomjs');
var jpegJs = require('jpeg-js');
var ndarray = require('ndarray');
var savePixels = require('save-pixels');

// Define our format to extension mapping
var formatToExtMap = {
  png: 'png',
  'image/png': 'png',
  jpg: 'jpeg',
  jpeg: 'jpeg',
  'image/jpg': 'jpeg',
  'image/jpeg': 'jpeg'
};

/**
 * PhantomJS exporter
 * @param {Object} options Options to export with
 * @param {Number} [options.quality] Quality of the exported item (jpeg only)
 * @param {Function} cb Error-first callback to return binary image string to
 */
function exportCanvas(options, callback) {
  // Find our matching extension for the given format
  var format = options.format || 'png';
  var ext = formatToExtMap[format];
  assert(ext, '`phantomjssmith` doesn\'t support exporting "' + ext + '". Please use "jpeg" or "png"');

  // Localize context for later and create common variables
  var that = this;
  var params, tmp, stdout, stderr, code;

  // In series
  async.waterfall([
    function createTmpFile (cb) {
      // Convert over all image paths to url paths
      var images = that.images;
      images.forEach(function getUrlPath (img) {
        img = img.img;
        img._urlpath = path.relative(__dirname + '/scripts', img._filepath);
      });

      // Collect our parameters
      params = that.params;
      params.images = images;
      params.options = options;

      // Stringify our argument for phantomjs
      var arg = JSON.stringify(params);
      var encodedArg = encodeURIComponent(arg);

      // Write out argument to temporary file -- streams weren't cutting it
      tmp = new Tempfile();
      tmp.writeFile(encodedArg, 'utf8', cb);
    },
    function spawnPhantomJS (cb) {
      // Create a child process for phantomjs
      var phantomjs = spawn(phantomLocation, [path.join(__dirname, 'scripts', 'compose.js'), tmp.path]);
      phantomjs.on('error', cb);

      // When there is data, save it
      // DEV: encodedPixels is an array of rgba values
      stdout = '';
      phantomjs.stdout.on('data', function handleStdout (buffer) {
        stdout += buffer.toString();
      });

      // When there is an error, concatenate it
      stderr = '';
      phantomjs.stderr.on('data', function handleData (buffer) {
        // Ignore PhantomJS 1.9.2 OSX errors
        // https://github.com/Ensighten/grunt-spritesmith/issues/33
        var bufferStr = buffer.toString();
        var isNot192OSXError = bufferStr.indexOf('WARNING: Method userSpaceScaleFactor') === -1;
        var isNotPerformanceNote = bufferStr.indexOf('CoreText performance note:') === -1;
        if (isNot192OSXError && isNotPerformanceNote) {
          stderr += bufferStr;
        }
      });

      // When we are done, save the code and continue
      phantomjs.on('close', function handleClose (_code) {
        code = _code;
        cb();
      });
    },
    function deleteTmpFile (cb) {
      // Destroy the temporary file
      tmp.unlink(cb);
    },
    function handleResult (cb) {
      // If we received a non-zero exit code, complain and leave
      if (code !== 0) {
        var err = new Error('Received non-zero exit code "' + code + '" from PhantomJS. stdout:' + stdout);
        return cb(err);
      }

      // Otherwise, decode the pixel values
      // DEV: This used to be thinner and not need padding but Windows was messing up the image
      var encodedPixels = stdout;
      var decodedPixels;
      try {
        decodedPixels = JSON.parse(encodedPixels);
      } catch (e) {
        return cb(new Error('Error while parsing JSON "' + encodedPixels + '".\n' + e.message));
      }

      // If we are dealing with a `jpeg`, then use `jpeg-js`
      // DEV: This is to support `quality` which `save-pixels` doesn't
      if (ext === 'jpeg') {
        // Encode our data via `jpeg-js` and callback with its internal buffer
        // TODO: When transitioning to a stream, use `contentstream`
        var jpg;
        try {
          jpg = jpegJs.encode({
            data: decodedPixels,
            width: params.width,
            height: params.height
          }, options.quality);
        } catch (err) {
          return cb(err);
        }
        cb(null, jpg.data.toString('binary'));
      // Otherwise, leverage `save-pixels`
      } else {
        // Convert the pixels into an ndarray
        // Taken from https://github.com/mikolalysenko/get-pixels/blob/2ac98645119244d6e52afcef5fe52cc9300fb27b/dom-pixels.js#L14
        var imgNdarray = ndarray(decodedPixels,
          [params.height, params.width, 4], [4 * params.width, 4, 1], 0);
        var imgStream = savePixels(imgNdarray, 'PNG');

        // Collect the stream into a buffer and callback with a binary string (expected by spritesmith)
        imgStream.on('error', cb);
        imgStream.pipe(concat(function handleBuffer (imgBuff) {
          cb(null, imgBuff.toString('binary'));
        }));
      }
    }
  ], callback);
}
module.exports = exportCanvas;
<commit_msg>Fixed up lint error<commit_after>// Load in our dependencies
var assert = require('assert');
var path = require('path');
var spawn = require('child_process').spawn;
var async = require('async');
var concat = require('concat-stream');
var Tempfile = require('temporary/lib/file');
var phantomLocation = require('which').sync('phantomjs');
var jpegJs = require('jpeg-js');
var ndarray = require('ndarray');
var savePixels = require('save-pixels');

// Define our format to extension mapping
var formatToExtMap = {
  png: 'png',
  'image/png': 'png',
  jpg: 'jpeg',
  jpeg: 'jpeg',
  'image/jpg': 'jpeg',
  'image/jpeg': 'jpeg'
};

/**
 * PhantomJS exporter
 * @param {Object} options Options to export with
 * @param {Number} [options.quality] Quality of the exported item (jpeg only)
 * @param {Function} cb Error-first callback to return binary image string to
 */
function exportCanvas(options, callback) {
  // Find our matching extension for the given format
  var format = options.format || 'png';
  var ext = formatToExtMap[format];
  assert(ext, '`phantomjssmith` doesn\'t support exporting "' + ext + '". Please use "jpeg" or "png"');

  // Localize context for later and create common variables
  var that = this;
  var params, tmp, stdout, stderr, code;

  // In series
  async.waterfall([
    function createTmpFile (cb) {
      // Convert over all image paths to url paths
      var images = that.images;
      images.forEach(function getUrlPath (img) {
        img = img.img;
        img._urlpath = path.relative(__dirname + '/scripts', img._filepath);
      });

      // Collect our parameters
      params = that.params;
      params.images = images;
      params.options = options;

      // Stringify our argument for phantomjs
      var arg = JSON.stringify(params);
      var encodedArg = encodeURIComponent(arg);

      // Write out argument to temporary file -- streams weren't cutting it
      tmp = new Tempfile();
      tmp.writeFile(encodedArg, 'utf8', cb);
    },
    function spawnPhantomJS (cb) {
      // Create a child process for phantomjs
      var phantomjs = spawn(phantomLocation, [path.join(__dirname, 'scripts', 'compose.js'), tmp.path]);
      phantomjs.on('error', cb);

      // When there is data, save it
      // DEV: encodedPixels is an array of rgba values
      stdout = '';
      phantomjs.stdout.on('data', function handleStdout (buffer) {
        stdout += buffer.toString();
      });

      // When there is an error, concatenate it
      stderr = '';
      phantomjs.stderr.on('data', function handleData (buffer) {
        // Ignore PhantomJS 1.9.2 OSX errors
        // https://github.com/Ensighten/grunt-spritesmith/issues/33
        var bufferStr = buffer.toString();
        var isNot192OSXError = bufferStr.indexOf('WARNING: Method userSpaceScaleFactor') === -1;
        var isNotPerformanceNote = bufferStr.indexOf('CoreText performance note:') === -1;
        if (isNot192OSXError && isNotPerformanceNote) {
          stderr += bufferStr;
        }
      });

      // When we are done, save the code and continue
      phantomjs.on('close', function handleClose (_code) {
        code = _code;
        cb();
      });
    },
    function deleteTmpFile (cb) {
      // Destroy the temporary file
      tmp.unlink(cb);
    },
    function handleResult (cb) {
      // If we received a non-zero exit code, complain and leave
      if (code !== 0) {
        var err = new Error('Received non-zero exit code "' + code + '" from PhantomJS. stdout:' + stdout);
        return cb(err);
      }

      // Otherwise, decode the pixel values
      // DEV: This used to be thinner and not need padding but Windows was messing up the image
      var encodedPixels = stdout;
      var decodedPixels;
      try {
        decodedPixels = JSON.parse(encodedPixels);
      } catch (e) {
        return cb(new Error('Error while parsing JSON "' + encodedPixels + '".\n' + e.message));
      }

      // If we are dealing with a `jpeg`, then use `jpeg-js`
      // DEV: This is to support `quality` which `save-pixels` doesn't
      if (ext === 'jpeg') {
        // Encode our data via `jpeg-js` and callback with its internal buffer
        // TODO: When transitioning to a stream, use `contentstream`
        var jpg;
        try {
          jpg = jpegJs.encode({
            data: decodedPixels,
            width: params.width,
            height: params.height
          }, options.quality);
        } catch (err) {
          return cb(err);
        }
        cb(null, jpg.data.toString('binary'));
      // Otherwise, leverage `save-pixels`
      } else {
        // Convert the pixels into an ndarray
        // Taken from https://github.com/mikolalysenko/get-pixels/blob/2ac98645119244d6e52afcef5fe52cc9300fb27b/dom-pixels.js#L14
        var imgNdarray = ndarray(decodedPixels,
          [params.height, params.width, 4], [4 * params.width, 4, 1], 0);
        var imgStream = savePixels(imgNdarray, 'PNG');

        // Collect the stream into a buffer and callback with a binary string (expected by spritesmith)
        imgStream.on('error', cb);
        imgStream.pipe(concat(function handleBuffer (imgBuff) {
          cb(null, imgBuff.toString('binary'));
        }));
      }
    }
  ], callback);
}
module.exports = exportCanvas;
<|endoftext|>


<commit_before>/*
 * Project:
 *   glideinWMS
 *
 * File Version:
 *   $Id: frontend_support.js,v 1.2.8.1.18.1 2011/07/02 01:29:57 sfiligoi Exp $
 *
 * Support javascript module for the frontend monitoring
 * Part of the gldieinWMS package
 *
 * Original repository: http://www.uscms.org/SoftwareComputing/Grid/WMS/glideinWMS/
 *
 */

// Load FrontendStats XML file and return the object
function loadFrontendStats() {
  var request =  new XMLHttpRequest();
  request.open("GET", "frontend_status.xml",false);
  request.send(null);

  var frontendStats=request.responseXML.firstChild;
  return frontendStats;
}

// Extract group names from a frontendStats XML object
function getFrontendGroups(frontendStats) {
  groups=new Array();
  for (var elc=0; elc<frontendStats.childNodes.length; elc++) {
    var el=frontendStats.childNodes[elc];
    if ((el.nodeType==1) && (el.nodeName=="groups")) {
      for (var etc=0; etc<el.childNodes.length; etc++) {
	var group=el.childNodes[etc];
	if ((group.nodeType==1)&&(group.nodeName=="group")) {
	  var group_name=group.attributes.getNamedItem("name");
	  groups.push(group_name.value);
	}
      }
    }
  }
  return groups;
}

//Extract factory names from frontendStats XML obj
function getFrontendGroupFactories(frontendStats, group_name) {
  factories=new Array();

  if(group_name=="total") {
    for (var i=0; i<frontendStats.childNodes.length; i++) {
      var el=frontendStats.childNodes[i];
      if ((el.nodeType==1) && (el.nodeName=="factories")) {
        for (var j=0; j<el.childNodes.length; j++) {
  	  var group=el.childNodes[j];
            if ((group.nodeType==1)&&(group.nodeName=="factory")) {
              var group_name=group.attributes.getNamedItem("name");
	      factories.push(group_name.value);
	    }
          }
       }
    }
    return factories;
  }

  for (var i=0; i<frontendStats.childNodes.length; i++) {
    var el=frontendStats.childNodes[i];
    if ((el.nodeType==1) && (el.nodeName=="groups")) {
      for (var j=0; j<el.childNodes.length; j++) {
	var group=el.childNodes[j];
	if ((group.nodeType==1)&&(group.nodeName=="group")) {
	  var group_name1=group.attributes.getNamedItem("name").value;
          if(group_name1==group_name) {
             for(var k=0; k<group.childNodes.length; k++) {
               var el2 = group.childNodes[k];
               if (el2.nodeName=="factories") {
                  for(var m=0; m<el2.childNodes.length; m++) {
                     var factory = el2.childNodes[m];
                     if(factory.nodeName=="factory") {
                        factory_name=factory.attributes.getNamedItem("name");
	                factories.push(factory_name.value);
                     }
                  }
               }
             }
          }
	}
      }
    }
  }
  return factories;
}
<commit_msg>Add sanitize function<commit_after>/*
 * Project:
 *   glideinWMS
 *
 * File Version:
 *   $Id: frontend_support.js,v 1.2.8.1.18.2 2011/07/05 16:36:39 sfiligoi Exp $
 *
 * Support javascript module for the frontend monitoring
 * Part of the gldieinWMS package
 *
 * Original repository: http://www.uscms.org/SoftwareComputing/Grid/WMS/glideinWMS/
 *
 */

// Load FrontendStats XML file and return the object
function loadFrontendStats() {
  var request =  new XMLHttpRequest();
  request.open("GET", "frontend_status.xml",false);
  request.send(null);

  var frontendStats=request.responseXML.firstChild;
  return frontendStats;
}

// Extract group names from a frontendStats XML object
function getFrontendGroups(frontendStats) {
  groups=new Array();
  for (var elc=0; elc<frontendStats.childNodes.length; elc++) {
    var el=frontendStats.childNodes[elc];
    if ((el.nodeType==1) && (el.nodeName=="groups")) {
      for (var etc=0; etc<el.childNodes.length; etc++) {
	var group=el.childNodes[etc];
	if ((group.nodeType==1)&&(group.nodeName=="group")) {
	  var group_name=group.attributes.getNamedItem("name");
	  groups.push(group_name.value);
	}
      }
    }
  }
  return groups;
}

//Extract factory names from frontendStats XML obj
function getFrontendGroupFactories(frontendStats, group_name) {
  factories=new Array();

  if(group_name=="total") {
    for (var i=0; i<frontendStats.childNodes.length; i++) {
      var el=frontendStats.childNodes[i];
      if ((el.nodeType==1) && (el.nodeName=="factories")) {
        for (var j=0; j<el.childNodes.length; j++) {
  	  var group=el.childNodes[j];
            if ((group.nodeType==1)&&(group.nodeName=="factory")) {
              var group_name=group.attributes.getNamedItem("name");
	      factories.push(group_name.value);
	    }
          }
       }
    }
    return factories;
  }

  for (var i=0; i<frontendStats.childNodes.length; i++) {
    var el=frontendStats.childNodes[i];
    if ((el.nodeType==1) && (el.nodeName=="groups")) {
      for (var j=0; j<el.childNodes.length; j++) {
	var group=el.childNodes[j];
	if ((group.nodeType==1)&&(group.nodeName=="group")) {
	  var group_name1=group.attributes.getNamedItem("name").value;
          if(group_name1==group_name) {
             for(var k=0; k<group.childNodes.length; k++) {
               var el2 = group.childNodes[k];
               if (el2.nodeName=="factories") {
                  for(var m=0; m<el2.childNodes.length; m++) {
                     var factory = el2.childNodes[m];
                     if(factory.nodeName=="factory") {
                        factory_name=factory.attributes.getNamedItem("name");
	                factories.push(factory_name.value);
                     }
                  }
               }
             }
          }
	}
      }
    }
  }
  return factories;
}

function sanitize(name) {
 var out="";
 for (var i=0; i<name.length; i++) {
  var c=name.charAt(i);
  if (c.search('[A-z0-9\-.]')==-1) {
    out=out.concat('_');
  } else {
    out=out.concat(c);
  }
 }
 return out;
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
import '../../server/env';

import { ArgumentParser } from 'argparse';
import { get, intersection } from 'lodash';

import { MODERATION_CATEGORIES_ALIASES } from '../../server/constants/moderation-categories';
import orderStatus from '../../server/constants/order_status';
import { purgeCacheForCollective } from '../../server/lib/cache';
import logger from '../../server/lib/logger';
import { notifyAdminsOfCollective } from '../../server/lib/notifications';
import * as libPayments from '../../server/lib/payments';
import models, { Op, sequelize } from '../../server/models';

// Fetch all orders potentially affected: contributor flagged AND recipient setup rejection

const query = `SELECT "Orders"."id"
  FROM "Orders", "Collectives", "Collectives" as "FromCollectives"
  WHERE "Orders"."CollectiveId" = "Collectives"."id" AND "FromCollectives"."id" = "Orders"."FromCollectiveId"
  AND "Orders"."status" IN ('ACTIVE', 'PAID')
  AND "Collectives"."settings"->'moderation'->'rejectedCategories' IS NOT NULL
  AND "FromCollectives"."data"->'categories' IS NOT NULL`;

const getContributorRejectedCategories = (fromCollective, collective) => {
  const rejectedCategories = get(collective, 'settings.moderation.rejectedCategories', []);
  const contributorCategories = get(fromCollective, 'data.categories', []);

  if (rejectedCategories.length === 0 || contributorCategories.length === 0) {
    return [];
  }

  // Example:
  // MODERATION_CATEGORIES_ALIASES = ['CASINO_GAMBLING': ['casino', 'gambling'], 'VPN_PROXY': ['vpn', 'proxy']]
  // - when contributorCategories = ['CASINO_GAMBLING'], returns ['CASINO_GAMBLING']
  // - when contributorCategories = ['vpn'] or ['proxy'], returns ['VPN_PROXY']
  const contributorRejectedCategories = Object.keys(MODERATION_CATEGORIES_ALIASES).filter(key => {
    return (
      contributorCategories.includes(key) ||
      intersection(MODERATION_CATEGORIES_ALIASES[key], contributorCategories).length !== 0
    );
  });

  return intersection(rejectedCategories, contributorRejectedCategories);
};

async function run({ dryRun, limit, force } = {}) {
  let rows = await sequelize.query(query, { type: sequelize.QueryTypes.SELECT });

  if (rows.length > 0 && limit) {
    rows = rows.slice(0, limit);
  }

  for (const row of rows) {
    const order = await models.Order.findByPk(row['id']);
    const collective = await models.Collective.findByPk(order.CollectiveId);
    const fromCollective = await models.Collective.findByPk(order.FromCollectiveId);

    logger.info(`Checking order #${order.id} from #${fromCollective.slug} to #${collective.slug}`);

    const rejectedCategories = getContributorRejectedCategories(fromCollective, collective);

    if (rejectedCategories.length === 0) {
      logger.info(`  - No rejected categories`);
      continue;
    }

    logger.info(`  - Found rejected categories: ${rejectedCategories.join(', ')}`);

    let shouldMarkAsRejected = true;

    // Retrieve latest transaction
    const transaction = await models.Transaction.findOne({
      where: {
        OrderId: order.id,
        type: 'CREDIT',
        createdAt: { [Op.gte]: sequelize.literal("NOW() - INTERVAL '30 days'") },
      },
      order: [['createdAt', 'DESC']],
    });

    if (transaction) {
      logger.info(`  - Found transaction #${transaction.id}`);
      // Refund transaction if not already refunded
      if (!transaction.RefundTransactionId) {
        logger.info(`  - Refunding transaction`);
        const paymentMethod = transaction.PaymentMethodId
          ? await models.PaymentMethod.findByPk(transaction.PaymentMethodId)
          : null;
        const paymentMethodProvider = paymentMethod ? libPayments.findPaymentMethodProvider(paymentMethod) : null;
        if (!paymentMethodProvider || !paymentMethodProvider.refundTransaction) {
          if (force) {
            logger.info(`  - refundTransaction not available. Creating refundTransaction in the database only.`);
          } else {
            logger.info(`  - refundTransaction not available. Use 'force' to refundTransaction in the database only.`);
          }
        }
        if (!dryRun) {
          try {
            if (paymentMethodProvider.refundTransaction) {
              await libPayments.refundTransaction(transaction);
            } else if (force) {
              await libPayments.createRefundTransaction(transaction, 0, null);
            }
          } catch (e) {
            if (e.message.includes('has already been refunded')) {
              logger.info(`  - Transaction has already been refunded on Payment Provider`);
              if (paymentMethodProvider && paymentMethodProvider.refundTransactionOnlyInDatabase) {
                await paymentMethodProvider.refundTransactionOnlyInDatabase(transaction);
              }
            }
          }
        }
      } else {
        logger.info(`  - Transaction already refunded`);
      }
    } else {
      logger.info(`  - No transaction found`);
      if (order.status === 'PAID') {
        shouldMarkAsRejected = false;
      }
    }

    // Mark the Order as rejected (only if we found a transaction to refund)
    if (shouldMarkAsRejected) {
      logger.info(`  - Marking order #${order.id} as rejected `);
      if (!dryRun) {
        await order.update({ status: orderStatus.REJECTED });
      }
    }

    // Deactivate subscription
    if (order.SubscriptionId) {
      const subscription = await models.Subscription.findByPk(order.SubscriptionId);
      if (subscription) {
        logger.info(`  - Deactivating subscription #${order.SubscriptionId}`);
        if (!dryRun) {
          await subscription.deactivate();
        }
      } else {
        logger.info(`  - Subscription not found`);
      }
    } else {
      logger.info(`  - No subscription to deactivate`);
    }

    // Remove memberships
    logger.info(`  - Deleting BACKER membership`);
    if (!dryRun) {
      await models.Member.destroy({
        where: {
          MemberCollectiveId: fromCollective.id,
          CollectiveId: collective.id,
          role: 'BACKER',
        },
      });
    }

    logger.info(`  - Purging cache for ${collective.slug}`);
    logger.info(`  - Purging cache for ${fromCollective.slug}`);
    if (!dryRun) {
      purgeCacheForCollective(collective.slug);
      purgeCacheForCollective(fromCollective.slug);
    }

    const activity = {
      type: 'contribution.rejected',
      data: {
        collective: { name: collective.name },
        rejectionReason: `${collective.name} banned some specific categories of contributors and there was a match with your profile.`,
      },
    };

    logger.info(`  - Notifying admins of ${fromCollective.slug}`);
    if (!dryRun) {
      await notifyAdminsOfCollective(fromCollective.id, activity);
    }
  }
}

/* eslint-disable camelcase */
function parseCommandLineArguments() {
  const parser = new ArgumentParser({
    add_help: true,
    description: 'Reject Contributions based on Categories',
  });
  parser.add_argument('--dryrun', {
    help: "Don't perform any change, just log.",
    default: false,
    action: 'store_const',
    const: true,
  });
  parser.add_argument('-l', '--limit', {
    help: 'Total matching orders to process',
  });
  parser.add_argument('--force', {
    help: "Force refunds even if payment provider doesn't support it.",
    default: false,
    action: 'store_const',
    const: true,
  });
  const args = parser.parse_args();
  return {
    dryRun: args.dryrun,
    limit: args.limit,
    force: args.force,
  };
}

/* eslint-enable camelcase */

if (require.main === module) {
  run(parseCommandLineArguments())
    .then(() => {
      process.exit(0);
    })
    .catch(e => {
      console.error(e);
      process.exit(1);
    });
}
<commit_msg>reject-contributions tweaks<commit_after>#!/usr/bin/env node
import '../../server/env';

import { ArgumentParser } from 'argparse';
import { get, intersection } from 'lodash';

import { MODERATION_CATEGORIES_ALIASES } from '../../server/constants/moderation-categories';
import orderStatus from '../../server/constants/order_status';
import { purgeCacheForCollective } from '../../server/lib/cache';
import logger from '../../server/lib/logger';
import { notifyAdminsOfCollective } from '../../server/lib/notifications';
import * as libPayments from '../../server/lib/payments';
import models, { Op, sequelize } from '../../server/models';

// Fetch all orders potentially affected: contributor flagged AND recipient setup rejection

const query = `SELECT "Orders"."id"
  FROM "Orders", "Collectives", "Collectives" as "FromCollectives"
  WHERE "Orders"."CollectiveId" = "Collectives"."id" AND "FromCollectives"."id" = "Orders"."FromCollectiveId"
  AND "Orders"."status" IN ('ACTIVE', 'PAID')
  AND "Collectives"."settings"->'moderation'->'rejectedCategories' IS NOT NULL
  AND "FromCollectives"."data"->'categories' IS NOT NULL`;

const getContributorRejectedCategories = (fromCollective, collective) => {
  const rejectedCategories = get(collective, 'settings.moderation.rejectedCategories', []);
  const contributorCategories = get(fromCollective, 'data.categories', []);

  if (rejectedCategories.length === 0 || contributorCategories.length === 0) {
    return [];
  }

  // Example:
  // MODERATION_CATEGORIES_ALIASES = ['CASINO_GAMBLING': ['casino', 'gambling'], 'VPN_PROXY': ['vpn', 'proxy']]
  // - when contributorCategories = ['CASINO_GAMBLING'], returns ['CASINO_GAMBLING']
  // - when contributorCategories = ['vpn'] or ['proxy'], returns ['VPN_PROXY']
  const contributorRejectedCategories = Object.keys(MODERATION_CATEGORIES_ALIASES).filter(key => {
    return (
      contributorCategories.includes(key) ||
      intersection(MODERATION_CATEGORIES_ALIASES[key], contributorCategories).length !== 0
    );
  });

  return intersection(rejectedCategories, contributorRejectedCategories);
};

async function run({ dryRun, limit, force } = {}) {
  let rows = await sequelize.query(query, { type: sequelize.QueryTypes.SELECT });

  if (rows.length > 0 && limit) {
    rows = rows.slice(0, limit);
  }

  for (const row of rows) {
    const order = await models.Order.findByPk(row['id']);
    const collective = await models.Collective.findByPk(order.CollectiveId);
    const fromCollective = await models.Collective.findByPk(order.FromCollectiveId);

    if (collective.slug === 'opencollective') {
      continue;
    }

    logger.info(`Checking order #${order.id} from #${fromCollective.slug} to #${collective.slug}`);

    const rejectedCategories = getContributorRejectedCategories(fromCollective, collective);

    if (rejectedCategories.length === 0) {
      logger.info(`  - No rejected categories`);
      continue;
    }

    logger.info(`  - Found rejected categories: ${rejectedCategories.join(', ')}`);

    let shouldMarkAsRejected = true;
    let shouldNotifyContributor = true;

    // Retrieve latest transaction
    const transaction = await models.Transaction.findOne({
      where: {
        OrderId: order.id,
        type: 'CREDIT',
        createdAt: { [Op.gte]: sequelize.literal("NOW() - INTERVAL '30 days'") },
      },
      order: [['createdAt', 'DESC']],
    });

    if (transaction) {
      logger.info(`  - Found transaction #${transaction.id}`);
      // Refund transaction if not already refunded
      if (!transaction.RefundTransactionId) {
        logger.info(`  - Refunding transaction`);
        const paymentMethod = transaction.PaymentMethodId
          ? await models.PaymentMethod.findByPk(transaction.PaymentMethodId)
          : null;
        const paymentMethodProvider = paymentMethod ? libPayments.findPaymentMethodProvider(paymentMethod) : null;
        if (!paymentMethodProvider || !paymentMethodProvider.refundTransaction) {
          if (force) {
            logger.info(`  - refundTransaction not available. Creating refundTransaction in the database only.`);
          } else {
            logger.info(`  - refundTransaction not available. Use 'force' to refundTransaction in the database only.`);
          }
        }
        if (!dryRun) {
          try {
            if (paymentMethodProvider.refundTransaction) {
              await libPayments.refundTransaction(transaction);
            } else if (force) {
              await libPayments.createRefundTransaction(transaction, 0, null);
            }
          } catch (e) {
            if (e.message.includes('has already been refunded')) {
              logger.info(`  - Transaction has already been refunded on Payment Provider`);
              if (paymentMethodProvider && paymentMethodProvider.refundTransactionOnlyInDatabase) {
                await paymentMethodProvider.refundTransactionOnlyInDatabase(transaction);
              }
            }
          }
        }
      } else {
        logger.info(`  - Transaction already refunded`);
      }
    } else {
      logger.info(`  - No transaction found`);
      if (order.status === 'PAID') {
        shouldMarkAsRejected = false;
        shouldNotifyContributor = false;
      }
    }

    // Mark the Order as rejected (only if we found a transaction to refund)
    if (shouldMarkAsRejected) {
      logger.info(`  - Marking order #${order.id} as rejected `);
      if (!dryRun) {
        await order.update({ status: orderStatus.REJECTED });
      }
    }

    // Deactivate subscription
    if (order.SubscriptionId) {
      const subscription = await models.Subscription.findByPk(order.SubscriptionId);
      if (subscription) {
        logger.info(`  - Deactivating subscription #${order.SubscriptionId}`);
        if (!dryRun) {
          await subscription.deactivate();
        }
      } else {
        logger.info(`  - Subscription not found`);
      }
    } else {
      logger.info(`  - No subscription to deactivate`);
    }

    // Remove memberships
    logger.info(`  - Deleting BACKER membership`);
    if (!dryRun) {
      await models.Member.destroy({
        where: {
          MemberCollectiveId: fromCollective.id,
          CollectiveId: collective.id,
          role: 'BACKER',
        },
      });
    }

    logger.info(`  - Purging cache for ${collective.slug}`);
    logger.info(`  - Purging cache for ${fromCollective.slug}`);
    if (!dryRun) {
      purgeCacheForCollective(collective.slug);
      purgeCacheForCollective(fromCollective.slug);
    }

    if (shouldNotifyContributor) {
      const activity = {
        type: 'contribution.rejected',
        data: {
          collective: { name: collective.name },
          rejectionReason: `${collective.name} banned some specific categories of contributors and there was a match with your profile.`,
        },
      };
      logger.info(`  - Notifying admins of ${fromCollective.slug}`);
      if (!dryRun) {
        await notifyAdminsOfCollective(fromCollective.id, activity);
      }
    }
  }
}

/* eslint-disable camelcase */
function parseCommandLineArguments() {
  const parser = new ArgumentParser({
    add_help: true,
    description: 'Reject Contributions based on Categories',
  });
  parser.add_argument('--dryrun', {
    help: "Don't perform any change, just log.",
    default: false,
    action: 'store_const',
    const: true,
  });
  parser.add_argument('-l', '--limit', {
    help: 'Total matching orders to process',
  });
  parser.add_argument('--force', {
    help: "Force refunds even if payment provider doesn't support it.",
    default: false,
    action: 'store_const',
    const: true,
  });
  const args = parser.parse_args();
  return {
    dryRun: args.dryrun,
    limit: args.limit,
    force: args.force,
  };
}

/* eslint-enable camelcase */

if (require.main === module) {
  run(parseCommandLineArguments())
    .then(() => {
      process.exit(0);
    })
    .catch(e => {
      console.error(e);
      process.exit(1);
    });
}
<|endoftext|>


<commit_before>//
// fast-image-size - Simple stand alone module to just extract the image size from image file without using special image libraries.
//
// Please refer to README.md for this module's documentations.
//
// NOTE:
// - Before changing this code please refer to the 'hacking the code section' on README.md.
//
// Copyright (c) 2013 Ziv Barber;
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// 'Software'), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

var fs = require('fs');
var path = require('path');

module.exports = exports = function (file_path, callback) {

    function getJpgSize(buffer_data, retInfo) {
        // Skip 5 chars, they are for signature
        buffer_data = buffer_data.slice(4);

        var i, next;
        while (buffer_data.length) {
            // read length of the next block
            i = buffer_data.readUInt16BE(0);

            // 0xFFC0 is baseline(SOF)
            // 0xFFC2 is progressive(SOF2)
            next = buffer_data[i + 1];
            if (next === 0xC0 || next === 0xC2) {
                return {
                    'height': buffer_data.readUInt16BE(i + 5),
                    'width': buffer_data.readUInt16BE(i + 7)
                };
            }

            // move to the next block
            buffer_data = buffer_data.slice(i + 2);
        }
    }

    function parseHeaderData(buffer_data, callback_data) {
        var retInfo = {};

        // Detect GIF:
        if (buffer_data[0] == 0x47 && buffer_data[1] == 0x49 && buffer_data[2] == 0x46) {
            retInfo.type = 'gif';
            retInfo.width = (buffer_data[7] * 256) + buffer_data[6];
            retInfo.height = (buffer_data[9] * 256) + buffer_data[8];

            // Detect JPEG:
        } else if (buffer_data[0] == 0xFF && buffer_data[1] == 0xD8 && buffer_data[2] == 0xFF && (buffer_data[3] == 0xE0 || buffer_data[3] == 0xE1)) {
            retInfo.type = 'jpeg';
            var size = getJpgSize(buffer_data, retInfo);
            retInfo.width = size.width;
            retInfo.height = size.height;

            // Detect PNG:
        } else if (buffer_data[0] == 137 && buffer_data[1] == 80 && buffer_data[2] == 78 && buffer_data[3] == 71 && buffer_data[4] == 13 && buffer_data[5] == 10 && buffer_data[6] == 26 && buffer_data[7] == 10) {
            retInfo.type = 'png';

            if (buffer_data[12] == 0x49 && buffer_data[13] == 0x48 && buffer_data[14] == 0x44 && buffer_data[15] == 0x52) {
                retInfo.width = (buffer_data[16] * 256 * 256 * 256) + (buffer_data[17] * 256 * 256) + (buffer_data[18] * 256) + buffer_data[19];
                retInfo.height = (buffer_data[20] * 256 * 256 * 256) + (buffer_data[21] * 256 * 256) + (buffer_data[22] * 256) + buffer_data[23];
            } // Endif.

            // Detect BMP:
        } else if (buffer_data[0] == 0x42 && buffer_data[1] == 0x4D) {
            retInfo.type = 'bmp';
            retInfo.width = (buffer_data[21] * 256 * 256 * 256) + (buffer_data[20] * 256 * 256) + (buffer_data[19] * 256) + buffer_data[18];
            retInfo.height = (buffer_data[25] * 256 * 256 * 256) + (buffer_data[24] * 256 * 256) + (buffer_data[23] * 256) + buffer_data[22];
        } // Endif.

        retInfo.image = file_path;
        if (!retInfo.type) {
            retInfo.type = 'unknown';
        } // Endif.

        if (callback_data) {
            callback_data(retInfo);
        } // Endif.

        return retInfo;
    };

    function getSVGImageSize(data) {
        var retInfo = {};

        retInfo.type = 'svg';
        retInfo.width = data.match(/<svg(.*?)width="(.*?)px/)[2];
        retInfo.height = data.match(/<svg(.*?)height="(.*?)px/)[2];
        return retInfo;
    }

    // Async mode:
    if (callback) {
        fs.exists(file_path, function (exists) {
            if (exists) {
                fs.open(file_path, "r", function (error, fd) {
                    var bufferSize = fs.fstatSync(fd).size;
                    var buffer = new Buffer(bufferSize);
                    fs.read(fd, buffer, 0, bufferSize, null, function (error, bytesRead, buffer) {
                        fs.close(fd);
                        parseHeaderData(buffer, callback);
                    });
                });

            } else {
                throw 'Error: Invalid file name.';
            } // Endif.
        });

        // Sync mode:
    } else {

        if(!fs.existsSync(file_path)){
            console.log(file_path + ' not exist');
            return;
        }

        if(file_path.indexOf('.svg') > -1){
            var fd = fs.openSync(file_path, "r");
            var bufferSize = fs.fstatSync(fd).size;
            var buffer = new Buffer(bufferSize);
            var bytesRead = fs.readSync(fd, buffer, 0, bufferSize, 0);
            fs.closeSync(fd);
            return getSVGImageSize(buffer.toString(),null);
        }else{
            var fd = fs.openSync(file_path, "r");
            var bufferSize = fs.fstatSync(fd).size;
            var buffer = new Buffer(bufferSize);
            var bytesRead = fs.readSync(fd, buffer, 0, bufferSize, 0);
            fs.closeSync(fd);
            return parseHeaderData(buffer, null);
        }

    } // Endif.
};

<commit_msg>提交一个svg bug修改<commit_after>//
// fast-image-size - Simple stand alone module to just extract the image size from image file without using special image libraries.
//
// Please refer to README.md for this module's documentations.
//
// NOTE:
// - Before changing this code please refer to the 'hacking the code section' on README.md.
//
// Copyright (c) 2013 Ziv Barber;
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// 'Software'), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

var fs = require('fs');
var path = require('path');

module.exports = exports = function (file_path, callback) {

    function getJpgSize(buffer_data, retInfo) {
        // Skip 5 chars, they are for signature
        buffer_data = buffer_data.slice(4);

        var i, next;
        while (buffer_data.length) {
            // read length of the next block
            i = buffer_data.readUInt16BE(0);

            // 0xFFC0 is baseline(SOF)
            // 0xFFC2 is progressive(SOF2)
            next = buffer_data[i + 1];
            if (next === 0xC0 || next === 0xC2) {
                return {
                    'height': buffer_data.readUInt16BE(i + 5),
                    'width': buffer_data.readUInt16BE(i + 7)
                };
            }

            // move to the next block
            buffer_data = buffer_data.slice(i + 2);
        }
    }

    function parseHeaderData(buffer_data, callback_data) {
        var retInfo = {};

        // Detect GIF:
        if (buffer_data[0] == 0x47 && buffer_data[1] == 0x49 && buffer_data[2] == 0x46) {
            retInfo.type = 'gif';
            retInfo.width = (buffer_data[7] * 256) + buffer_data[6];
            retInfo.height = (buffer_data[9] * 256) + buffer_data[8];

            // Detect JPEG:
        } else if (buffer_data[0] == 0xFF && buffer_data[1] == 0xD8 && buffer_data[2] == 0xFF && (buffer_data[3] == 0xE0 || buffer_data[3] == 0xE1)) {
            retInfo.type = 'jpeg';
            var size = getJpgSize(buffer_data, retInfo);
            retInfo.width = size.width;
            retInfo.height = size.height;

            // Detect PNG:
        } else if (buffer_data[0] == 137 && buffer_data[1] == 80 && buffer_data[2] == 78 && buffer_data[3] == 71 && buffer_data[4] == 13 && buffer_data[5] == 10 && buffer_data[6] == 26 && buffer_data[7] == 10) {
            retInfo.type = 'png';

            if (buffer_data[12] == 0x49 && buffer_data[13] == 0x48 && buffer_data[14] == 0x44 && buffer_data[15] == 0x52) {
                retInfo.width = (buffer_data[16] * 256 * 256 * 256) + (buffer_data[17] * 256 * 256) + (buffer_data[18] * 256) + buffer_data[19];
                retInfo.height = (buffer_data[20] * 256 * 256 * 256) + (buffer_data[21] * 256 * 256) + (buffer_data[22] * 256) + buffer_data[23];
            } // Endif.

            // Detect BMP:
        } else if (buffer_data[0] == 0x42 && buffer_data[1] == 0x4D) {
            retInfo.type = 'bmp';
            retInfo.width = (buffer_data[21] * 256 * 256 * 256) + (buffer_data[20] * 256 * 256) + (buffer_data[19] * 256) + buffer_data[18];
            retInfo.height = (buffer_data[25] * 256 * 256 * 256) + (buffer_data[24] * 256 * 256) + (buffer_data[23] * 256) + buffer_data[22];
        } // Endif.

        retInfo.image = file_path;
        if (!retInfo.type) {
            retInfo.type = 'unknown';
        } // Endif.

        if (callback_data) {
            callback_data(retInfo);
        } // Endif.

        return retInfo;
    };

    function getSVGImageSize(data) {
        var retInfo = {};
        retInfo.width = 0;
        retInfo.height = 0;
        retInfo.type = 'svg';
        try{
            retInfo.width = data.match(/<svg(.*?)width=["|'](.*?)(px)?["|']/)[2];
            retInfo.height = data.match(/<svg(.*?)height=["|'](.*?)(px)?["|']/)[2];
        }catch(e){

        }
        return retInfo;
    }

    // Async mode:
    if (callback) {
        fs.exists(file_path, function (exists) {
            if (exists) {
                fs.open(file_path, "r", function (error, fd) {
                    var bufferSize = fs.fstatSync(fd).size;
                    var buffer = new Buffer(bufferSize);
                    fs.read(fd, buffer, 0, bufferSize, null, function (error, bytesRead, buffer) {
                        fs.close(fd);
                        parseHeaderData(buffer, callback);
                    });
                });

            } else {
                throw 'Error: Invalid file name.';
            } // Endif.
        });

        // Sync mode:
    } else {

        if(!fs.existsSync(file_path)){
            console.log(file_path + ' not exist');
            return;
        }

        if(file_path.indexOf('.svg') > -1){
            var fd = fs.openSync(file_path, "r");
            var bufferSize = fs.fstatSync(fd).size;
            var buffer = new Buffer(bufferSize);
            var bytesRead = fs.readSync(fd, buffer, 0, bufferSize, 0);
            fs.closeSync(fd);
            return getSVGImageSize(buffer.toString(),null);
        }else{
            var fd = fs.openSync(file_path, "r");
            var bufferSize = fs.fstatSync(fd).size;
            var buffer = new Buffer(bufferSize);
            var bytesRead = fs.readSync(fd, buffer, 0, bufferSize, 0);
            fs.closeSync(fd);
            return parseHeaderData(buffer, null);
        }

    } // Endif.
};

<|endoftext|>


<commit_before>var strRepeat = require('./util').strRepeat
var indentWidth = require('./config').indentWidth
var getIndent = require('./getIndent')
var formatAtRuleParams = require('./formatAtRuleParams')
var formatDecls = require('./formatDecls')

function formatAtRules (root) {
  root.walkAtRules(function (atrule, index) {
    var parentType = atrule.parent.type
    var atruleBefore
    var atruleAfter

    var hasComment = false
    var prev = atrule.prev()
    if (prev && prev.type === 'comment') {
      hasComment = true
    }

    var params = formatAtRuleParams(atrule)
    atrule.params = params

    atrule.lastEach++

    if (index === 0 && parentType === 'root') {
      atruleBefore = ''
    } else {
      if (parentType === 'atrule') {
        if (atrule.parent.first === atrule) {
          atruleBefore = '\n' + getIndent(atrule)
        } else {
          atruleBefore = '\n\n' + getIndent(atrule)
        }
      }
      if (parentType === 'rule') {
        atruleBefore = '\n\n' + getIndent(atrule)
      }

      if (parentType === 'root') {
        atruleBefore = '\n\n' + getIndent(atrule)
      }

      if (hasComment) {
        atruleBefore = '\n' + getIndent(atrule)
      }
    }

    atrule.raws.before = atruleBefore
    atrule.raws.after = '\n' + getIndent(atrule)
    atrule.raws.between = ' '
    atrule.raws.semicolon = true
    atrule.raws.afterName = ' '

    if (atrule.name === 'font-face') {
      atrule.raws.afterName = ''
      formatDecls(atrule)
    }

    if (atrule.name === 'mixin') {
      atrule.params = atrule.params.replace(/(^[A-Za-z0-9]+)\s*\(/, "$1 (")
    }

    if (atrule.name === 'extend') {
      atrule.raws.before = '\n' + getIndent(atrule)
      atrule.raws.between = ''
    }

    if (atrule.name === 'include') {
      atrule.raws.before = '\n' + getIndent(atrule)
      atrule.raws.between = ''
    }

    if (atrule.name === 'function') {
      atrule.raws.before = getIndent(atrule)
      atrule.raws.between = ' '
    }
  })

  return root
}

module.exports = formatAtRules
<commit_msg>remove variables are not using<commit_after>var formatAtRuleParams = require('./formatAtRuleParams')
var formatDecls = require('./formatDecls')
var getIndent = require('./getIndent')

function formatAtRules (root) {
  root.walkAtRules(function (atrule, index) {
    var parentType = atrule.parent.type
    var atruleBefore
    var atruleAfter

    var hasComment = false
    var prev = atrule.prev()
    if (prev && prev.type === 'comment') {
      hasComment = true
    }

    var params = formatAtRuleParams(atrule)
    atrule.params = params

    atrule.lastEach++

    if (index === 0 && parentType === 'root') {
      atruleBefore = ''
    } else {
      if (parentType === 'atrule') {
        if (atrule.parent.first === atrule) {
          atruleBefore = '\n' + getIndent(atrule)
        } else {
          atruleBefore = '\n\n' + getIndent(atrule)
        }
      }
      if (parentType === 'rule') {
        atruleBefore = '\n\n' + getIndent(atrule)
      }

      if (parentType === 'root') {
        atruleBefore = '\n\n' + getIndent(atrule)
      }

      if (hasComment) {
        atruleBefore = '\n' + getIndent(atrule)
      }
    }

    atrule.raws.before = atruleBefore
    atrule.raws.after = '\n' + getIndent(atrule)
    atrule.raws.between = ' '
    atrule.raws.semicolon = true
    atrule.raws.afterName = ' '

    if (atrule.name === 'font-face') {
      atrule.raws.afterName = ''
      formatDecls(atrule)
    }

    if (atrule.name === 'mixin') {
      atrule.params = atrule.params.replace(/(^[A-Za-z0-9]+)\s*\(/, "$1 (")
    }

    if (atrule.name === 'extend') {
      atrule.raws.before = '\n' + getIndent(atrule)
      atrule.raws.between = ''
    }

    if (atrule.name === 'include') {
      atrule.raws.before = '\n' + getIndent(atrule)
      atrule.raws.between = ''
    }

    if (atrule.name === 'function') {
      atrule.raws.before = getIndent(atrule)
      atrule.raws.between = ' '
    }
  })

  return root
}

module.exports = formatAtRules
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
var passport = require('passport')
var co = require('co')

/**
 * Passport's default/connect middleware.
 */
var _initialize   = require('passport/lib/middleware/initialize')
var _authenticate = require('passport/lib/middleware/authenticate')

/**
 * Passport's initialization middleware for Koa.
 *
 * @return {GeneratorFunction}
 * @api private
 */
function initialize(passport) {
  var middleware = _initialize(passport)
  return function* passportInitialize(next) {
    var ctx = this

    // koa <-> connect compatibility:
    this.passport = {}
    var userProperty = passport._userProperty || 'user'
    // check ctx.req has the userProperty
    if (!ctx.req.hasOwnProperty(userProperty)) {
      Object.defineProperty(ctx.req, userProperty, {
        enumerable: true,
        get: function() {
          return ctx.passport[userProperty]
        },
        set: function(val) {
          ctx.passport[userProperty] = val
        }
      })
    }

    var req = createReqMock(ctx)

    // add aliases for passport's request extensions to Koa's context
    var login  = ctx.req.login
    var logout = ctx.req.logout

    ctx.login = ctx.logIn = function(user, options) {
      return login.bind(req, user, options)
    }
    ctx.req.login = ctx.req.logIn = login.bind(req)
    ctx.logout = ctx.logOut = ctx.req.logout = ctx.req.logOut = logout.bind(req)
    ctx.isAuthenticated     = ctx.req.isAuthenticated   = ctx.req.isAuthenticated.bind(req)
    ctx.isUnauthenticated   = ctx.req.isUnauthenticated = ctx.req.isUnauthenticated.bind(req)

    yield middleware.bind(middleware, req, ctx)
    yield next
  }
}

/**
 * Passport's authenticate middleware for Koa.
 *
 * @param {String|Array} name
 * @param {Object} options
 * @param {GeneratorFunction} callback
 * @return {GeneratorFunction}
 * @api private
 */
function authenticate(passport, name, options, callback) {
  // normalize arguments
  if (typeof options === 'function') {
    callback = options
    options  = {}
  }
  options = options || {}

  if (callback) {
    if (callback.constructor.name !== 'GeneratorFunction') {
      throw TypeError('Your custom authentication callback must be a Generator Function')
    }

    // When the callback is set, neither `next`, `res.redirect` or `res.end`
    // are called. That is, a workaround to catch the `callback` is required.
    // The `passportAuthenticate()` method below will therefore set
    // `callback.done`. Then, once the authentication finishes, the modified
    // callback yields the original one and afterwards triggers `callback.done`
    // to inform `passportAuthenticate()` that we are ready.
    var _callback = callback
    callback = co.wrap(function*(err, user, info, status) {
      yield _callback(err, user, info, status)
      callback.done(null, false)
    })
  }

  var middleware = _authenticate(passport, name, options, callback)
  return function* passportAuthenticate(next) {
    var ctx = this

    // this functions wraps the connect middleware
    // to catch `next`, `res.redirect` and `res.end` calls
    var cont = yield function(done) {
      // mock the `req` object
      var req = createReqMock(ctx)

      // mock the `res` object
      var res = {
        redirect: function(url) {
          ctx.redirect(url)
          done(null, false)
        },
        setHeader: ctx.set.bind(ctx),
        end: function(content) {
          if (content) ctx.body = content
          done(null, false)
        },
        set statusCode(status) {
          ctx.status = status
        },
        get statusCode() {
          return ctx.status
        }
      }

      if (callback) {
        callback.done = done
      }

      // call the connect middleware
      middleware(req, res, done)
    }

    // cont equals `false` when `res.redirect` or `res.end` got called
    // in this case, yield next to continue through Koa's middleware stack
    if (cont !== false) {
      yield next
    }
  }
}

/**
 * Framework support for Koa.
 *
 * This module provides support for using Passport with Koa. It exposes
 * middleware that conform to the `fn*(next)` signature and extends
 * Node's built-in HTTP request object with useful authentication-related
 * functions.
 *
 * @return {Object}
 * @api protected
 */
module.exports = function() {
  return {
    initialize: initialize,
    authenticate: authenticate
  }
}

// create request mock
var properties = require('./request')
function createReqMock(ctx) {
  var req = Object.create(ctx.request, properties)
  return req
}
<commit_msg>authenticate callback error handling fixed<commit_after>/**
 * Module dependencies.
 */
var passport = require('passport')
var co = require('co')

/**
 * Passport's default/connect middleware.
 */
var _initialize   = require('passport/lib/middleware/initialize')
var _authenticate = require('passport/lib/middleware/authenticate')

/**
 * Passport's initialization middleware for Koa.
 *
 * @return {GeneratorFunction}
 * @api private
 */
function initialize(passport) {
  var middleware = _initialize(passport)
  return function* passportInitialize(next) {
    var ctx = this

    // koa <-> connect compatibility:
    this.passport = {}
    var userProperty = passport._userProperty || 'user'
    // check ctx.req has the userProperty
    if (!ctx.req.hasOwnProperty(userProperty)) {
      Object.defineProperty(ctx.req, userProperty, {
        enumerable: true,
        get: function() {
          return ctx.passport[userProperty]
        },
        set: function(val) {
          ctx.passport[userProperty] = val
        }
      })
    }

    var req = createReqMock(ctx)

    // add aliases for passport's request extensions to Koa's context
    var login  = ctx.req.login
    var logout = ctx.req.logout

    ctx.login = ctx.logIn = function(user, options) {
      return login.bind(req, user, options)
    }
    ctx.req.login = ctx.req.logIn = login.bind(req)
    ctx.logout = ctx.logOut = ctx.req.logout = ctx.req.logOut = logout.bind(req)
    ctx.isAuthenticated     = ctx.req.isAuthenticated   = ctx.req.isAuthenticated.bind(req)
    ctx.isUnauthenticated   = ctx.req.isUnauthenticated = ctx.req.isUnauthenticated.bind(req)

    yield middleware.bind(middleware, req, ctx)
    yield next
  }
}

/**
 * Passport's authenticate middleware for Koa.
 *
 * @param {String|Array} name
 * @param {Object} options
 * @param {GeneratorFunction} callback
 * @return {GeneratorFunction}
 * @api private
 */
function authenticate(passport, name, options, callback) {
  // normalize arguments
  if (typeof options === 'function') {
    callback = options
    options  = {}
  }
  options = options || {}

  if (callback) {
    if (callback.constructor.name !== 'GeneratorFunction') {
      throw TypeError('Your custom authentication callback must be a Generator Function')
    }

    // When the callback is set, neither `next`, `res.redirect` or `res.end`
    // are called. That is, a workaround to catch the `callback` is required.
    // The `passportAuthenticate()` method below will therefore set
    // `callback.done`. Then, once the authentication finishes, the modified
    // callback yields the original one and afterwards triggers `callback.done`
    // to inform `passportAuthenticate()` that we are ready.
    var _callback = callback
    callback = co.wrap(function*(err, user, info, status) {
      try {
        yield _callback(err, user, info, status)
        callback.done(null, false)
      } catch (err) {
        callback.done(err);
      }
    })
  }

  var middleware = _authenticate(passport, name, options, callback)
  return function* passportAuthenticate(next) {
    var ctx = this

    // this functions wraps the connect middleware
    // to catch `next`, `res.redirect` and `res.end` calls
    var cont = yield function(done) {
      // mock the `req` object
      var req = createReqMock(ctx)

      // mock the `res` object
      var res = {
        redirect: function(url) {
          ctx.redirect(url)
          done(null, false)
        },
        setHeader: ctx.set.bind(ctx),
        end: function(content) {
          if (content) ctx.body = content
          done(null, false)
        },
        set statusCode(status) {
          ctx.status = status
        },
        get statusCode() {
          return ctx.status
        }
      }

      if (callback) {
        callback.done = done
      }

      // call the connect middleware
      middleware(req, res, done)
    }

    // cont equals `false` when `res.redirect` or `res.end` got called
    // in this case, yield next to continue through Koa's middleware stack
    if (cont !== false) {
      yield next
    }
  }
}

/**
 * Framework support for Koa.
 *
 * This module provides support for using Passport with Koa. It exposes
 * middleware that conform to the `fn*(next)` signature and extends
 * Node's built-in HTTP request object with useful authentication-related
 * functions.
 *
 * @return {Object}
 * @api protected
 */
module.exports = function() {
  return {
    initialize: initialize,
    authenticate: authenticate
  }
}

// create request mock
var properties = require('./request')
function createReqMock(ctx) {
  var req = Object.create(ctx.request, properties)
  return req
}
<|endoftext|>


<commit_before>

//////////////////////////////////////////////////////////////////////////////
/**
 * @module geo
 */
//////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////
/**
 * Create a new instance of class sliderWidget
 *
 * @class
 * @returns {geo.sliderWidget}
 */
//////////////////////////////////////////////////////////////////////////////
geo.sliderWidget = function (arg) {
  'use strict';
  if (!(this instanceof geo.sliderWidget)) {
    return new geo.sliderWidget(arg);
  }
  geo.widget.call(this, arg);

  var m_this = this,
      m_xscale,
      m_yscale,
      m_plus,
      m_minus,
      m_track,
      m_nub,
      m_width = 20, // Approximate size of the widget in pixels
      m_height = 100,
      m_nubSize = 6,
      m_plusIcon,
      m_minusIcon,
      m_group;

  /* http://icomoon.io */
  /* CC BY 3.0 http://creativecommons.org/licenses/by/3.0/ */
  /* jshint -W101 */
  m_plusIcon = 'M512 81.92c-237.568 0-430.080 192.614-430.080 430.080 0 237.568 192.563 430.080 430.080 430.080s430.080-192.563 430.080-430.080c0-237.517-192.563-430.080-430.080-430.080zM564.326 564.326v206.182h-104.653v-206.182h-206.234v-104.653h206.182v-206.234h104.704v206.182h206.182v104.704h-206.182z';
  m_minusIcon = 'M512 81.92c-237.568 0-430.080 192.614-430.080 430.080 0 237.568 192.563 430.080 430.080 430.080s430.080-192.563 430.080-430.080c0-237.517-192.563-430.080-430.080-430.080zM770.56 459.674v104.704h-517.12v-104.704h517.12z';
  /* jshint +W101 */

//////////////////////////////////////////////////////////////////////////////
/**
 * Add an icon from a path string.
 *
 * @function
 * @argument {String} icon svg path string
 * @argument {d3 selection} base where to append the element
 * @argument {Number} cx Center x-coordinate
 * @argument {Number} cy Center y-coordinate
 * @argument {Number} size Icon size in pixels
 * @returns {d3 group element}
 * @private
 */
//////////////////////////////////////////////////////////////////////////////
  function put_icon(icon, base, cx, cy, size) {
    var g = base.append('g');

    // the scale factor
    var s = size / 1024;

    g.append('g')
      .append('g')
        .attr(
          'transform',
          'translate(' + cx + ',' + cy + ') scale(' + s + ') translate(-512,-512)'
      )
      .append('path')
        .attr('d', icon)
        .attr('class', 'geo-glyphicon');

    return g;
  }

//////////////////////////////////////////////////////////////////////////////
/**
 * Initialize the slider widget in the map.
 *
 * @function
 * @returns {geo.sliderWidget}
 * @private
 */
//////////////////////////////////////////////////////////////////////////////
  this._init = function () {
    var svg = m_this.layer().renderer().canvas(),
        x0 = 40,
        y0 = 40 + m_width,
        map = m_this.layer().map(),
        main = svg;

    // create d3 scales for positioning
    // TODO: make customizable and responsive
    m_xscale = d3.scale.linear().domain([-4, 4]).range([x0, x0 + m_width]);
    m_yscale = d3.scale.linear().domain([0, 1]).range([y0, y0 + m_height]);

    // Add a background
    var back = svg
      .append('rect')
        .attr('rx', 20)
        .attr('ry', 20)
        .style('fill', 'gray')
        .style('fill-opacity', 1)
        .attr('filter', 'url(#geo-blur)');

    // Create the main group element
    svg = svg.append('g').classed('geo-ui-slider', true);
    m_group = svg;

    // Create + zoom button
    m_plus = svg.append('g');
    m_plus.append('circle')
      .classed('geo-zoom-in', true)
      .attr('cx', m_xscale(0))
      .attr('cy', m_yscale(0.0) - m_width + 2)
      .attr('r', m_width / 2)
      .style({
        'fill': 'white',
        'cursor': 'pointer'
      })
      .on('click', function () {
        var z = map.zoom();
        map.zoom(z + 1);
      })
      .on('mousedown', function () {
        d3.event.stopPropagation();
      });

    put_icon(
      m_plusIcon,
      m_plus,
      m_xscale(0),
      m_yscale(0) - m_width + 2,
      m_width + 5
    ).style('cursor', 'pointer')
      .style('pointer-events', 'none');

    // Create the - zoom button
    m_minus = svg.append('g');
    m_minus.append('circle')
      .classed('geo-zoom-out', true)
      .attr('cx', m_xscale(0))
      .attr('cy', m_yscale(1.0) + m_width - 2)
      .attr('r', m_width / 2)
      .style({
        'fill': 'white',
        'cursor': 'pointer'
      })
      .on('click', function () {
        var z = map.zoom();
        map.zoom(z - 1);
      })
      .on('mousedown', function () {
        d3.event.stopPropagation();
      });

    put_icon(
      m_minusIcon,
      m_minus,
      m_xscale(0),
      m_yscale(1) + m_width - 2,
      m_width + 5
    ).style('cursor', 'pointer')
      .style('pointer-events', 'none');

    // Respond to a mouse event on the widget
    function respond(evt) {
      var z = m_yscale.invert(d3.mouse(m_this.layer().node()[0])[1]),
          zrange = map.zoomRange();
      z = (1 - z) * (zrange.max - zrange.min) + zrange.min;
      map.zoom(z);
      m_this._update();
      evt.stopPropagation();
    }

    // Create the track
    m_track = svg.append('rect')
      .classed('geo-zoom-track', true)
      .attr('x', m_xscale(0) - m_width / 10)
      .attr('y', m_yscale(0))
      .attr('rx', m_width / 10)
      .attr('ry', m_width / 10)
      .attr('width', m_width / 5)
      .attr('height', m_height)
      .style({
        'fill': 'white',
        'stroke': 'black',
        'cursor': 'pointer'
      })
      .on('click', function () {
        respond(d3.event);
      });

    // Create the nub
    m_nub = svg.append('rect')
      .classed('geo-zoom-nub', true)
      .attr('x', m_xscale(-4))
      .attr('y', m_yscale(0.5) - m_nubSize / 2)
      .attr('rx', 3)
      .attr('ry', 3)
      .attr('width', m_width)
      .attr('height', m_nubSize)
      .style({
        'fill': 'black',
        'cursor': 'pointer'
      })
      .on('mousedown', function () {
        d3.select(document).on('mousemove.geo.slider', function () {
          respond(d3.event);
        });
        d3.select(document).on('mouseup.geo.slider', function () {
          respond(d3.event);
          d3.select(document).on('.geo.slider', null);
        });
        d3.event.stopPropagation();
      });

    // Get the bounding box to size a background
    // rectangle for the widget.
    var bbox = svg.node().getBBox();
    back.attr('width', bbox.width + 20)
      .attr('height', bbox.height + 20)
      .attr('x', bbox.x - 10)
      .attr('y', bbox.y - 10)
      .style('opacity', 1e-6);
    main
      .on('mouseenter', function () {
        back.style('opacity', 1);
      })
      .on('mouseleave', function () {
        back.style('opacity', 1e-6);
      });

    // Apply a highlight effect
    svg.selectAll('*')
      .on('mouseover', function () {
        d3.select(this).attr('filter', 'url(#geo-highlight)');
      })
      .on('mouseout', function () {
        d3.select(this).attr('filter', null);
      });

    // Update the nub position on zoom
    m_this.layer().geoOn(geo.event.zoom, function () {
      m_this._update();
    });

    m_this._update();
  };

//////////////////////////////////////////////////////////////////////////////
/**
 * Removes the slider element from the map and unbinds all handlers.
 *
 * @function
 * @returns {geo.sliderWidget}
 * @private
 */
//////////////////////////////////////////////////////////////////////////////
  this._exit = function () {
    m_group.remove();
    m_this.layer().geoOff(geo.event.zoom);
  };

//////////////////////////////////////////////////////////////////////////////
/**
 * Update the slider widget state in reponse to map changes.  I.e. zoom
 * range changes.
 *
 * @function
 * @returns {geo.sliderWidget}
 * @private
 */
//////////////////////////////////////////////////////////////////////////////
  this._update = function (obj) {
    var map = m_this.layer().map(),
        zoomRange = map.zoomRange(),
        zoom = map.zoom(),
        zoomScale = d3.scale.linear();

    obj = obj || {};
    zoom = obj.value || zoom;
    zoomScale.domain([zoomRange.min, zoomRange.max])
      .range([1, 0])
      .clamp(true);

    m_nub.attr('y', m_yscale(zoomScale(zoom)) - m_nubSize / 2);
  };
};

inherit(geo.sliderWidget, geo.widget);

geo.registerWidget('d3', 'slider', geo.sliderWidget);
<commit_msg>Remove slider background<commit_after>

//////////////////////////////////////////////////////////////////////////////
/**
 * @module geo
 */
//////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////
/**
 * Create a new instance of class sliderWidget
 *
 * @class
 * @returns {geo.sliderWidget}
 */
//////////////////////////////////////////////////////////////////////////////
geo.sliderWidget = function (arg) {
  'use strict';
  if (!(this instanceof geo.sliderWidget)) {
    return new geo.sliderWidget(arg);
  }
  geo.widget.call(this, arg);

  var m_this = this,
      m_xscale,
      m_yscale,
      m_plus,
      m_minus,
      m_track,
      m_nub,
      m_width = 20, // Approximate size of the widget in pixels
      m_height = 100,
      m_nubSize = 6,
      m_plusIcon,
      m_minusIcon,
      m_group;

  /* http://icomoon.io */
  /* CC BY 3.0 http://creativecommons.org/licenses/by/3.0/ */
  /* jshint -W101 */
  m_plusIcon = 'M512 81.92c-237.568 0-430.080 192.614-430.080 430.080 0 237.568 192.563 430.080 430.080 430.080s430.080-192.563 430.080-430.080c0-237.517-192.563-430.080-430.080-430.080zM564.326 564.326v206.182h-104.653v-206.182h-206.234v-104.653h206.182v-206.234h104.704v206.182h206.182v104.704h-206.182z';
  m_minusIcon = 'M512 81.92c-237.568 0-430.080 192.614-430.080 430.080 0 237.568 192.563 430.080 430.080 430.080s430.080-192.563 430.080-430.080c0-237.517-192.563-430.080-430.080-430.080zM770.56 459.674v104.704h-517.12v-104.704h517.12z';
  /* jshint +W101 */

//////////////////////////////////////////////////////////////////////////////
/**
 * Add an icon from a path string.
 *
 * @function
 * @argument {String} icon svg path string
 * @argument {d3 selection} base where to append the element
 * @argument {Number} cx Center x-coordinate
 * @argument {Number} cy Center y-coordinate
 * @argument {Number} size Icon size in pixels
 * @returns {d3 group element}
 * @private
 */
//////////////////////////////////////////////////////////////////////////////
  function put_icon(icon, base, cx, cy, size) {
    var g = base.append('g');

    // the scale factor
    var s = size / 1024;

    g.append('g')
      .append('g')
        .attr(
          'transform',
          'translate(' + cx + ',' + cy + ') scale(' + s + ') translate(-512,-512)'
      )
      .append('path')
        .attr('d', icon)
        .attr('class', 'geo-glyphicon');

    return g;
  }

//////////////////////////////////////////////////////////////////////////////
/**
 * Initialize the slider widget in the map.
 *
 * @function
 * @returns {geo.sliderWidget}
 * @private
 */
//////////////////////////////////////////////////////////////////////////////
  this._init = function () {
    var svg = m_this.layer().renderer().canvas(),
        x0 = 40,
        y0 = 40 + m_width,
        map = m_this.layer().map();

    // create d3 scales for positioning
    // TODO: make customizable and responsive
    m_xscale = d3.scale.linear().domain([-4, 4]).range([x0, x0 + m_width]);
    m_yscale = d3.scale.linear().domain([0, 1]).range([y0, y0 + m_height]);

    // Create the main group element
    svg = svg.append('g').classed('geo-ui-slider', true);
    m_group = svg;

    // Create + zoom button
    m_plus = svg.append('g');
    m_plus.append('circle')
      .classed('geo-zoom-in', true)
      .attr('cx', m_xscale(0))
      .attr('cy', m_yscale(0.0) - m_width + 2)
      .attr('r', m_width / 2)
      .style({
        'fill': 'white',
        'cursor': 'pointer'
      })
      .on('click', function () {
        var z = map.zoom();
        map.zoom(z + 1);
      })
      .on('mousedown', function () {
        d3.event.stopPropagation();
      });

    put_icon(
      m_plusIcon,
      m_plus,
      m_xscale(0),
      m_yscale(0) - m_width + 2,
      m_width + 5
    ).style('cursor', 'pointer')
      .style('pointer-events', 'none');

    // Create the - zoom button
    m_minus = svg.append('g');
    m_minus.append('circle')
      .classed('geo-zoom-out', true)
      .attr('cx', m_xscale(0))
      .attr('cy', m_yscale(1.0) + m_width - 2)
      .attr('r', m_width / 2)
      .style({
        'fill': 'white',
        'cursor': 'pointer'
      })
      .on('click', function () {
        var z = map.zoom();
        map.zoom(z - 1);
      })
      .on('mousedown', function () {
        d3.event.stopPropagation();
      });

    put_icon(
      m_minusIcon,
      m_minus,
      m_xscale(0),
      m_yscale(1) + m_width - 2,
      m_width + 5
    ).style('cursor', 'pointer')
      .style('pointer-events', 'none');

    // Respond to a mouse event on the widget
    function respond(evt) {
      var z = m_yscale.invert(d3.mouse(m_this.layer().node()[0])[1]),
          zrange = map.zoomRange();
      z = (1 - z) * (zrange.max - zrange.min) + zrange.min;
      map.zoom(z);
      m_this._update();
      evt.stopPropagation();
    }

    // Create the track
    m_track = svg.append('rect')
      .classed('geo-zoom-track', true)
      .attr('x', m_xscale(0) - m_width / 10)
      .attr('y', m_yscale(0))
      .attr('rx', m_width / 10)
      .attr('ry', m_width / 10)
      .attr('width', m_width / 5)
      .attr('height', m_height)
      .style({
        'fill': 'white',
        'stroke': 'black',
        'cursor': 'pointer'
      })
      .on('click', function () {
        respond(d3.event);
      });

    // Create the nub
    m_nub = svg.append('rect')
      .classed('geo-zoom-nub', true)
      .attr('x', m_xscale(-4))
      .attr('y', m_yscale(0.5) - m_nubSize / 2)
      .attr('rx', 3)
      .attr('ry', 3)
      .attr('width', m_width)
      .attr('height', m_nubSize)
      .style({
        'fill': 'black',
        'cursor': 'pointer'
      })
      .on('mousedown', function () {
        d3.select(document).on('mousemove.geo.slider', function () {
          respond(d3.event);
        });
        d3.select(document).on('mouseup.geo.slider', function () {
          respond(d3.event);
          d3.select(document).on('.geo.slider', null);
        });
        d3.event.stopPropagation();
      });

    // Apply a highlight effect
    svg.selectAll('*')
      .on('mouseover', function () {
        d3.select(this).attr('filter', 'url(#geo-highlight)');
      })
      .on('mouseout', function () {
        d3.select(this).attr('filter', null);
      });

    // Update the nub position on zoom
    m_this.layer().geoOn(geo.event.zoom, function () {
      m_this._update();
    });

    m_this._update();
  };

//////////////////////////////////////////////////////////////////////////////
/**
 * Removes the slider element from the map and unbinds all handlers.
 *
 * @function
 * @returns {geo.sliderWidget}
 * @private
 */
//////////////////////////////////////////////////////////////////////////////
  this._exit = function () {
    m_group.remove();
    m_this.layer().geoOff(geo.event.zoom);
  };

//////////////////////////////////////////////////////////////////////////////
/**
 * Update the slider widget state in reponse to map changes.  I.e. zoom
 * range changes.
 *
 * @function
 * @returns {geo.sliderWidget}
 * @private
 */
//////////////////////////////////////////////////////////////////////////////
  this._update = function (obj) {
    var map = m_this.layer().map(),
        zoomRange = map.zoomRange(),
        zoom = map.zoom(),
        zoomScale = d3.scale.linear();

    obj = obj || {};
    zoom = obj.value || zoom;
    zoomScale.domain([zoomRange.min, zoomRange.max])
      .range([1, 0])
      .clamp(true);

    m_nub.attr('y', m_yscale(zoomScale(zoom)) - m_nubSize / 2);
  };
};

inherit(geo.sliderWidget, geo.widget);

geo.registerWidget('d3', 'slider', geo.sliderWidget);
<|endoftext|>


<commit_before>/**
 * @fileoverview Description of this file.
 */
var todoTrackerApp=angular.module("todoTrackerApp", []);
todoTrackerApp.controller("listBranches", function($scope,$http) {
  // $http.get(window.location.protocol + "//" + window.location.host + "/zz_list_branches_json.html")
  $http.get(window.location.protocol + "//" + window.location.host + "/aliases")
    .success(function(response) {$scope.repositories = processBranchListResponse(response);});
});

function processBranchListResponse(response) {
  // alert("response = " + response);
  // var branchesStrObj = JSON.parse(response);
  var branchesStrObj = response;
  var reposRaw = {};

  for (var i = 0; i < branchesStrObj.length; i++) {
    var oneBranchRaw = branchesStrObj[i];
    console.log("branch = " + oneBranchRaw.Branch);
    var result = parseBranchName(oneBranchRaw.Branch);
    // TODO: add lastModified and lastModifiedBy fields
    var branch = new Branch(result[1], oneBranchRaw.Revision, "", "");
    if (!(result[0] in reposRaw)) {
      reposRaw[result[0]] = [];
    }
    reposRaw[result[0]].push(branch);
  }

  var repos = [];
  for (var r in reposRaw) {
    var repo = new Repository(r);
    repo.branches = reposRaw[r];
    repos.push(repo);
  }

  function Repository(repository) {
    this.repository = repository;
    this.branches = [];
  }

  function Branch(branch, revision, lastModified, lastModifiedBy) {
    this.branch = branch;
    this.revision = revision;
    this.lastModified = lastModified;
    this.lastModifiedBy = lastModifiedBy;
  }

  function parseBranchName(branchName) {
    var result = branchName.split("/");
    if (result.length == 3) {
      return [result[0], result[2]];
    } else {
      return ['local', result[0]];
    }
  }

  console.log("final repos = " + JSON.stringify(repos));
  return repos;
}
<commit_msg>commit before merge from master, no important change<commit_after>/**
 * @fileoverview Description of this file.
 */
var todoTrackerApp=angular.module("todoTrackerApp", []);
todoTrackerApp.controller("listBranches", function($scope,$http) {
  // $http.get(window.location.protocol + "//" + window.location.host + "/zz_list_branches_json.html")
  $http.get(window.location.protocol + "//" + window.location.host + "/aliases")
    .success(function(response) {$scope.repositories = processBranchListResponse(response);});
});

function processBranchListResponse(response) {
  var branchesStrObj = response;
  var reposRaw = {};

  for (var i = 0; i < branchesStrObj.length; i++) {
    var oneBranchRaw = branchesStrObj[i];
    console.log("branch = " + oneBranchRaw.Branch);
    var result = parseBranchName(oneBranchRaw.Branch);
    // TODO: add lastModified and lastModifiedBy fields
    var branch = new Branch(result[1], oneBranchRaw.Revision, "", "");
    if (!(result[0] in reposRaw)) {
      reposRaw[result[0]] = [];
    }
    reposRaw[result[0]].push(branch);
  }

  var repos = [];
  for (var r in reposRaw) {
    var repo = new Repository(r);
    repo.branches = reposRaw[r];
    repos.push(repo);
  }

  function Repository(repository) {
    this.repository = repository;
    this.branches = [];
  }

  function Branch(branch, revision, lastModified, lastModifiedBy) {
    this.branch = branch;
    this.revision = revision;
    this.lastModified = lastModified;
    this.lastModifiedBy = lastModifiedBy;
  }

  function parseBranchName(branchName) {
    var result = branchName.split("/");
    if (result.length == 3) {
      return [result[0], result[2]];
    } else {
      return ['local', result[0]];
    }
  }

  console.log("final repos = " + JSON.stringify(repos));
  return repos;
}

/*
todoTrackerApp.controller("viewBranch", function($scope,$http) {
  $http.get(window.location.protocol + "//" + window.location.host + "/aliases")
    .success(function(response) {$scope.repositories = processBranchListResponse(response);});
});
*/
<|endoftext|>