<commit_before>$(window).resize(function () {
    //заради менюто което се премахва на малък екран
    setTimeout(function () {
        resizeCharts();
        resizeGrids();
    }
   , 1);

});

function resizeCharts() {
    var $kendoCharts = $(".k-chart").data("kendoChart");
    if ($kendoCharts) {
        $kendoCharts.refresh();
    }
}

function resizeGrids() {
    var grids = $(".k-grid table");
    if (grids) {
        grids.each(function (i) {
            var $tbody = $(this).find("tbody").first();
            if (!$tbody) {
                return;
            }
            if ($tbody.width() > $(this).parent().parent().width()) {
                if (!$(this).attr("style")) {
                    $(this).attr('style', 'overflow-x: auto !important; display: block !important;');
                }
            }
            else {
                if ($(this).attr("style")) {
                    $(this).removeAttr("style");
                }
            }
        }
        );
    }
}

$(window).ready(function myfunction() {
    //заради менюто което се премахва на малък екран. Важно е да е около 200, защото лявото меню се скрива след определено време и то трябва да мине за да се преначертае графиката отново
    setTimeout(function () {
        resizeCharts();
        resizeGrids();
    }
   , 200);

    $("div.hide-menu").click(function () {
        setTimeout(function () {
            resizeCharts();
            resizeGrids();
        }
       , 300); // важен е този timeout 300
    });

    var clipboard = new Clipboard('.fa-pencil-square');

    clipboard.on('success', function (e) {

        // Toastr options
        toastr.options = {
            "debug": false,
            "newestOnTop": false,
            "positionClass": "toast-top-center",
            "closeButton": true,
            "toastClass": "animated fadeInDown",
        };

        toastr.info('Copied to clipboard.');
        e.preventDefault();
        $("#iconSendEmail").click();

    });

    clipboard.on('error', function (e) {
    });

    var $ip = $("#ip");
    if ($ip.length != 0) {
        var arrOfPlaceholders = [];
        arrOfPlaceholders[0] = "google.com";
        arrOfPlaceholders[1] = "www.yahoo.com";
        arrOfPlaceholders[2] = "http://www.facebook.com";
        arrOfPlaceholders[3] = "ftp://ftp.microsoft.com/";
        arrOfPlaceholders[4] = "https://weather.com/en-GB";
        arrOfPlaceholders[5] = "8.8.8.8";
        arrOfPlaceholders[6] = "172.217.3.238";
        arrOfPlaceholders[7] = "https://en.wikipedia.org/wiki/Main_Page";
        arrOfPlaceholders[8] = "https://www.youtube.com/";
        arrOfPlaceholders[9] = "134.170.188.232";
        arrOfPlaceholders[10] = "216.58.212.142";

        for (var i = 0; i < arrOfPlaceholders.length * 1000; i++) {
            setTimeout(animateIpPlaceholder, 5000 * i, arrOfPlaceholders[i % arrOfPlaceholders.length]);
        }

    }
    // export pdf
    $(".pdfExportPage").click(function () {
        debugger;
        // Convert the DOM element to a drawing using kendo.drawing.drawDOM
        kendo.drawing.drawDOM($("#divBody"))
        .then(function (group) {
            // Render the result as a PDF file
            return kendo.drawing.exportPDF(group, {
                paperSize: "auto",
                margin: { left: "1cm", top: "1cm", right: "1cm", bottom: "1cm" }
            });
        })
        .done(function (data) {
            // Save the PDF file
            debugger;

            kendo.saveAs({
                dataURI: data,
                fileName: "ToolsForNet" + new Date().getDate() + ".pdf",
                proxyURL: window.location.origin + "/pdf/export"
            });
        });
    });

    //$("#pngExportPage").click(function () {
    //    // Convert the DOM element to a drawing using kendo.drawing.drawDOM
    //    kendo.drawing.drawDOM($("#divBody"))
    //    .then(function (group) {
    //        // Render the result as a PNG image
    //        return kendo.drawing.exportImage(group);
    //    })
    //    .done(function (data) {
    //        // Save the image file
    //        kendo.saveAs({
    //            dataURI: data,
    //            fileName: "ToolsForNet" + new Date().getDate() + ".png",
    //            proxyURL: "@Url.Action('Pdf', 'Export')"
    //        });
    //    });
    //});

    //$("#svgExportPage").click(function () {
    //    // Convert the DOM element to a drawing using kendo.drawing.drawDOM
    //    kendo.drawing.drawDOM($("#divBody"))
    //    .then(function (group) {
    //        // Render the result as a SVG document
    //        return kendo.drawing.exportSVG(group);
    //    })
    //    .done(function (data) {
    //        // Save the SVG document
    //        kendo.saveAs({
    //            dataURI: data,
    //            fileName: "ToolsForNet" + new Date().getDate() + ".svg",
    //            proxyURL: "@Url.Action('Pdf', 'Export')"
    //        });
    //    });
    //});

})

$.ajaxSetup({
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        // Toastr options
        toastr.options = {
            "debug": false,
            "newestOnTop": false,
            "positionClass": "toast-top-center",
            "closeButton": true,
            "toastClass": "animated fadeInDown",
        };
        var laddaButtons = $("[data-loading]");
        laddaButtons.ladda('stop');

        toastr.error('An error occured! Try again.');
    },
    success: function myfunction(event, xhr, settings) {
        alert(message);
    }
});

function animateIpPlaceholder(txt) {

    var timeOut;
    var txtLen = txt.length;
    var char = 0;
    var $ip = $("#ip");
    $ip.attr('placeholder', '|');
    (function typeIt() {
        var humanize = Math.round(Math.random() * (200 - 30)) + 30;
        timeOut = setTimeout(function () {
            var visible = vis(); // gives current state
            if (visible) {
                char++;
                var type = txt.substring(0, char);
                $ip.attr('placeholder', type + '|');
                typeIt();

                if (char == txtLen) {
                    $ip.attr('placeholder', $ip.attr('placeholder').slice(0, -1)) // remove the '|'
                    clearTimeout(timeOut);
                }
            }
            else {
                $ip.attr('placeholder', txt);
            }

        },
         humanize);
    })();
}

var vis = (function () {
    var stateKey, eventKey, keys = {
        hidden: "visibilitychange",
        webkitHidden: "webkitvisibilitychange",
        mozHidden: "mozvisibilitychange",
        msHidden: "msvisibilitychange"
    };
    for (stateKey in keys) {
        if (stateKey in document) {
            eventKey = keys[stateKey];
            break;
        }
    }
    return function (c) {
        if (c) document.addEventListener(eventKey, c);
        return !document[stateKey];
    }
})();

<commit_msg>"/export/pdf"<commit_after>$(window).resize(function () {
    //заради менюто което се премахва на малък екран
    setTimeout(function () {
        resizeCharts();
        resizeGrids();
    }
   , 1);

});

function resizeCharts() {
    var $kendoCharts = $(".k-chart").data("kendoChart");
    if ($kendoCharts) {
        $kendoCharts.refresh();
    }
}

function resizeGrids() {
    var grids = $(".k-grid table");
    if (grids) {
        grids.each(function (i) {
            var $tbody = $(this).find("tbody").first();
            if (!$tbody) {
                return;
            }
            if ($tbody.width() > $(this).parent().parent().width()) {
                if (!$(this).attr("style")) {
                    $(this).attr('style', 'overflow-x: auto !important; display: block !important;');
                }
            }
            else {
                if ($(this).attr("style")) {
                    $(this).removeAttr("style");
                }
            }
        }
        );
    }
}

$(window).ready(function myfunction() {
    //заради менюто което се премахва на малък екран. Важно е да е около 200, защото лявото меню се скрива след определено време и то трябва да мине за да се преначертае графиката отново
    setTimeout(function () {
        resizeCharts();
        resizeGrids();
    }
   , 200);

    $("div.hide-menu").click(function () {
        setTimeout(function () {
            resizeCharts();
            resizeGrids();
        }
       , 300); // важен е този timeout 300
    });

    var clipboard = new Clipboard('.fa-pencil-square');

    clipboard.on('success', function (e) {

        // Toastr options
        toastr.options = {
            "debug": false,
            "newestOnTop": false,
            "positionClass": "toast-top-center",
            "closeButton": true,
            "toastClass": "animated fadeInDown",
        };

        toastr.info('Copied to clipboard.');
        e.preventDefault();
        $("#iconSendEmail").click();

    });

    clipboard.on('error', function (e) {
    });

    var $ip = $("#ip");
    if ($ip.length != 0) {
        var arrOfPlaceholders = [];
        arrOfPlaceholders[0] = "google.com";
        arrOfPlaceholders[1] = "www.yahoo.com";
        arrOfPlaceholders[2] = "http://www.facebook.com";
        arrOfPlaceholders[3] = "ftp://ftp.microsoft.com/";
        arrOfPlaceholders[4] = "https://weather.com/en-GB";
        arrOfPlaceholders[5] = "8.8.8.8";
        arrOfPlaceholders[6] = "172.217.3.238";
        arrOfPlaceholders[7] = "https://en.wikipedia.org/wiki/Main_Page";
        arrOfPlaceholders[8] = "https://www.youtube.com/";
        arrOfPlaceholders[9] = "134.170.188.232";
        arrOfPlaceholders[10] = "216.58.212.142";

        for (var i = 0; i < arrOfPlaceholders.length * 1000; i++) {
            setTimeout(animateIpPlaceholder, 5000 * i, arrOfPlaceholders[i % arrOfPlaceholders.length]);
        }

    }
    // export pdf
    $(".pdfExportPage").click(function () {
        debugger;
        // Convert the DOM element to a drawing using kendo.drawing.drawDOM
        kendo.drawing.drawDOM($("#divBody"))
        .then(function (group) {
            // Render the result as a PDF file
            return kendo.drawing.exportPDF(group, {
                paperSize: "auto",
                margin: { left: "1cm", top: "1cm", right: "1cm", bottom: "1cm" }
            });
        })
        .done(function (data) {
            // Save the PDF file
            debugger;

            kendo.saveAs({
                dataURI: data,
                fileName: "ToolsForNet" + new Date().getDate() + ".pdf",
                proxyURL: window.location.origin + "/export/pdf"
            });
        });
    });

    //$("#pngExportPage").click(function () {
    //    // Convert the DOM element to a drawing using kendo.drawing.drawDOM
    //    kendo.drawing.drawDOM($("#divBody"))
    //    .then(function (group) {
    //        // Render the result as a PNG image
    //        return kendo.drawing.exportImage(group);
    //    })
    //    .done(function (data) {
    //        // Save the image file
    //        kendo.saveAs({
    //            dataURI: data,
    //            fileName: "ToolsForNet" + new Date().getDate() + ".png",
    //            proxyURL: "@Url.Action('Pdf', 'Export')"
    //        });
    //    });
    //});

    //$("#svgExportPage").click(function () {
    //    // Convert the DOM element to a drawing using kendo.drawing.drawDOM
    //    kendo.drawing.drawDOM($("#divBody"))
    //    .then(function (group) {
    //        // Render the result as a SVG document
    //        return kendo.drawing.exportSVG(group);
    //    })
    //    .done(function (data) {
    //        // Save the SVG document
    //        kendo.saveAs({
    //            dataURI: data,
    //            fileName: "ToolsForNet" + new Date().getDate() + ".svg",
    //            proxyURL: "@Url.Action('Pdf', 'Export')"
    //        });
    //    });
    //});

})

$.ajaxSetup({
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        // Toastr options
        toastr.options = {
            "debug": false,
            "newestOnTop": false,
            "positionClass": "toast-top-center",
            "closeButton": true,
            "toastClass": "animated fadeInDown",
        };
        var laddaButtons = $("[data-loading]");
        laddaButtons.ladda('stop');

        toastr.error('An error occured! Try again.');
    },
    success: function myfunction(event, xhr, settings) {
        alert(message);
    }
});

function animateIpPlaceholder(txt) {

    var timeOut;
    var txtLen = txt.length;
    var char = 0;
    var $ip = $("#ip");
    $ip.attr('placeholder', '|');
    (function typeIt() {
        var humanize = Math.round(Math.random() * (200 - 30)) + 30;
        timeOut = setTimeout(function () {
            var visible = vis(); // gives current state
            if (visible) {
                char++;
                var type = txt.substring(0, char);
                $ip.attr('placeholder', type + '|');
                typeIt();

                if (char == txtLen) {
                    $ip.attr('placeholder', $ip.attr('placeholder').slice(0, -1)) // remove the '|'
                    clearTimeout(timeOut);
                }
            }
            else {
                $ip.attr('placeholder', txt);
            }

        },
         humanize);
    })();
}

var vis = (function () {
    var stateKey, eventKey, keys = {
        hidden: "visibilitychange",
        webkitHidden: "webkitvisibilitychange",
        mozHidden: "mozvisibilitychange",
        msHidden: "msvisibilitychange"
    };
    for (stateKey in keys) {
        if (stateKey in document) {
            eventKey = keys[stateKey];
            break;
        }
    }
    return function (c) {
        if (c) document.addEventListener(eventKey, c);
        return !document[stateKey];
    }
})();

<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var os = require('os');
var fs = require('graceful-fs');
var osenv = require('osenv');
var assign = require('object-assign');
var mkdirp = require('mkdirp');
var yaml = require('js-yaml');
var uuid = require('uuid');

var user = (osenv.user() || uuid.v4()).replace(/\\/g, '');
var tmpDir = path.join(os.tmpdir(), user);
var configDir = process.env.XDG_CONFIG_HOME || path.join(osenv.home() || tmpDir, '.config');
var permissionError = 'You don\'t have access to this file.';

function Configstore(id, defaults) {
	this.path = path.join(configDir, 'configstore', id + '.yml');
	this.all = [defaults || {}, this.all || {}].reduce(assign, {});
}

Configstore.prototype = Object.create(Object.prototype, {
	all: {
		get: function () {
			try {
				return yaml.safeLoad(fs.readFileSync(this.path, 'utf8'), {
					filename: this.path,
					schema: yaml.JSON_SCHEMA
				});
			} catch (err) {
				// create dir if it doesn't exist
				if (err.code === 'ENOENT') {
					mkdirp.sync(path.dirname(this.path));
					return {};
				}

				// improve the message of permission errors
				if (err.code === 'EACCES') {
					err.message = err.message + '\n' + permissionError + '\n';
				}

				// empty the file if it encounters invalid YAML
				if (err.name === 'YAMLException') {
					fs.writeFileSync(this.path, '');
					return {};
				}

				throw err;
			}
		},
		set: function (val) {
			try {
				// make sure the folder exists, it could have been
				// deleted meanwhile
				mkdirp.sync(path.dirname(this.path));
				fs.writeFileSync(this.path, yaml.safeDump(val, {
					skipInvalid: true,
					schema: yaml.JSON_SCHEMA
				}));
			} catch (err) {
				// improve the message of permission errors
				if (err.code === 'EACCES') {
					err.message = err.message + '\n' + permissionError + '\n';
				}

				throw err;
			}
		}
	},
	size: {
		get: function () {
			return Object.keys(this.all || {}).length;
		}
	}
});

Configstore.prototype.get = function (key) {
	return this.all[key];
};

Configstore.prototype.set = function (key, val) {
	var config = this.all;
	config[key] = val;
	this.all = config;
};

Configstore.prototype.del = function (key) {
	var config = this.all;
	delete config[key];
	this.all = config;
};

module.exports = Configstore;
<commit_msg>Support node 0.8 which has os.tmpDir with different capitalization<commit_after>'use strict';
var path = require('path');
var os = require('os');
var fs = require('graceful-fs');
var osenv = require('osenv');
var assign = require('object-assign');
var mkdirp = require('mkdirp');
var yaml = require('js-yaml');
var uuid = require('uuid');
var getTempDir = os.tmpdir || os.tmpDir; //support node 0.8

var user = (osenv.user() || uuid.v4()).replace(/\\/g, '');
var tmpDir = path.join(getTempDir(), user);
var configDir = process.env.XDG_CONFIG_HOME || path.join(osenv.home() || tmpDir, '.config');
var permissionError = 'You don\'t have access to this file.';

function Configstore(id, defaults) {
	this.path = path.join(configDir, 'configstore', id + '.yml');
	this.all = [defaults || {}, this.all || {}].reduce(assign, {});
}

Configstore.prototype = Object.create(Object.prototype, {
	all: {
		get: function () {
			try {
				return yaml.safeLoad(fs.readFileSync(this.path, 'utf8'), {
					filename: this.path,
					schema: yaml.JSON_SCHEMA
				});
			} catch (err) {
				// create dir if it doesn't exist
				if (err.code === 'ENOENT') {
					mkdirp.sync(path.dirname(this.path));
					return {};
				}

				// improve the message of permission errors
				if (err.code === 'EACCES') {
					err.message = err.message + '\n' + permissionError + '\n';
				}

				// empty the file if it encounters invalid YAML
				if (err.name === 'YAMLException') {
					fs.writeFileSync(this.path, '');
					return {};
				}

				throw err;
			}
		},
		set: function (val) {
			try {
				// make sure the folder exists, it could have been
				// deleted meanwhile
				mkdirp.sync(path.dirname(this.path));
				fs.writeFileSync(this.path, yaml.safeDump(val, {
					skipInvalid: true,
					schema: yaml.JSON_SCHEMA
				}));
			} catch (err) {
				// improve the message of permission errors
				if (err.code === 'EACCES') {
					err.message = err.message + '\n' + permissionError + '\n';
				}

				throw err;
			}
		}
	},
	size: {
		get: function () {
			return Object.keys(this.all || {}).length;
		}
	}
});

Configstore.prototype.get = function (key) {
	return this.all[key];
};

Configstore.prototype.set = function (key, val) {
	var config = this.all;
	config[key] = val;
	this.all = config;
};

Configstore.prototype.del = function (key) {
	var config = this.all;
	delete config[key];
	this.all = config;
};

module.exports = Configstore;
<|endoftext|>


<commit_before>// A safer console object - see github.com/nathanl/consolation
safe_console = {
  enabled: false,
  __no_op_console: {},
  __args_to_array: function(args) { return Array.prototype.slice.call(args); },
  __caller_location: function() {
    var call_locations, current_position, caller, file_and_line;
    try {
    call_locations   = (new Error).stack.split("\n");
    current_position = call_locations[0].match(/Error/) ? 3 : 2;
    caller           = call_locations[current_position];
    // Match from either the last '/' or from '<anonymous>' to the end
    file_and_line    = caller.match(/(\/([^\/]*)|\<anonymous\>.*)$/)[0];

    } catch (err) {
      file_and_line = 'location not supported by browser';
    }
    return file_and_line;
  },
  // Metaprogramming in JS! Wooooooooooooooo
  __add_console_methods: function(console_object, definer) {
    logging_methods = ['log', 'debug', 'info', 'error', 'warn'];
    methods         = ['dir', 'group', 'groupCollapsed', 'groupEnd', 'time', 'timeEnd', 'trace'].concat(logging_methods);
    for (i = 0; i < methods.length; i++) {
      method_name = methods[i];
      definer(console_object, method_name);
    }
  }
};

// If the browser has no usable console, use a no-op.
safe_console.original_console = (function(){
  return (typeof(window.console === 'object') && typeof(window.console.log) === 'function') ? window.console : safe_console.__no_op_console;
})();

// Define all no-op methods for dummy console
safe_console.__add_console_methods(safe_console.__no_op_console, function(console_object, method_name) {
  console_object[method_name] = function() { return; };
});

// Define real logging methods for safe console
safe_console.__add_console_methods(safe_console, function(console_object, method_name){
  console_object[method_name] = function() {
    if (!this.enabled) { return; }
    var args = arguments;
    // Tack on the caller location if this is a logging method
    if (logging_methods.indexOf(method_name) !== -1) {
      var called_from = this.__caller_location();
      args            = this.__args_to_array(arguments).concat("(" + called_from + ")");
    }
    this.original_console[method_name].apply(this.original_console, args);
  };
});

// In case we missed any methods, inherit from original console. (These would ignore the `enabled` switch)
safe_console.__proto__ = safe_console.original_console;

// Recklessly cautious!
window.console = safe_console;
<commit_msg>Remove accidental global variable |i|<commit_after>// A safer console object - see github.com/nathanl/consolation
safe_console = {
  enabled: false,
  __no_op_console: {},
  __args_to_array: function(args) { return Array.prototype.slice.call(args); },
  __caller_location: function() {
    var call_locations, current_position, caller, file_and_line;
    try {
    call_locations   = (new Error).stack.split("\n");
    current_position = call_locations[0].match(/Error/) ? 3 : 2;
    caller           = call_locations[current_position];
    // Match from either the last '/' or from '<anonymous>' to the end
    file_and_line    = caller.match(/(\/([^\/]*)|\<anonymous\>.*)$/)[0];

    } catch (err) {
      file_and_line = 'location not supported by browser';
    }
    return file_and_line;
  },
  // Metaprogramming in JS! Wooooooooooooooo
  __add_console_methods: function(console_object, definer) {
    logging_methods = ['log', 'debug', 'info', 'error', 'warn'];
    methods         = ['dir', 'group', 'groupCollapsed', 'groupEnd', 'time', 'timeEnd', 'trace'].concat(logging_methods);
    for (var i = 0; i < methods.length; i++) {
      method_name = methods[i];
      definer(console_object, method_name);
    }
  }
};

// If the browser has no usable console, use a no-op.
safe_console.original_console = (function(){
  return (typeof(window.console === 'object') && typeof(window.console.log) === 'function') ? window.console : safe_console.__no_op_console;
})();

// Define all no-op methods for dummy console
safe_console.__add_console_methods(safe_console.__no_op_console, function(console_object, method_name) {
  console_object[method_name] = function() { return; };
});

// Define real logging methods for safe console
safe_console.__add_console_methods(safe_console, function(console_object, method_name){
  console_object[method_name] = function() {
    if (!this.enabled) { return; }
    var args = arguments;
    // Tack on the caller location if this is a logging method
    if (logging_methods.indexOf(method_name) !== -1) {
      var called_from = this.__caller_location();
      args            = this.__args_to_array(arguments).concat("(" + called_from + ")");
    }
    this.original_console[method_name].apply(this.original_console, args);
  };
});

// In case we missed any methods, inherit from original console. (These would ignore the `enabled` switch)
safe_console.__proto__ = safe_console.original_console;

// Recklessly cautious!
window.console = safe_console;
<|endoftext|>


<commit_before>var fs = require('fs')
var format = require('util').format
var https = require('https')
var path = require('path')

module.exports = function getVersions (options) {
  var distributionListingUri = options.baseUrl + 'index.json'

  https.get(distributionListingUri, function (res) {
    if (res.statusCode !== 200) return this.emit('error', res)

    var responseData = ''

    res
    .on('data', function (data) {
      responseData = responseData + data
    })
    .on('end', function () {
      var self = this;
      JSON.parse(responseData)
        .map(function (build) {
          return Object.assign(Object.create(Build), {
            baseUrl: options.baseUrl,
            binaries: [],
            prefix: options.prefix || '',
            version: build.version
          })
        })
        .filter(function (build) {
          return !build.fileExists || options.overwrite
        })
        .forEach(function (build) {
          getChecksumsFile(build, function(err, shasumData) {
            extractShasums(build, shasumData, writeFile)
          })
        })
    })
    .on('error', this.emit.bind(this, 'error'))
  }).on('error', function (e) { console.error('Error with distribution listing', e.message) })
}

// private

var Build = {
  get basename () {
    return this.prefix + this.version.replace(/v/, '')
  },
  get filename () {
    return path.join(__dirname, '../share/node-build', this.basename)
  },
  get fileExists () {
    return fs.existsSync(this.filename)
  },
  get shasumFileUri () {
    return format('%s%s/SHASUMS256.txt', this.baseUrl, this.version)
  },
  get definition () {
    return format('%sinstall_package "%s" "%s"\n', this.distros, this.name, this.downloadUri)
  },
  get distros () {
    return this.binaries.map(function(binary){ return binary.definition }).join('') + (this.binaries.length ? '\n' : '')
  },
  get downloadUri () {
    return format('%s%s/%s#%s', this.baseUrl, this.version, this.package, this.shasum)
  }
}

var Binary = {
  get definition () {
    return format('distro %s "%s"\n', this.platform, this.downloadUri)
  },
  get downloadUri () {
    return format('%s%s/%s#%s', this.build.baseUrl, this.build.version, this.package, this.shasum)
  }
}

function getChecksumsFile (build, cb) {
  https.get(build.shasumFileUri, function (res) {
    if (res.statusCode !== 200) return this.emit('error', res)

    var shasumData = ''

    res
    .on('data', function (data) {
      shasumData = shasumData + data
    })
    .on('end', function () {
      cb(null, shasumData)
    })
    .on('error', this.emit.bind(this, 'error'))
  }).on('error', function (e) { console.error('Error with ', build.version, e.message) })
}

function extractShasums (build, shasumData, cb) {
  try {
    extractSourceChecksum(build, shasumData)
    extractBinaryChecksums(build, shasumData)
    cb(null, build)
  } catch (error) {
    cb(err)
  }
}

function extractSourceChecksum (build, shasumData) {
  var result = shasumData.match(/^(\w{64}) {2}(?:\.\/)?(((?:node|iojs)-v\d+\.\d+\.\d+).tar.gz)$/im)

  if (result) {
    build.shasum = result[1]
    build.package = result[2]
    build.name = result[3]
  } else {
    throw new Error("bad checksum data", shasumData)
  }
}

function extractBinaryChecksums (build, shasumData) {
  var result = shasumData.match(/^(\w{64}) {2}(?:\.\/)?((?:(?:node|iojs)-v\d+\.\d+\.\d+)-(.+).tar.gz)$/gim)
  if (!result) return

  result.forEach(function(distro) {
    var result = distro.match(/^(\w{64}) {2}(?:\.\/)?((?:(?:node|iojs)-v\d+\.\d+\.\d+)-(.+).tar.gz)$/i)
    if(!result) return
    build.binaries.push(
      Object.assign(Object.create(Binary), {
        build: build,
        shasum: result[1],
        package: result[2],
        platform: result[3]
      })
    )
  })
}

function writeFile (err, build) {
  if (err) return console.error(err)

  fs.writeFile(build.filename, build.definition, function (err) {
    if (err) return console.error(err)

    console.log(build.name + ' written')
  })
}
<commit_msg>exclude headers packages<commit_after>var fs = require('fs')
var format = require('util').format
var https = require('https')
var path = require('path')

module.exports = function getVersions (options) {
  var distributionListingUri = options.baseUrl + 'index.json'

  https.get(distributionListingUri, function (res) {
    if (res.statusCode !== 200) return this.emit('error', res)

    var responseData = ''

    res
    .on('data', function (data) {
      responseData = responseData + data
    })
    .on('end', function () {
      var self = this;
      JSON.parse(responseData)
        .map(function (build) {
          return Object.assign(Object.create(Build), {
            baseUrl: options.baseUrl,
            binaries: [],
            prefix: options.prefix || '',
            version: build.version
          })
        })
        .filter(function (build) {
          return !build.fileExists || options.overwrite
        })
        .forEach(function (build) {
          getChecksumsFile(build, function(err, shasumData) {
            extractShasums(build, shasumData, writeFile)
          })
        })
    })
    .on('error', this.emit.bind(this, 'error'))
  }).on('error', function (e) { console.error('Error with distribution listing', e.message) })
}

// private

var Build = {
  get basename () {
    return this.prefix + this.version.replace(/v/, '')
  },
  get filename () {
    return path.join(__dirname, '../share/node-build', this.basename)
  },
  get fileExists () {
    return fs.existsSync(this.filename)
  },
  get shasumFileUri () {
    return format('%s%s/SHASUMS256.txt', this.baseUrl, this.version)
  },
  get definition () {
    return format('%sinstall_package "%s" "%s"\n', this.distros, this.name, this.downloadUri)
  },
  get distros () {
    return this.binaries.map(function(binary){ return binary.definition }).join('') + (this.binaries.length ? '\n' : '')
  },
  get downloadUri () {
    return format('%s%s/%s#%s', this.baseUrl, this.version, this.package, this.shasum)
  }
}

var Binary = {
  get definition () {
    return format('distro %s "%s"\n', this.platform, this.downloadUri)
  },
  get downloadUri () {
    return format('%s%s/%s#%s', this.build.baseUrl, this.build.version, this.package, this.shasum)
  }
}

function getChecksumsFile (build, cb) {
  https.get(build.shasumFileUri, function (res) {
    if (res.statusCode !== 200) return this.emit('error', res)

    var shasumData = ''

    res
    .on('data', function (data) {
      shasumData = shasumData + data
    })
    .on('end', function () {
      cb(null, shasumData)
    })
    .on('error', this.emit.bind(this, 'error'))
  }).on('error', function (e) { console.error('Error with ', build.version, e.message) })
}

function extractShasums (build, shasumData, cb) {
  try {
    extractSourceChecksum(build, shasumData)
    extractBinaryChecksums(build, shasumData)
    cb(null, build)
  } catch (error) {
    cb(error)
  }
}

function extractSourceChecksum (build, shasumData) {
  var result = shasumData.match(/^(\w{64}) {2}(?:\.\/)?(((?:node|iojs)-v\d+\.\d+\.\d+).tar.gz)$/im)

  if (result) {
    build.shasum = result[1]
    build.package = result[2]
    build.name = result[3]
  } else {
    throw new Error("bad checksum data", shasumData)
  }
}

function extractBinaryChecksums (build, shasumData) {
  var result = shasumData.match(/^(\w{64}) {2}(?:\.\/)?((?:(?:node|iojs)-v\d+\.\d+\.\d+)-(?!headers)(.+).tar.gz)$/gim)
  if (!result) return

  result.forEach(function(distro) {
    var result = distro.match(/^(\w{64}) {2}(?:\.\/)?((?:(?:node|iojs)-v\d+\.\d+\.\d+)-(.+).tar.gz)$/i)
    if(!result) return
    build.binaries.push(
      Object.assign(Object.create(Binary), {
        build: build,
        shasum: result[1],
        package: result[2],
        platform: result[3]
      })
    )
  })
}

function writeFile (err, build) {
  if (err) return console.error(err)

  fs.writeFile(build.filename, build.definition, function (err) {
    if (err) return console.error(err)

    console.log(build.name + ' written')
  })
}
<|endoftext|>


<commit_before>'use strict';

// script for sales tools page

// The Store object constructor
function Store (name, min, max, avg) {
  this.storeName = name;
  this.minCust = min;
  this.maxCust = max;
  this.avgCookiesPurchased = avg;
  this.totalCookies = 0;
  this.hourlyCookies = [];
  this.tableRow;
}

// creating object functions and putting them on the prototype
Store.prototype.getRandomNum = function () {
  // this generates a random number between the min and max values.
  return Math.floor(Math.random() * (this.maxCust - this.minCust + 1) + this.minCust);
};

Store.prototype.cookiesPerHour = function () {
  // calculates a random number average of cookies purchased
  return this.getRandomNum() * this.avgCookiesPurchased;
};

Store.prototype.cookiesPerDay = function () {
  // caclulates total cookes per day based on the random average of cookies per hour
  for (var j = 0; j < 14; j++) {
    this.hourlyCookies[j] = Math.round(this.cookiesPerHour());
    this.totalCookies += this.hourlyCookies[j];
  };
};

Store.prototype.createTableData = function () {
  // create the data to put in a table...
  this.cookiesPerDay();

  //  store table data created here (a row of data for the table)
  var bodyRow     = document.createElement('tr');

  // create the row header first, then load in the rest of the row data
  var rowName     = document.createElement('th');
  rowName.textContent = this.storeName;
  bodyRow.appendChild(rowName);

  for (var j = 0; j < this.hourlyCookies.length; j++) {
    var elem = document.createElement('td');
    elem.textContent = this.hourlyCookies[j];
    bodyRow.appendChild(elem);
  }

  // now put the total for the store into the row
  var td = document.createElement('td');
  td.textContent = this.totalCookies;
  bodyRow.appendChild(td);

  this.tableRow = bodyRow;
};

var allStores = [];

var firstAndPike = new Store('1st and Pike', 23, 65, 6.3);
var seaTac = new Store('SeaTac Airport', 3, 24, 1.2);
var seaCtr = new Store('Seattle Center', 11, 28, 3.7);
var capHill = new Store('Capitol Hill', 20, 38, 2.3);
var alki = new Store('Alki', 2, 16, 4.6);

allStores[0] = firstAndPike;
allStores[1] = seaTac;
allStores[2] = seaCtr;
allStores[3] = capHill;
allStores[4] = alki;

// create table header here
// create the table to hold that data just created
var salesTable = document.createElement('table');

// create Header data here
var hoursOpenArray = [];
var hour = 0;
var hourText = '';
for (var h = 0; h < 14; h++) {
  hour = h + 6;
  if (hour > 12) {
    hourText = (hour - 12) + ':00 pm';
  } else if ( hour < 12) {
    hourText = hour + ':00 am';
  } else {
    hourText = hour + ':00 pm';
  };
  hoursOpenArray[h] = hourText;
};

var salesHeader = document.createElement('thead');
var headerRow   = document.createElement('tr');
var blankHdr    = document.createElement('th');
// we need a blank column heading before adding the rest of the header data
headerRow.appendChild(blankHdr);

for (var i = 0; i < hoursOpenArray.length; i++) {
  var th = document.createElement('th');
  th.textContent = hoursOpenArray[i];
  headerRow.appendChild(th);
}
// we also need a final column for the total for the store
// we will just re-use the blankHdr we have sitting around.
var headerTotal = document.createElement('th');
headerTotal.textContent = 'Total';
headerRow.appendChild(headerTotal);

salesHeader.appendChild(headerRow);
salesTable.appendChild(salesHeader);

var salesBody   = document.createElement('tbody');
var footTotals = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var footGrandTotal = 0;
// now for each store, get it's data
for (var m = 0; m < allStores.length; m++) {
  allStores[m].createTableData();
  // put row of data into body
  salesBody.appendChild(allStores[m].tableRow);

  // while we are looping through the stores, generate TOTALS
  for (var c = 0; c < allStores[m].hourlyCookies.length; c++){
    footTotals[c] += allStores[m].hourlyCookies[c];
  }
  footGrandTotal += allStores[m].totalCookies;
}
// put the body into the table
salesTable.appendChild(salesBody);

// TODO: work the details out for the footer
var salesFoot = document.createElement('tfoot');
var footRow  = document.createElement('tr');
var footHdr   = document.createElement('th');
footHdr.textContent = 'TOTALS:';
footRow.appendChild(footHdr);

// load zeros in for totals for now.
for (var f = 0; f < footTotals.length; f++) {
  var footData = document.createElement('td');
  footData.textContent = footTotals[f];
  footRow.appendChild(footData);
};
// add one more for the total column
var tdTotal = document.createElement('td');
tdTotal.textContent = footGrandTotal;
footRow.appendChild(tdTotal);

// put that footer row in the footer.
salesFoot.appendChild(footRow);
// and put the footer into the table.
salesTable.appendChild(salesFoot);

var storeData = document.getElementById('store_data');
storeData.appendChild(salesTable);

// hope for the best!
<commit_msg>organized js code<commit_after>'use strict';

// script for sales tools page

// The Store object constructor
function Store (name, min, max, avg) {
  this.storeName = name;
  this.minCust = min;
  this.maxCust = max;
  this.avgCookiesPurchased = avg;
  this.totalCookies = 0;
  this.hourlyCookies = [];
  this.tableRow;
}

// creating object functions and putting them on the prototype
Store.prototype.getRandomNum = function () {
  // this generates a random number between the min and max values.
  return Math.floor(Math.random() * (this.maxCust - this.minCust + 1) + this.minCust);
};

Store.prototype.cookiesPerHour = function () {
  // calculates a random number average of cookies purchased
  return this.getRandomNum() * this.avgCookiesPurchased;
};

Store.prototype.cookiesPerDay = function () {
  // caclulates total cookes per day based on the random average of cookies per hour
  for (var j = 0; j < 14; j++) {
    this.hourlyCookies[j] = Math.round(this.cookiesPerHour());
    this.totalCookies += this.hourlyCookies[j];
  };
};

Store.prototype.createTableData = function () {
  // create the data to put in a table...
  this.cookiesPerDay();

  //  store table data created here (a row of data for the table)
  var bodyRow     = document.createElement('tr');

  // create the row header first, then load in the rest of the row data
  var rowName     = document.createElement('th');
  rowName.textContent = this.storeName;
  bodyRow.appendChild(rowName);

  for (var j = 0; j < this.hourlyCookies.length; j++) {
    var elem = document.createElement('td');
    elem.textContent = this.hourlyCookies[j];
    bodyRow.appendChild(elem);
  }

  // now put the total for the store into the row
  var td = document.createElement('td');
  td.textContent = this.totalCookies;
  bodyRow.appendChild(td);

  this.tableRow = bodyRow;
};
// ------------- THAT IS ALL THE STORE OBJECT STUFF

// ------------- Now a couple general functions

// create the header and append it to the passed table
function createHdr(theTable) {
  // create table header here
  var hoursOpenArray = [];
  var hour = 0;
  var hourText = '';
  for (var h = 0; h < 14; h++) {
    hour = h + 6;
    if (hour > 12) {
      hourText = (hour - 12) + ':00 pm';
    } else if ( hour < 12) {
      hourText = hour + ':00 am';
    } else {
      hourText = hour + ':00 pm';
    };
    hoursOpenArray[h] = hourText;
  };

  var salesHeader = document.createElement('thead');
  var headerRow   = document.createElement('tr');
  var blankHdr    = document.createElement('th');
  // we need a blank column heading before adding the rest of the header data
  headerRow.appendChild(blankHdr);

  for (var i = 0; i < hoursOpenArray.length; i++) {
    var th = document.createElement('th');
    th.textContent = hoursOpenArray[i];
    headerRow.appendChild(th);
  }
  // we also need a final column for the total for the store
  // we will just re-use the blankHdr we have sitting around.
  var headerTotal = document.createElement('th');
  headerTotal.textContent = 'Total';
  headerRow.appendChild(headerTotal);

  salesHeader.appendChild(headerRow);
  theTable.appendChild(salesHeader);
};

// create the footer and append it to the passed table.
function createFtr (theTable) {
  // TODO: work the details out for the footer
  var salesFoot = document.createElement('tfoot');
  var footRow  = document.createElement('tr');
  var footHdr   = document.createElement('th');
  footHdr.textContent = 'TOTALS:';
  footRow.appendChild(footHdr);

  // load zeros in for totals for now.
  for (var f = 0; f < footTotals.length; f++) {
    var footData = document.createElement('td');
    footData.textContent = footTotals[f];
    footRow.appendChild(footData);
  };
  // add one more for the total column
  var tdTotal = document.createElement('td');
  tdTotal.textContent = footGrandTotal;
  footRow.appendChild(tdTotal);

  // put that footer row in the footer.
  salesFoot.appendChild(footRow);
  // and put the footer into the table.
  theTable.appendChild(salesFoot);
};
// ------------ Done with general functions

// Now run the 'control' script

var allStores = [];

allStores[0] = new Store('1st and Pike', 23, 65, 6.3);
allStores[1] = new Store('SeaTac Airport', 3, 24, 1.2);
allStores[2] = new Store('Seattle Center', 11, 28, 3.7);
allStores[3] = new Store('Capitol Hill', 20, 38, 2.3);
allStores[4] = new Store('Alki', 2, 16, 4.6);

// create the table to hold that data just created
var salesTable = document.createElement('table');
createHdr(salesTable);

var salesBody  = document.createElement('tbody');
// these two variables below are used when creating the footer, but populated
// as eah table is processed.
var footTotals = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var footGrandTotal = 0;
// now for each store, get it's data
for (var m = 0; m < allStores.length; m++) {
  allStores[m].createTableData();
  // put row of data into body
  salesBody.appendChild(allStores[m].tableRow);

  // while we are looping through the stores, generate TOTALS
  for (var c = 0; c < allStores[m].hourlyCookies.length; c++){
    footTotals[c] += allStores[m].hourlyCookies[c];
  }
  footGrandTotal += allStores[m].totalCookies;
}
// put the body into the table
salesTable.appendChild(salesBody);

// add the footer
createFtr(salesTable);

var storeData = document.getElementById('store_data');
storeData.appendChild(salesTable);

// hope for the best!
<|endoftext|>


<commit_before>const events = [
    'beforeActivation',
    'afterActivation',
    'beforeDeactivation',
    'afterDeactivation',

    'beforeActivationFor',
    'afterActivationFor',
    'beforeDeactivationFor',
    'afterDeactivationFor'
];

export class Scope {
    constructor() {
        this.activatedItems = new Set();

        this._isActive = false;
        this._partials = new Set();

        // TODO: use a dedicated event listener library
        this._eventCallbacks = new Map();
        for(let eventName of events) {
            this._eventCallbacks.set(eventName, new Set());
        }
    }

    // Managing composites
    add(partial) {
        this._partials.add(partial);

        // TODO: adding to an already active scope should activate the partial

        return this;
    }
    remove(partial) {
        this._partials.delete(partial);

        return this;
    }
    contains(partial) {
        return this._partials.has(partial);
    }
    [Symbol.iterator]() {
        return this._partials.values()
    }

    // Scope Activation
    activate() {
        if(!this.isActive()) {
            this._eventCallbacks.get('beforeActivation').forEach(callback => callback());

            this._isActive = true;
            this._partials.forEach(partial => partial.activate());

            this._eventCallbacks.get('afterActivation').forEach(callback => callback());
        }

        return this;
    }
    deactivate() {
        if(this.isActive()) {
            this._eventCallbacks.get('beforeDeactivation').forEach(callback => callback());

            this._isActive = false;
            this._partials.forEach(partial => partial.deactivate());

            this._eventCallbacks.get('afterDeactivation').forEach(callback => callback());
        }

        return this;
    }
    isActive() { return this._isActive; }

    // Activation Hooks
    on(event, callback) {
        var callbacks = this._eventCallbacks.get(event);
        callbacks.add(callback);

        return this;
    }
    off(event, callback) {
        var callbacks = this._eventCallbacks.get(event);
        callbacks.delete(callback);

        return this;
    }

    activateFor(obj) {
        if(!this.isActiveFor(obj)) {
            this._eventCallbacks.get('beforeActivationFor').forEach(callback => callback(obj));

            this.activatedItems.add(obj);
            this._partials.forEach(partial => partial.activateFor(obj));

            this._eventCallbacks.get('afterActivationFor').forEach(callback => callback(obj));
        }

        return this;
    }

    deactivateFor(obj) {
        if(this.isActiveFor(obj)) {
            this._eventCallbacks.get('beforeDeactivationFor').forEach(callback => callback(obj));

            this.activatedItems.delete(obj);
            this._partials.forEach(partial => partial.deactivateFor(obj));

            this._eventCallbacks.get('afterDeactivationFor').forEach(callback => callback(obj));
        }

        return this;
    }
    isActiveFor(obj) {
        return this.activatedItems.has(obj);
    }
}
<commit_msg>introduce separate class for Partials<commit_after>const events = [
    'beforeActivation',
    'afterActivation',
    'beforeDeactivation',
    'afterDeactivation',

    'beforeActivationFor',
    'afterActivationFor',
    'beforeDeactivationFor',
    'afterDeactivationFor'
];

export class Partial {
    activate() {}
    deactivate() {}
    activateFor() {}
    deactivateFor() {}
}

export class Scope extends Partial {
    constructor() {
        super();

        this.activatedItems = new Set();

        this._isActive = false;
        this._partials = new Set();

        // TODO: use a dedicated event listener library
        this._eventCallbacks = new Map();
        for(let eventName of events) {
            this._eventCallbacks.set(eventName, new Set());
        }
    }

    // Managing composites
    add(partial) {
        this._partials.add(partial);

        // TODO: adding to an already active scope should activate the partial

        return this;
    }
    remove(partial) {
        this._partials.delete(partial);

        return this;
    }
    contains(partial) {
        return this._partials.has(partial);
    }
    [Symbol.iterator]() {
        return this._partials.values()
    }

    // Scope Activation
    activate() {
        if(!this.isActive()) {
            this._eventCallbacks.get('beforeActivation').forEach(callback => callback());

            this._isActive = true;
            this._partials.forEach(partial => partial.activate());

            this._eventCallbacks.get('afterActivation').forEach(callback => callback());
        }

        return this;
    }
    deactivate() {
        if(this.isActive()) {
            this._eventCallbacks.get('beforeDeactivation').forEach(callback => callback());

            this._isActive = false;
            this._partials.forEach(partial => partial.deactivate());

            this._eventCallbacks.get('afterDeactivation').forEach(callback => callback());
        }

        return this;
    }
    isActive() { return this._isActive; }

    // Activation Hooks
    on(event, callback) {
        var callbacks = this._eventCallbacks.get(event);
        callbacks.add(callback);

        return this;
    }
    off(event, callback) {
        var callbacks = this._eventCallbacks.get(event);
        callbacks.delete(callback);

        return this;
    }

    activateFor(obj) {
        if(!this.isActiveFor(obj)) {
            this._eventCallbacks.get('beforeActivationFor').forEach(callback => callback(obj));

            this.activatedItems.add(obj);
            this._partials.forEach(partial => partial.activateFor(obj));

            this._eventCallbacks.get('afterActivationFor').forEach(callback => callback(obj));
        }

        return this;
    }

    deactivateFor(obj) {
        if(this.isActiveFor(obj)) {
            this._eventCallbacks.get('beforeDeactivationFor').forEach(callback => callback(obj));

            this.activatedItems.delete(obj);
            this._partials.forEach(partial => partial.deactivateFor(obj));

            this._eventCallbacks.get('afterDeactivationFor').forEach(callback => callback(obj));
        }

        return this;
    }
    isActiveFor(obj) {
        return this.activatedItems.has(obj);
    }
}
<|endoftext|>


<commit_before>
(function (module) {
	'use strict';

	var copySelection = require('ksxatomsupports').clipboard.copySelection;
	var utils = require('../lib/utils.js');
	var ConsoleHistory = require('../lib/console-history.js');
	var specialcmds = require('../lib/special-commands.js');

	var compareSequence = utils.compareSequence.iterable;

	const ENTER_KEY = 0x0D;
	const ESC_KEY = 0x1B;
	const KEY_UP = 0x26;
	const KEY_DOWN = 0x28;
	const CHAR_CODE_0 = '0'.charCodeAt();
	const CHAR_CODE_9 = '9'.charCodeAt();
	const MINI_EDITOR = Object.freeze({mini: true});
	const OUT_INPUT = Object.freeze(['from-input', 'text-normal']);
	const OUT_DATA = Object.freeze(['from-data', 'text-normal']);
	const OUT_ERROR = Object.freeze(['text-error']);

	module.exports = (elements, param) => {

		function SpecialCommandsParam(command, elements) {
			this.command = command;
			this.elements = elements;
		}

		SpecialCommandsParam.prototype = {
			handleData: handleData,
			handleError: handleError,
			handleClose: handleClose,
			writeStdIn: writeStdIn,
			writeString: writeString,
			writeChar: writeChar,
			closePaneItem: closePaneItem
		};

		function main(elements, param) {
			handleCommon(elements, param);
			handleConfig(elements, param.fromConfig);
			handleCloseEvent(elements, param.process);
			handleStdIn(elements, param.process.stdin);
			handleStdOut(elements, param.process.stdout);
			handleStdErr(elements, param.process.stderr);
		}

		function handleCommon(elements, param) {
			elements.descriptiondiv.textContent = `Running: ${param.fromScript.path}`;
			((proto) => {
				proto.process = param.process;
				proto.services = param.services;
				proto.fromConfig = param.fromConfig;
				proto.fromScript = param.fromScript;
			})(SpecialCommandsParam.prototype);
			handleCommon.handlePromise = param.handlePromise;
		}

		function handleConfig(elements, config) {
			enterStdIn.write = config.hideInputText ? () => {} : writeString;
			handleClose.considerClosePaneItem = config.closeOnExit ? closePaneItem : () => {};
			handleSpecialCommand(config);
		}

		function handleCloseEvent(elements, process) {
			process.on('close', handleClose.bind(null, elements));
			process.on('error', (error) => handleError(elements, String(error)));
			handleCommon.handlePromise((paneitem) => {
				handleCommon.paneItem = paneitem;
				paneitem.onDidDestroy(() => process.kill());
			});
		}

		function handleSpecialCommand(config) {
			var list = config.utils;
			if (list instanceof Array) {
				enterStdIn.handleSpecialCommand = (command, elements) => {
					for (let fname of list) {
						if (command === fname || !command.indexOf(`${fname}\x20`)) {
							try {
								return !specialcmds[fname](new SpecialCommandsParam(command, elements));
							} catch (error) {
								handleError(elements, `A JS error has occurred during execution of command '${command}'\nCommand may not be supported\n${error}\n`);
								handleData(elements, `Passing data to stdin by default...\n`);
								return false;
							}
						}
					}
				};
			} else {
				enterStdIn.handleSpecialCommand = () => {};
			}

		}

		function handleClose(elements, exitcode) {
			elements.finaloutputdiv.textContent = `Process finished, exit code: ${exitcode}`;
			elements.inputdiv.remove();
			handleClose.considerClosePaneItem();
		}

		function handleStdIn(elements, stdin) {
			if (!stdin) {
				return;
			}
			var editorutil = buildTextEditor(elements);
			handleControl(editorutil, elements, stdin);
			focusInputElement(editorutil);
			handleCommon.handlePromise((paneitem) => {
				paneitem.onDidActive(() => focusInputElement(editorutil));
				paneitem.acceptToBeClosed = () => editorutil.empty;
			});
			enterStdIn.history = new ConsoleHistory();
			elements.outputpre.hidden = true;
		}

		function focusInputElement(editorutil) {
			setTimeout(() => editorutil.element.focus());
		}

		function buildTextEditor(elements) {
			var editorutil = require('ksxatomsupports').editor.EditorUtil.new(MINI_EDITOR);
			elements.editordiv.insertBefore(editorutil.element, null);
			return editorutil;
		}

		function handleControl(editorutil, elements, stdin) {
			attachStdInEvent(editorutil.editor, editorutil.element, elements, stdin);
			makeConfirmButton(editorutil.editor, elements, stdin);
		}

		function attachStdInEvent(editor, element, elements, stdin) {
			var handle = handleKeyboardEvent.bind(null, stdin, editor, elements);
			element.addEventListener('keydown', handle, false);
		}

		function handleKeyboardEvent(stdin, editor, elements, event) {
			switch (event.keyCode) {
				case ENTER_KEY:
					return enterStdIn(stdin, editor, elements);
				case ESC_KEY:
					return void editor.setText('');
				case KEY_UP:
					return enterStdIn.history.up(editor);
				case KEY_DOWN:
					return enterStdIn.history.down(editor);
			}
		}

		function makeConfirmButton(editor, elements, stdin) {
			var handle = () => enterStdIn(stdin, editor, elements);
			elements.confirmbutton.addEventListener('click', handle, false);
		}

		function enterStdIn(stdin, editor, elements) {
			var text = editor.getText();
			editor.setText('');
			text && enterStdIn.history.add(text);
			enterStdIn.handleSpecialCommand(text, elements) || writeStdIn(stdin, new Buffer(`${text}\n`), editor.getEncoding(), elements.outputpre);
		}

		function writeStdIn(stdin, data, encoding, outputpre) {
			stdin.write(data, encoding);
			enterStdIn.write(outputpre, data, OUT_INPUT);
		}

		function handleStdOut(elements, stdout) {
			if (!stdout) return;
			stdout.on('data', handleData.bind(null, elements));
		}

		function handleData(elements, data) {
			writeString(elements.outputpre, `${data}`, OUT_DATA);
		}

		function handleStdErr(elements, stderr) {
			if (!stderr) return;
			stderr.on('data', handleError.bind(null, elements));
		}

		function handleError(elements, error) {
			writeString(elements.outputpre, `${error}\n`, OUT_ERROR);
		}

		function writeString(outputpre, string, extraclass) {
			if (!writeString.target || !compareSequence(extraclass, writeString.extraclass)) {
				writeString.extraclass = extraclass;
				replaceTerminalTarget(document.createElement('span'), outputpre);
				extraclass instanceof Array && extraclass.forEach((classname) => writeString.target.classList.add(classname));
			}
			for (let char of String(string)) {
				writeChar(writeString.target, char, outputpre);
			}
			outputpre.parentElement.scrollTop = outputpre.parentElement.scrollHeight;
		}

		function writeChar(target, char, outputpre) {
			var charcode = char.charCodeAt();
			if (charcode === 0x1B && !writeChar.esc) {
				writeChar.esc = 1;
				writeChar.num = '';
				return;
			}
			if (writeChar.esc === 1) {
				writeChar.esc = char === '[' ? 2 : 0;
			} else if (writeChar.esc === 2) {
				if (charcode < CHAR_CODE_0 || charcode > CHAR_CODE_9) {
					switch (char) {
						case 'H':
							outputpre.hidden = true;
							utils.clearChildren(outputpre);
							target = replaceTerminalTarget(writeString.target.cloneNode(false), outputpre);
							break;
						case 'm':
							handleTerminalStyle(writeChar.num);
							break;
					}
					writeChar.esc = 0;
				} else {
					writeChar.num += char;
				}
			} else {
				outputpre.hidden = false;
				target.textContent += char;
			}
		}

		function replaceTerminalTarget(target, outputpre) {
			outputpre.insertBefore(target, null);
			writeString.target = target;
			return target;
		}

		function handleTerminalStyle(string) {
			console.log(`Format: ${string}`);
		}

		function closePaneItem() {
			setTimeout(() => handleCommon.paneItem.destroy());
		}

		main(elements, param);

	}

})(module);
<commit_msg>complete handle-terminal-format<commit_after>
(function (module) {
	'use strict';

	var copySelection = require('ksxatomsupports').clipboard.copySelection;
	var utils = require('../lib/utils.js');
	var ConsoleHistory = require('../lib/console-history.js');
	var specialcmds = require('../lib/special-commands.js');
	var getStyle = require('../lib/terminal-styles.js');

	var compareSequence = utils.compareSequence.iterable;

	const ENTER_KEY = 0x0D;
	const ESC_KEY = 0x1B;
	const KEY_UP = 0x26;
	const KEY_DOWN = 0x28;
	const CHAR_CODE_0 = '0'.charCodeAt();
	const CHAR_CODE_9 = '9'.charCodeAt();
	const MINI_EDITOR = Object.freeze({mini: true});
	const OUT_INPUT = Object.freeze(['from-input', 'text-normal']);
	const OUT_DATA = Object.freeze(['from-data', 'text-normal']);
	const OUT_ERROR = Object.freeze(['text-error']);

	module.exports = (elements, param) => {

		function SpecialCommandsParam(command, elements) {
			this.command = command;
			this.elements = elements;
		}

		SpecialCommandsParam.prototype = {
			handleData: handleData,
			handleError: handleError,
			handleClose: handleClose,
			writeStdIn: writeStdIn,
			writeString: writeString,
			writeChar: writeChar,
			closePaneItem: closePaneItem
		};

		function main(elements, param) {
			handleCommon(elements, param);
			handleConfig(elements, param.fromConfig);
			handleCloseEvent(elements, param.process);
			handleStdIn(elements, param.process.stdin);
			handleStdOut(elements, param.process.stdout);
			handleStdErr(elements, param.process.stderr);
		}

		function handleCommon(elements, param) {
			elements.descriptiondiv.textContent = `Running: ${param.fromScript.path}`;
			((proto) => {
				proto.process = param.process;
				proto.services = param.services;
				proto.fromConfig = param.fromConfig;
				proto.fromScript = param.fromScript;
			})(SpecialCommandsParam.prototype);
			handleCommon.handlePromise = param.handlePromise;
		}

		function handleConfig(elements, config) {
			enterStdIn.write = config.hideInputText ? () => {} : writeString;
			handleClose.considerClosePaneItem = config.closeOnExit ? closePaneItem : () => {};
			handleSpecialCommand(config);
		}

		function handleCloseEvent(elements, process) {
			process.on('close', handleClose.bind(null, elements));
			process.on('error', (error) => handleError(elements, String(error)));
			handleCommon.handlePromise((paneitem) => {
				handleCommon.paneItem = paneitem;
				paneitem.onDidDestroy(() => process.kill());
			});
		}

		function handleSpecialCommand(config) {
			var list = config.utils;
			if (list instanceof Array) {
				enterStdIn.handleSpecialCommand = (command, elements) => {
					for (let fname of list) {
						if (command === fname || !command.indexOf(`${fname}\x20`)) {
							try {
								return !specialcmds[fname](new SpecialCommandsParam(command, elements));
							} catch (error) {
								handleError(elements, `A JS error has occurred during execution of command '${command}'\nCommand may not be supported\n${error}\n`);
								handleData(elements, `Passing data to stdin by default...\n`);
								return false;
							}
						}
					}
				};
			} else {
				enterStdIn.handleSpecialCommand = () => {};
			}

		}

		function handleClose(elements, exitcode) {
			elements.finaloutputdiv.textContent = `Process finished, exit code: ${exitcode}`;
			elements.inputdiv.remove();
			handleClose.considerClosePaneItem();
		}

		function handleStdIn(elements, stdin) {
			if (!stdin) {
				return;
			}
			var editorutil = buildTextEditor(elements);
			handleControl(editorutil, elements, stdin);
			focusInputElement(editorutil);
			handleCommon.handlePromise((paneitem) => {
				paneitem.onDidActive(() => focusInputElement(editorutil));
				paneitem.acceptToBeClosed = () => editorutil.empty;
			});
			enterStdIn.history = new ConsoleHistory();
			elements.outputpre.hidden = true;
		}

		function focusInputElement(editorutil) {
			setTimeout(() => editorutil.element.focus());
		}

		function buildTextEditor(elements) {
			var editorutil = require('ksxatomsupports').editor.EditorUtil.new(MINI_EDITOR);
			elements.editordiv.insertBefore(editorutil.element, null);
			return editorutil;
		}

		function handleControl(editorutil, elements, stdin) {
			attachStdInEvent(editorutil.editor, editorutil.element, elements, stdin);
			makeConfirmButton(editorutil.editor, elements, stdin);
		}

		function attachStdInEvent(editor, element, elements, stdin) {
			var handle = handleKeyboardEvent.bind(null, stdin, editor, elements);
			element.addEventListener('keydown', handle, false);
		}

		function handleKeyboardEvent(stdin, editor, elements, event) {
			switch (event.keyCode) {
				case ENTER_KEY:
					return enterStdIn(stdin, editor, elements);
				case ESC_KEY:
					return void editor.setText('');
				case KEY_UP:
					return enterStdIn.history.up(editor);
				case KEY_DOWN:
					return enterStdIn.history.down(editor);
			}
		}

		function makeConfirmButton(editor, elements, stdin) {
			var handle = () => enterStdIn(stdin, editor, elements);
			elements.confirmbutton.addEventListener('click', handle, false);
		}

		function enterStdIn(stdin, editor, elements) {
			var text = editor.getText();
			editor.setText('');
			text && enterStdIn.history.add(text);
			enterStdIn.handleSpecialCommand(text, elements) || writeStdIn(stdin, new Buffer(`${text}\n`), editor.getEncoding(), elements.outputpre);
		}

		function writeStdIn(stdin, data, encoding, outputpre) {
			stdin.write(data, encoding);
			enterStdIn.write(outputpre, data, OUT_INPUT);
		}

		function handleStdOut(elements, stdout) {
			if (!stdout) return;
			stdout.on('data', handleData.bind(null, elements));
		}

		function handleData(elements, data) {
			writeString(elements.outputpre, `${data}`, OUT_DATA);
		}

		function handleStdErr(elements, stderr) {
			if (!stderr) return;
			stderr.on('data', handleError.bind(null, elements));
		}

		function handleError(elements, error) {
			writeString(elements.outputpre, `${error}\n`, OUT_ERROR);
		}

		function writeString(outputpre, string, extraclass) {
			if (!writeString.target || !compareSequence(extraclass, writeString.extraclass)) {
				writeString.extraclass = extraclass;
				replaceTerminalTarget(document.createElement('span'), outputpre);
				extraclass instanceof Array && extraclass.forEach((classname) => writeString.target.classList.add(classname));
				Object.assign(writeString.target.style, writeString.style);
			}
			for (let char of String(string)) {
				writeChar(writeString.target, char, outputpre);
			}
			outputpre.parentElement.scrollTop = outputpre.parentElement.scrollHeight;
		}

		function writeChar(target, char, outputpre) {
			var charcode = char.charCodeAt();
			if (charcode === 0x1B && !writeChar.esc) {
				writeChar.esc = 1;
				writeChar.num = '';
				return;
			}
			if (writeChar.esc === 1) {
				writeChar.esc = char === '[' ? 2 : 0;
			} else if (writeChar.esc === 2) {
				if (charcode < CHAR_CODE_0 || charcode > CHAR_CODE_9) {
					switch (char) {
						case 'H':
							outputpre.hidden = true;
							utils.clearChildren(outputpre);
							target = replaceTerminalTarget(writeString.target.cloneNode(false), outputpre);
							break;
						case 'm':
							handleTerminalStyle(writeChar.num, outputpre);
							break;
					}
					writeChar.esc = 0;
				} else {
					writeChar.num += char;
				}
			} else {
				outputpre.hidden = false;
				target.textContent += char;
			}
		}

		function replaceTerminalTarget(target, outputpre) {
			outputpre.insertBefore(target, null);
			writeString.target = target;
			return target;
		}

		function handleTerminalStyle(string, outputpre) {
			var target = replaceTerminalTarget(writeString.target.cloneNode(false), outputpre);
			var style = writeString.style = getStyle(string);
			Object.assign(target.style, style);
		}

		function closePaneItem() {
			setTimeout(() => handleCommon.paneItem.destroy());
		}

		main(elements, param);

	}

})(module);
<|endoftext|>


<commit_before>/**
 * # Instant Win
 *
 * A type of game where the player win or lose instantly.
 *
 * ## Parameters
 *
 * - `provider`: The identity provider to log with before playing. By default it
 *   will list all your identity providers.
 * - `delay`: Time in milliseconds to wait before displaying the game's results.
 *   By default the results are displayed imediatly after that the server tell
 *   us if the user has win or lost.
 */
define({
  type: 'Hull',

  templates: [
    /**
     * Show the button to play to the game.
     */
    'intro',
    /**
     * Show a loading message.
     */
    'working',
    /**
     * Say to the user that he has won
     */
    'won',
    /**
     * Say to the user that he has lost.
     */
    'lost',
    /**
     * Say to the user that he has already played.
     */
    'played',
    /**
     * Say to the user that the game hasn't started yet.
     */
    'unstarted',
    /**
     * Say to the user that the game has ended.
     */
    'ended'
  ],

  refreshEvents: ['model.hull.me.change'],

  datasources: {
    /**
     * The InstantWin achievement
     */
    achievement: function() {
      return this.api('hull/' + this.options.id);
    },
    /**
     * The user's badge for the InstantWin
     */
    badge: function() {
      return this.loggedIn() ? this.api('hull/me/badges/' + this.options.id) : null;
    }
  },

  actions: {
    /**
     * Ensure that the user is logged and call the `play` method.
     */
    play: function(source, event, data) {
      if (this.loggedIn()) {
        this.play();
      } else {
        var provider = data.provider || this.options.provider;
        Hull.login(provider, {}, _.bind(this.play, this));
      }
    }
  },

  initialize: function() {
      this.authProviders = _.map(this.sandbox.config.services.types.auth, function(s) {
        return s.replace(/_app$/, '');
      });
    },

    beforeRender: function(data) {
      this.template = this.getInitialTemplate();
      data.authProviders = this.authProviders;
    },

    afterRender: function() {
      this.sandbox.emit('hull.instant_win.' + this.options.id + '.template.render', this.template);
    },

    /**
     * Return the template name that the user should see when he lands on the
     * game.
     *
     * - `intro`: if the user hasn't played during the current day.
     * - `won`: if the user has won a prize.
     * - `played`: if the user has played during the current day.
     * - `unstarted`: if the game hasn't started.
     * - `ended`: if the game has ended.
     *
     * @return {String}
     */
    getInitialTemplate: function() {
      if (this.userHasWon()) {
        return 'won';
      } else if (this.hasEnded()) {
        return 'ended';
      } else if (this.hasStarted()) {
        return this.userCanPlay() ? 'intro' : 'played';
      } else {
        return 'unstarted';
      }
    },

    /**
     * Determine if the game has started. return `true` if it has `false` if it
     * hasn't.
     *
     * @return {Boolean}
     */
    hasStarted: function() {
      // TODO Need achievement `start_date`
      return true;
    },

    /**
     * Determine if the game has ended. Return `true` if it has `false` if it
     * hasn't.
     *
     * @return {Boolean}
     */
    hasEnded: function() {
      // TODO Need achievement `end_date`
      return false;
    },

    /**
     * Determine if the user can play. Return `true` if he can `false` if he
     * cannot.
     *
     * @return {Boolean}
     */
    userCanPlay: function() {
      if (!this.data.badge) { return true; }
      var d = new Date().toISOString().slice(0, 10);
      return !this.data.badge.data.attempts[d];
    },

    /**
     * Determine if user has won. Return `true` if the he has, `false` if he
     * hasn't.
     *
     * @return {Boolean}
   */
  userHasWon: function() {
    if (!this.data.badge) { return false; }
    return this.data.badge.data.winner;
  },

  /**
   * Play to the game and render a template:
   *
   * - `won`: if the user has won.
   * - `lost`: if the user has lost.
   * - `played`: if the user has played during the current day.
   *
   * When the function is called we render `working` and display it
   * until we know if the user has won.
   */
  play: function() {
    if (this.userHasWon()) { return; }

    var delay = this.wait(this.options.delay || 0);
    this.render('working');

    this.api('hull/' + this.id + '/achieve', 'post', _.bind(function(res) {
      var template = 'played';
      if (this.userCanPlay()) {
        template = res.data.winner ? 'won' : 'lost';
      }
      delay.then(_.bind(function() {
        this.render(template);
      }, this));
    }, this));
  },

  /**
   * Wait a given `time` before resolving the returned deferred.
   *
   * @param {Integer} time Number of milliseconds to wait.
   * @return {Promise}
   */
  wait: function(time) {
    var deferred = this.sandbox.data.deferred();
    time = parseInt(time, 10) || 0;

    if (time <= 0) {
      deferred.resolve();
    } else {
      setTimeout(deferred.resolve, time);
    }

    return deferred.promise();
  }
});
<commit_msg>Fix indentation<commit_after>/**
 * # Instant Win
 *
 * A type of game where the player win or lose instantly.
 *
 * ## Parameters
 *
 * - `provider`: The identity provider to log with before playing. By default it
 *   will list all your identity providers.
 * - `delay`: Time in milliseconds to wait before displaying the game's results.
 *   By default the results are displayed imediatly after that the server tell
 *   us if the user has win or lost.
 */
define({
  type: 'Hull',

  templates: [
    /**
     * Show the button to play to the game.
     */
    'intro',
    /**
     * Show a loading message.
     */
    'working',
    /**
     * Say to the user that he has won
     */
    'won',
    /**
     * Say to the user that he has lost.
     */
    'lost',
    /**
     * Say to the user that he has already played.
     */
    'played',
    /**
     * Say to the user that the game hasn't started yet.
     */
    'unstarted',
    /**
     * Say to the user that the game has ended.
     */
    'ended'
  ],

  refreshEvents: ['model.hull.me.change'],

  datasources: {
    /**
     * The InstantWin achievement
     */
    achievement: function() {
      return this.api('hull/' + this.options.id);
    },
    /**
     * The user's badge for the InstantWin
     */
    badge: function() {
      return this.loggedIn() ? this.api('hull/me/badges/' + this.options.id) : null;
    }
  },

  actions: {
    /**
     * Ensure that the user is logged and call the `play` method.
     */
    play: function(source, event, data) {
      if (this.loggedIn()) {
        this.play();
      } else {
        var provider = data.provider || this.options.provider;
        Hull.login(provider, {}, _.bind(this.play, this));
      }
    }
  },

  initialize: function() {
    this.authProviders = _.map(this.sandbox.config.services.types.auth, function(s) {
      return s.replace(/_app$/, '');
    });
  },

  beforeRender: function(data) {
    this.template = this.getInitialTemplate();

    data.authProviders = this.authProviders;
  },

  afterRender: function() {
    this.sandbox.emit('hull.instant_win.' + this.options.id + '.template.render', this.template);
  },

  /**
   * Return the template name that the user should see when he lands on the
   * game.
   *
   * - `intro`: if the user hasn't played during the current day.
   * - `won`: if the user has won a prize.
   * - `played`: if the user has played during the current day.
   * - `unstarted`: if the game hasn't started.
   * - `ended`: if the game has ended.
   *
   * @return {String}
   */
  getInitialTemplate: function() {
    if (this.userHasWon()) {
      return 'won';
    } else if (this.hasEnded()) {
      return 'ended';
    } else if (this.hasStarted()) {
      return this.userCanPlay() ? 'intro' : 'played';
    } else {
      return 'unstarted';
    }
  },

  /**
   * Determine if the game has started. return `true` if it has `false` if it
   * hasn't.
   *
   * @return {Boolean}
   */
  hasStarted: function() {
    // TODO Need achievement `start_date`
    return true;
  },

  /**
   * Determine if the game has ended. Return `true` if it has `false` if it
   * hasn't.
   *
   * @return {Boolean}
   */
  hasEnded: function() {
    // TODO Need achievement `end_date`
    return false;
  },

  /**
   * Determine if the user can play. Return `true` if he can `false` if he
   * cannot.
   *
   * @return {Boolean}
   */
  userCanPlay: function() {
    if (!this.data.badge) { return true; }
    var d = new Date().toISOString().slice(0, 10);
    return !this.data.badge.data.attempts[d];
  },

  /**
   * Determine if user has won. Return `true` if the he has, `false` if he
   * hasn't.
   *
   * @return {Boolean}
   */
  userHasWon: function() {
    if (!this.data.badge) { return false; }
    return this.data.badge.data.winner;
  },

  /**
   * Play to the game and render a template:
   *
   * - `won`: if the user has won.
   * - `lost`: if the user has lost.
   * - `played`: if the user has played during the current day.
   *
   * When the function is called we render `working` and display it
   * until we know if the user has won.
   */
  play: function() {
    if (this.userHasWon()) { return; }

    var delay = this.wait(this.options.delay || 0);
    this.render('working');

    this.api('hull/' + this.id + '/achieve', 'post', _.bind(function(res) {
      var template = 'played';
      if (this.userCanPlay()) {
        template = res.data.winner ? 'won' : 'lost';
      }
      delay.then(_.bind(function() {
        this.render(template);
      }, this));
    }, this));
  },

  /**
   * Wait a given `time` before resolving the returned deferred.
   *
   * @param {Integer} time Number of milliseconds to wait.
   * @return {Promise}
   */
  wait: function(time) {
    var deferred = this.sandbox.data.deferred();
    time = parseInt(time, 10) || 0;

    if (time <= 0) {
      deferred.resolve();
    } else {
      setTimeout(deferred.resolve, time);
    }

    return deferred.promise();
  }
});
<|endoftext|>


<commit_before>var boards = {
  'uno': {
    baud: 115200,
    signature: new Buffer([0x1e, 0x95, 0x0f]),
    pageSize: 128,
    numPages: 256,
    timeout: 400,
    productId: ['0x0043', '0x7523'],
    protocol: 'stk500v1'
  },
  'micro': {
    baud: 57600,
    signature: new Buffer([0x43, 0x41, 0x54, 0x45, 0x52, 0x49, 0x4e]),
    productId: ['0x0037', '0x8037'],
    protocol: 'avr109'
  },
  'imuduino': {
    baud: 57600,
    signature: new Buffer([0x43, 0x41, 0x54, 0x45, 0x52, 0x49, 0x4e]),
    productId: ['0x0036', '0x8037', '0x8036'],
    protocol: 'avr109'
  },
  'leonardo': {
    baud: 57600,
    signature: new Buffer([0x43, 0x41, 0x54, 0x45, 0x52, 0x49, 0x4e]),
    productId: ['0x0036', '0x8036'],
    protocol: 'avr109'
  },
  'little-bits': {
    baud: 57600,
    signature: new Buffer([0x43, 0x41, 0x54, 0x45, 0x52, 0x49, 0x4e]),
    productId: ['0x0036', '0x8036'],
    protocol: 'avr109'
  },
  'blend-micro': {
    baud: 57600,
    signature: new Buffer([0x43, 0x41, 0x54, 0x45, 0x52, 0x49, 0x4e]),
    productId: ['0x2404'],
    protocol: 'avr109'
  },
  'nano': {
    baud: 57600,
    signature: new Buffer([0x1e, 0x95, 0x0f]),
    pageSize: 128,
    numPages: 256,
    timeout: 400,
    productId: ['0x6001', '0x7523'],
    protocol: 'stk500v1'
  },
  'duemilanove168': {
    baud: 19200,
    signature: new Buffer([0x1e, 0x94, 0x06]),
    pageSize: 128,
    numPages: 128,
    timeout: 400,
    productId: ['0x6001'],
    protocol: 'stk500v1'
  },
  'tinyduino': {
    baud: 57600,
    signature: new Buffer([0x1e, 0x95, 0x0f]),
    pageSize: 128,
    numPages: 256,
    timeout: 400,
    productId: ['0x6015'],
    protocol: 'stk500v1'
  },
  'mega': {
    baud: 115200,
    signature: new Buffer([0x1e, 0x98, 0x01]), // ATmega2560
    pageSize: 256,
    delay1: 10,
    delay2: 1,
    timeout:0xc8,
    stabDelay:0x64,
    cmdexeDelay:0x19,
    synchLoops:0x20,
    byteDelay:0x00,
    pollValue:0x53,
    pollIndex:0x03,
    productId: ['0x0042', '0x6001'],
    protocol: 'stk500v2'
  },
  'sf-pro-micro': {
    baud: 57600,
    signature: new Buffer([0x43, 0x41, 0x54, 0x45, 0x52, 0x49, 0x4e]),
    productId: ['0x9206'],
    protocol: 'avr109'
  },
  'pro-mini': {
    baud: 57600,
    signature: new Buffer([0x1e, 0x95, 0x0f]),
    pageSize: 128,
    numPages: 256,
    timeout: 400,
    protocol: 'stk500v1'
  },
  'qduino': {
    baud: 57600,
    signature: new Buffer([0x43, 0x41, 0x54, 0x45, 0x52, 0x49, 0x4e]),
    productId: ['0x516d'],
    protocol: 'avr109'
  },
  'pinoccio': {
    baud: 115200,
    signature: new Buffer([0x1e, 0xa8, 0x02]), // ATmega256RFR2
    pageSize: 256,
    delay1: 10,
    delay2: 1,
    timeout:0xc8,
    stabDelay:0x64,
    cmdexeDelay:0x19,
    synchLoops:0x20,
    byteDelay:0x00,
    pollValue:0x53,
    pollIndex:0x03,
    productId: ['0x6051'],
    protocol: 'stk500v2'
  }
};

/**
 * Generate a reverse lookup table by pid mapped to possible board names.
 * @return {object} byPid
 */
function pidLookupTable() {
  var byPid = {};
  var boardNames = Object.keys( boards );
  for (var i=0;i<boardNames.length;i++) {
    var boardName = boardNames[i];
    var board = boards[ boardName ];
    if (board.productId) {
      for (var j=0;j<board.productId.length;j++) {
        var productId = board.productId[j];
        byPid[ productId ] = byPid[ productId ] || [];
        byPid[ productId ].push( boardName );
      }
    }
  }
  return byPid;
}

module.exports = {
  byName: boards,
  byPid: pidLookupTable()
}
<commit_msg>add feather support to boards<commit_after>var boards = {
  'uno': {
    baud: 115200,
    signature: new Buffer([0x1e, 0x95, 0x0f]),
    pageSize: 128,
    numPages: 256,
    timeout: 400,
    productId: ['0x0043', '0x7523'],
    protocol: 'stk500v1'
  },
  'micro': {
    baud: 57600,
    signature: new Buffer([0x43, 0x41, 0x54, 0x45, 0x52, 0x49, 0x4e]),
    productId: ['0x0037', '0x8037'],
    protocol: 'avr109'
  },
  'imuduino': {
    baud: 57600,
    signature: new Buffer([0x43, 0x41, 0x54, 0x45, 0x52, 0x49, 0x4e]),
    productId: ['0x0036', '0x8037', '0x8036'],
    protocol: 'avr109'
  },
  'leonardo': {
    baud: 57600,
    signature: new Buffer([0x43, 0x41, 0x54, 0x45, 0x52, 0x49, 0x4e]),
    productId: ['0x0036', '0x8036', '0x800c'],
    protocol: 'avr109'
  },
  'feather': {
    baud: 57600,
    signature: new Buffer([0x43, 0x41, 0x54, 0x45, 0x52, 0x49, 0x4e]),
    productId: ['0x800c'],
    protocol: 'avr109'
  },
  'little-bits': {
    baud: 57600,
    signature: new Buffer([0x43, 0x41, 0x54, 0x45, 0x52, 0x49, 0x4e]),
    productId: ['0x0036', '0x8036'],
    protocol: 'avr109'
  },
  'blend-micro': {
    baud: 57600,
    signature: new Buffer([0x43, 0x41, 0x54, 0x45, 0x52, 0x49, 0x4e]),
    productId: ['0x2404'],
    protocol: 'avr109'
  },
  'nano': {
    baud: 57600,
    signature: new Buffer([0x1e, 0x95, 0x0f]),
    pageSize: 128,
    numPages: 256,
    timeout: 400,
    productId: ['0x6001', '0x7523'],
    protocol: 'stk500v1'
  },
  'duemilanove168': {
    baud: 19200,
    signature: new Buffer([0x1e, 0x94, 0x06]),
    pageSize: 128,
    numPages: 128,
    timeout: 400,
    productId: ['0x6001'],
    protocol: 'stk500v1'
  },
  'tinyduino': {
    baud: 57600,
    signature: new Buffer([0x1e, 0x95, 0x0f]),
    pageSize: 128,
    numPages: 256,
    timeout: 400,
    productId: ['0x6015'],
    protocol: 'stk500v1'
  },
  'mega': {
    baud: 115200,
    signature: new Buffer([0x1e, 0x98, 0x01]), // ATmega2560
    pageSize: 256,
    delay1: 10,
    delay2: 1,
    timeout:0xc8,
    stabDelay:0x64,
    cmdexeDelay:0x19,
    synchLoops:0x20,
    byteDelay:0x00,
    pollValue:0x53,
    pollIndex:0x03,
    productId: ['0x0042', '0x6001'],
    protocol: 'stk500v2'
  },
  'sf-pro-micro': {
    baud: 57600,
    signature: new Buffer([0x43, 0x41, 0x54, 0x45, 0x52, 0x49, 0x4e]),
    productId: ['0x9206'],
    protocol: 'avr109'
  },
  'pro-mini': {
    baud: 57600,
    signature: new Buffer([0x1e, 0x95, 0x0f]),
    pageSize: 128,
    numPages: 256,
    timeout: 400,
    protocol: 'stk500v1'
  },
  'qduino': {
    baud: 57600,
    signature: new Buffer([0x43, 0x41, 0x54, 0x45, 0x52, 0x49, 0x4e]),
    productId: ['0x516d'],
    protocol: 'avr109'
  },
  'pinoccio': {
    baud: 115200,
    signature: new Buffer([0x1e, 0xa8, 0x02]), // ATmega256RFR2
    pageSize: 256,
    delay1: 10,
    delay2: 1,
    timeout:0xc8,
    stabDelay:0x64,
    cmdexeDelay:0x19,
    synchLoops:0x20,
    byteDelay:0x00,
    pollValue:0x53,
    pollIndex:0x03,
    productId: ['0x6051'],
    protocol: 'stk500v2'
  }
};

/**
 * Generate a reverse lookup table by pid mapped to possible board names.
 * @return {object} byPid
 */
function pidLookupTable() {
  var byPid = {};
  var boardNames = Object.keys( boards );
  for (var i=0;i<boardNames.length;i++) {
    var boardName = boardNames[i];
    var board = boards[ boardName ];
    if (board.productId) {
      for (var j=0;j<board.productId.length;j++) {
        var productId = board.productId[j];
        byPid[ productId ] = byPid[ productId ] || [];
        byPid[ productId ].push( boardName );
      }
    }
  }
  return byPid;
}

module.exports = {
  byName: boards,
  byPid: pidLookupTable()
}
<|endoftext|>