<commit_before>var drag = function(el, dx, dy, complete) {

	// speed = sync -> Drag syncrhonously.
	// speed = fast|slow -> Drag asyncrhonously - animated.

	return $(el).simulate("drag", {
		dx: dx||0, dy: dy||0, speed: 'sync', complete: complete
	});
};

module("Draggable");

test("create and destroy", function() {

	expect(2);

	$("#draggable1").draggable();
	ok($("#draggable1").data("draggable"), "Accessing draggable instance after creation");

	$("#draggable1").draggable("destroy");
	ok(!$("#draggable1").data("draggable"), "Accessing draggable instance after destroy");

});

test("No options, relative", function() {

	expect(4);

	$("#draggable1").draggable();

	var offset = $("#draggable1").data("draggable").element.offset();
	equals(offset.left, -979, "Checking initial left position");
	equals(offset.top, -979, "Checking initial top position");

	drag("#draggable1", 50, 50);

	var offset = $("#draggable1").data("draggable").element.offset();
	equals(offset.left, -929, "Checking new left position");
	equals(offset.top, -929, "Checking new top position");

});

test("No options, absolute", function() {

	expect(4);

	$("#draggable2").draggable();

	var offset = $("#draggable2").data("draggable").element.offset();
	equals(offset.left, -979, "Checking initial left position");
	equals(offset.top, -979, "Checking initial top position");

	drag("#draggable2", 50, 50);

	var offset = $("#draggable2").data("draggable").element.offset();
	equals(offset.left, -929, "Checking new left position");
	equals(offset.top, -929, "Checking new top position");

});

test("{ helper: 'clone' }", function() {

	expect(4);

	$("#draggable1, #draggable2").draggable({ helper: "clone" });

	drag("#draggable1, #draggable2", 50, 50);

	var offset = $("#draggable1").data("draggable").element.offset();
	equals(offset.left, -979, "Relative: Original position should be untouched");
	equals(offset.top, -979, "Relative: Original position should be untouched");

	var offset = $("#draggable2").data("draggable").element.offset();
	equals(offset.left, -979, "Absolute: Original position should be untouched");
	equals(offset.top, -979, "Absolute: Original position should be untouched");

});

test("{ grid: [50,50] }", function() {

	expect(4);

	$("#draggable1, #draggable2").draggable({ grid: [50,50] });

	drag("#draggable1, #draggable2", 30, 30);

	var offset = $("#draggable1").data("draggable").element.offset();
	equals(offset.left, -929, "Relative: 50px move in grid");
	equals(offset.top, -929, "Relative: 50px move in grid");

	var offset = $("#draggable2").data("draggable").element.offset();
	equals(offset.left, -929, "Absolute: 50px move in grid");
	equals(offset.top, -929, "Absolute: 50px move in grid");

});

test("{ axis: 'y' }", function() {

	expect(4);

	$("#draggable1, #draggable2").draggable({ axis: "y" });

	drag("#draggable1, #draggable2", 50, 50);

	var offset = $("#draggable1").data("draggable").element.offset();
	equals(offset.left, -979, "Relative: 0px move");
	equals(offset.top, -929, "Relative: 50px move");

	var offset = $("#draggable2").data("draggable").element.offset();
	equals(offset.left, -979, "Absolute: 0px move");
	equals(offset.top, -929, "Absolute: 50px move");

});

test("{ axis: 'x' }", function() {

	expect(4);

	$("#draggable1, #draggable2").draggable({ axis: "x" });

	drag("#draggable1, #draggable2", 50, 50);

	var offset = $("#draggable1").data("draggable").element.offset();
	equals(offset.left, -929, "Relative: 50px move");
	equals(offset.top, -979, "Relative: 0px move");

	var offset = $("#draggable2").data("draggable").element.offset();
	equals(offset.left, -929, "Absolute: 50px move");
	equals(offset.top, -979, "Absolute: 0px move");

});

test("{ cancel: 'span' }", function() {

	expect(2);

	$("#draggable2").draggable({ cancel: 'span' });

	drag("#draggable2 span", 50, 50);

	var offset = $("#draggable2").data("draggable").element.offset();
	equals(offset.left, -979, "Trigger on span: 0px move");
	equals(offset.top, -979, "Trigger on span: 0px move");

});

test("{ handle: 'span' }", function() {

	expect(4);

	$("#draggable2").draggable({ handle: 'span' });

	drag("#draggable2 span", 50, 50);

	var offset = $("#draggable2").data("draggable").element.offset();
	equals(offset.left, -929, "Trigger on span: 50px move");
	equals(offset.top, -929, "Trigger on span: 50px move");

	drag("#draggable2", 50, 50);

	var offset = $("#draggable2").data("draggable").element.offset();
	equals(offset.left, -929, "Trigger on element: 0px move");
	equals(offset.top, -929, "Trigger on element: 0px move");

});

test("{ containment: 'parent' }", function() {

	expect(4);

	$("#draggable2, #draggable1").draggable({ containment: 'parent' });

	drag("#draggable2, #draggable1", -100, -100);

	var offset = $("#draggable2").data("draggable").element.offset();
	equals(offset.left, -989, "Absolute: 10px move (to parent's margin end)");
	equals(offset.top, -989, "Absolute: 10px move (to parent's margin end)");

	var offset = $("#draggable1").data("draggable").element.offset();
	equals(offset.left, -989, "Relative: 10px move (to parent's margin end)");
	equals(offset.top, -989, "Relative: 10px move (to parent's margin end)");

});

test("{ cursorAt: { left: -5, top: -5 } }", function() {

	expect(4);

	var position = null;
	$("#draggable2").draggable({
		cursorAt: { left: -5, top: -5 },
		drag: function(e, ui) {
			position = ui.absolutePosition;
		}
	});

	drag("#draggable2", -1, -1);

	equals(position.left, -875, "Absolute: -1px move");
	equals(position.top, -925, "Absolute: -1px move");

	var position = null;
	$("#draggable1").draggable({
		cursorAt: { left: -5, top: -5 },
		drag: function(e, ui) {
			position = ui.absolutePosition;
		}
	});

	drag("#draggable1", -1, -1);

	equals(position.left, -875, "Relative: -1px move");
	equals(position.top, -925, "Relative: -1px move");

});

test("{ cursor: 'move' }", function() {

	expect(2);

	var cursor = null;
	$("#draggable2").draggable({
		cursor: "move",
		start: function(e, ui) {
			cursor = $("body").css("cursor");
		}
	});

	drag("#draggable2", -1, -1);

	equals(cursor, "move", "start callback: cursor 'move'");
	equals($("body").css("cursor"), "auto", "after drag: cursor restored");

});

test("{ distance: 10 }", function() {

	expect(2);

	var dragged = false;
	$("#draggable2").draggable({
		distance: 10,
		start: function(e, ui) {
			dragged = true;
		}
	});

	drag("#draggable2", -9, -9);
	equals(dragged, false, "The draggable should not have moved when moving -9px");

	drag("#draggable2", -10, -10);
	equals(dragged, true, "The draggable should have moved when moving -10px");

});

test("{ opacity: 0.5 }", function() {

	expect(1);

	var opacity = null;
	$("#draggable2").draggable({
		opacity: 0.5,
		start: function(e, ui) {
			opacity = $(this).css("opacity");
		}
	});

	drag("#draggable2", -1, -1);

	equals(opacity, 0.5, "start callback: opacity is 0.5");

});

test("{ zIndex: 10 }", function() {

	expect(1);

	var zIndex = null;
	$("#draggable2").draggable({
		zIndex: 10,
		start: function(e, ui) {
			zIndex = $(this).css("zIndex");
		}
	});

	drag("#draggable2", -1, -1);

	equals(zIndex, "10", "start callback: zIndex is 10");

});

test("callbacks occurance count", function() {

	expect(3);

	var start = 0, stop = 0, dragc = 0;
	$("#draggable2").draggable({
		start: function() { start++; },
		drag: function() { dragc++; },
		stop: function() { stop++; }
	});

	drag("#draggable2", 10, 10);

	equals(start, 1, "start callback should happen exactly once");
	equals(dragc, 11, "drag callback should happen exactly 1+10 times (first simultaneously with start)");
	equals(stop, 1, "stop callback should happen exactly once");

});

<commit_msg>made draggable tests more robust by removing hardcoded expect values<commit_after>/*
 * draggable tests
 */

var drag = function(el, dx, dy, complete) {

	// speed = sync -> Drag syncrhonously.
	// speed = fast|slow -> Drag asyncrhonously - animated.

	return $(el).simulate("drag", {
		dx: dx||0, dy: dy||0, speed: 'sync', complete: complete
	});
};

module("Draggable");

test("create and destroy", function() {

	expect(2);

	$("#draggable1").draggable();
	ok($("#draggable1").data("draggable"), "Accessing draggable instance after creation");

	$("#draggable1").draggable("destroy");
	ok(!$("#draggable1").data("draggable"), "Accessing draggable instance after destroy");

});

test("No options, relative", function() {

	expect(2);

	var dx = 50, dy = 50;

	$("#draggable1").draggable();
	var el = $("#draggable1").data("draggable").element;

	var before = el.offset();
	drag("#draggable1", dx, dy);
	var after = el.offset();

	equals(after.left, before.left + dx, "Checking new left position");
	equals(after.top, before.top + dy, "Checking new top position");

});

test("No options, absolute", function() {

	expect(2);

	var dx = 50, dy = 50;

	$("#draggable2").draggable();
	var el = $("#draggable2").data("draggable").element;

	var before = el.offset();
	drag("#draggable2", dx, dy);
	var after = el.offset();

	equals(after.left, before.left + dx, "Checking new left position");
	equals(after.top, before.top + dy, "Checking new top position");

});

test("{ helper: 'clone' }", function() {

	expect(4);

	var dx = 50, dy = 50;

	$("#draggable1, #draggable2").draggable({ helper: "clone" });
	var el1 = $("#draggable1").data("draggable").element;
	var el2 = $("#draggable2").data("draggable").element;

	var before1 = el1.offset();
	var before2 = el2.offset();
	drag("#draggable1, #draggable2", dx, dy);
	var after1 = el1.offset();
	var after2 = el2.offset();

	equals(after1.left, before1.left, "Relative: Original position should be untouched");
	equals(after1.top, before1.top, "Relative: Original position should be untouched");

	equals(after2.left, before2.left, "Absolute: Original position should be untouched");
	equals(after2.top, before2.top, "Absolute: Original position should be untouched");

});

test("{ grid: [50,50] }", function() {

	expect(4);

	var gx = 50, gy = 50;
	var dx = gx / 2 + 1, dy = gy / 2 + 1;

	$("#draggable1, #draggable2").draggable({ grid: [gx, gy] });
	var el1 = $("#draggable1").data("draggable").element;
	var el2 = $("#draggable2").data("draggable").element;

	var before1 = el1.offset();
	var before2 = el2.offset();
	drag("#draggable1, #draggable2", dx, dy);
	var after1 = el1.offset();
	var after2 = el2.offset();

	equals(after1.left, before1.left + gx, "Relative: 50px move in grid");
	equals(after1.top, before1.top + gy, "Relative: 50px move in grid");

	equals(after2.left, before2.left + gx, "Absolute: 50px move in grid");
	equals(after2.top, before2.top + gy, "Absolute: 50px move in grid");

});

test("{ grid: [50,50] }", function() {

	expect(4);

	var gx = 50, gy = 50;
	var dx = gx / 2 - 1, dy = gy / 2 - 1;

	$("#draggable1, #draggable2").draggable({ grid: [gx, gy] });
	var el1 = $("#draggable1").data("draggable").element;
	var el2 = $("#draggable2").data("draggable").element;

	var before1 = el1.offset();
	var before2 = el2.offset();
	drag("#draggable1, #draggable2", dx, dy);
	var after1 = el1.offset();
	var after2 = el2.offset();

	equals(after1.left, before1.left, "Relative: 50px move in grid");
	equals(after1.top, before1.top, "Relative: 50px move in grid");

	equals(after2.left, before2.left, "Absolute: 50px move in grid");
	equals(after2.top, before2.top, "Absolute: 50px move in grid");

});

test("{ axis: 'y' }", function() {

	expect(4);

	var dx = 50, dy = 50;

	$("#draggable1, #draggable2").draggable({ axis: "y" });
	var el1 = $("#draggable1").data("draggable").element;
	var el2 = $("#draggable2").data("draggable").element;

	var before1 = el1.offset();
	var before2 = el2.offset();
	drag("#draggable1, #draggable2", dx, dy);
	var after1 = el1.offset();
	var after2 = el2.offset();

	equals(after1.left, before1.left, "Relative: 0px move");
	equals(after1.top, before1.top + dy, "Relative: 50px move");

	equals(after2.left, before2.left, "Absolute: 0px move");
	equals(after2.top, before2.top + dy, "Absolute: 50px move");

});

test("{ axis: 'x' }", function() {

	expect(4);

	var dx = 50, dy = 50;

	$("#draggable1, #draggable2").draggable({ axis: "x" });
	var el1 = $("#draggable1").data("draggable").element;
	var el2 = $("#draggable2").data("draggable").element;

	var before1 = el1.offset();
	var before2 = el2.offset();
	drag("#draggable1, #draggable2", dx, dy);
	var after1 = el1.offset();
	var after2 = el2.offset();

	equals(after1.left, before1.left + dx, "Relative: 0px move");
	equals(after1.top, before1.top, "Relative: 50px move");

	equals(after2.left, before2.left + dy, "Absolute: 0px move");
	equals(after2.top, before2.top, "Absolute: 50px move");

});

test("{ cancel: 'span' }", function() {

	expect(4);

	var dx = 50, dy = 50;

	$("#draggable2").draggable({ cancel: 'span' });
	var el = $("#draggable2").data("draggable").element;

	var before = el.offset();
	drag("#draggable2 span", dx, dy);
	var after = el.offset();

	equals(after.left, before.left, "Trigger on span: 0px move");
	equals(after.top, before.top, "Trigger on span: 0px move");

	var before = el.offset();
	drag("#draggable2", dx, dy);
	var after = el.offset();

	equals(after.left, before.left + dx, "Trigger on element: 50px move");
	equals(after.top, before.top + dy, "Trigger on element: 50px move");

});

test("{ handle: 'span' }", function() {

	expect(4);

	var dx = 50, dy = 50;

	$("#draggable2").draggable({ handle: 'span' });
	var el = $("#draggable2").data("draggable").element;

	var before = el.offset();
	drag("#draggable2 span", dx, dy);
	var after = el.offset();

	equals(after.left, before.left + dx, "Trigger on span: 50px move");
	equals(after.top, before.top + dy, "Trigger on span: 50px move");

	var before = el.offset();
	drag("#draggable2", dx, dy);
	var after = el.offset();

	equals(after.left, before.left, "Trigger on element: 0px move");
	equals(after.top, before.top, "Trigger on element: 0px move");

});

test("{ containment: 'parent' }", function() {

	function border(el, side) { return parseInt(el.css('border-' + side + '-width')); }

	expect(4);

	var dx = -100, dy = -100;

	$("#draggable1, #draggable2").draggable({ containment: 'parent' });
	var el1 = $("#draggable1").data("draggable").element;
	var el2 = $("#draggable2").data("draggable").element;

	var before1 = el1.offset();
	var before2 = el2.offset();
	drag("#draggable1, #draggable2", dx, dy);
	var after1 = el1.offset();
	var after2 = el2.offset();

	var p1 = $("#draggable1").parent(), po1 = p1.offset();
	var p2 = $("#draggable2").parent(), po2 = p2.offset();
	var b1 = { left: border(p1, 'left'), top: border(p1, 'top') };
	var b2 = { left: border(p2, 'left'), top: border(p2, 'top') };

	equals(after1.left, po1.left + b1.left, "Absolute: " + (before1.left - po1.left + b1.left) + "px move (to parent's margin end)");
	equals(after1.top, po1.top + b1.top, "Absolute: " + (before1.top - po1.top + b1.top) + "px move (to parent's margin end)");

	equals(after2.left, po2.left + b2.left, "Relative: " + (before2.left - po2.left + b2.left) + "move (to parent's margin end)");
	equals(after2.top, po2.top + b2.top, "Relative: " + (before2.top - po2.top + b2.top) + "px move (to parent's margin end)");

});

test("{ cursorAt: { left: -5, top: -5 } }", function() {

	expect(4);

	var dx = -1, dy = -1;
	var ox = 5, oy = 5;
	var cax = -5, cay = -5;

	var actual = null;
	$("#draggable2").draggable({
		cursorAt: { left: cax, top: cay },
		drag: function(e, ui) {
			actual = ui.absolutePosition;
		}
	});
	var el = $("#draggable2").data("draggable").element;

	var before = el.offset();
	var pos = { clientX: before.left + ox, clientY: before.top + oy };
	$("#draggable2").simulate("mousedown", pos);
	pos = { clientX: pos.clientX + dx, clientY: pos.clienY + dy };
	$(document).simulate("mousedown", pos);
	$(document).simulate("mousedown", pos);
	$("#draggable2").simulate("mouseup", pos);
	var expected = { left: before.left + ox - cax, top: before.top + oy - cay };

	equals(actual.left, expected.left, "Absolute: -1px left");
	equals(actual.top, expected.top, "Absolute: -1px top");

	var actual = null;
	$("#draggable1").draggable({
		cursorAt: { left: cax, top: cay },
		drag: function(e, ui) {
			actual = ui.absolutePosition;
		}
	});
	var el = $("#draggable2").data("draggable").element;

	var before = el.offset();
	var pos = { clientX: before.left + ox, clientY: before.top + oy };
	$("#draggable2").simulate("mousedown", pos);
	pos = { clientX: pos.clientX + dx, clientY: pos.clienY + dy };
	$(document).simulate("mousedown", pos);
	$(document).simulate("mousedown", pos);
	$("#draggable2").simulate("mouseup", pos);
	var expected = { left: before.left + ox - cax, top: before.top + oy - cay };

	equals(actual.left, expected.left, "Relative: -1px left");
	equals(actual.top, expected.top, "Relative: -1px top");

});

test("{ cursor: 'move' }", function() {

	function getCursor() { return $("body").css("cursor"); }

	expect(2);

	var expected = "move", actual, before, after;

	$("#draggable2").draggable({
		cursor: expected,
		start: function(e, ui) {
			actual = getCursor();
		}
	});

	before = getCursor();
	drag("#draggable2", -1, -1);
	after = getCursor();

	equals(actual, expected, "start callback: cursor '" + expected + "'");
	equals(after, before, "after drag: cursor restored");

});

test("{ distance: 10 }", function() {

	expect(3);

	var dragged;
	$("#draggable2").draggable({
		distance: 10,
		start: function(e, ui) {
			dragged = true;
		}
	});

	dragged = false;
	drag("#draggable2", -9, -9);
	equals(dragged, false, "The draggable should not have moved when moving -9px");

	dragged = false;
	drag("#draggable2", -10, -10);
	equals(dragged, true, "The draggable should have moved when moving -10px");

	dragged = false;
	drag("#draggable2", 9, 9);
	equals(dragged, false, "The draggable should not have moved when moving 9px");

});

test("{ opacity: 0.5 }", function() {

	expect(1);

	var opacity = null;
	$("#draggable2").draggable({
		opacity: 0.5,
		start: function(e, ui) {
			opacity = $(this).css("opacity");
		}
	});

	drag("#draggable2", -1, -1);

	equals(opacity, 0.5, "start callback: opacity is");

});

test("{ zIndex: 10 }", function() {

	expect(1);

	var expected = 10, actual;

	var zIndex = null;
	$("#draggable2").draggable({
		zIndex: expected,
		start: function(e, ui) {
			actual = $(this).css("zIndex");
		}
	});

	drag("#draggable2", -1, -1);

	equals(actual, expected, "start callback: zIndex is");

});

test("callbacks occurance count", function() {

	expect(3);

	var start = 0, stop = 0, dragc = 0;
	$("#draggable2").draggable({
		start: function() { start++; },
		drag: function() { dragc++; },
		stop: function() { stop++; }
	});

	drag("#draggable2", 10, 10);

	equals(start, 1, "start callback should happen exactly once");
	equals(dragc, 11, "drag callback should happen exactly 1+10 times (first simultaneously with start)");
	equals(stop, 1, "stop callback should happen exactly once");

});
<|endoftext|>


<commit_before>var fs = require('file');

exports.Tech = function (name) {
    this.name = name;

    var tech = {};
    try { tech = require('./tech/' + name) } catch (e) {}
    try { tech = require(fs.absolute(name)) } catch (e) {}
    for (var name in tech)
        if (Object.prototype.hasOwnProperty.call(tech, name))
            this[name] = tech[name];

};

exports.Tech.prototype.filterExists = function (prefixes) {
    var _this = this,
        res = [];
    prefixes.forEach(function (prefix) {
        var file = fs.path(prefix + '.' + _this.name);
        file.exists() && res.push(file);
    });
    return res;
}

exports.Tech.prototype.outFile = function (file) {
    return file + '\n';
};

exports.Tech.prototype.outPrefixes = function (prefixes, outputDir, outputName) {
    var _this = this,
        content = '';
    this.filterExists(prefixes)
        .map(function (file) {
            return file.from(outputDir);
        })
        .forEach(function (file) {
            content += _this.outFile(file);
        });
    outputDir.join(outputName + '.' + this.name).write(content);
};
<commit_msg>Пытаемся искать модуль технологии по абсолютному пути, только если не удалось найти по имени<commit_after>var fs = require('file');

exports.Tech = function (name) {
    this.name = name;

    var tech = {};
    try { tech = require('./tech/' + name) } catch (e) {
        try { tech = require(fs.absolute(name)) } catch (e) {}
    }
    for (var name in tech)
        if (Object.prototype.hasOwnProperty.call(tech, name))
            this[name] = tech[name];

};

exports.Tech.prototype.filterExists = function (prefixes) {
    var _this = this,
        res = [];
    prefixes.forEach(function (prefix) {
        var file = fs.path(prefix + '.' + _this.name);
        file.exists() && res.push(file);
    });
    return res;
}

exports.Tech.prototype.outFile = function (file) {
    return file + '\n';
};

exports.Tech.prototype.outPrefixes = function (prefixes, outputDir, outputName) {
    var _this = this,
        content = '';
    this.filterExists(prefixes)
        .map(function (file) {
            return file.from(outputDir);
        })
        .forEach(function (file) {
            content += _this.outFile(file);
        });
    outputDir.join(outputName + '.' + this.name).write(content);
};
<|endoftext|>


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

    var main            = global.cloudcmd.main,
        DIR             = main.DIR,
        SRVDIR          = main.SRVDIR,

        socket          = main.socket,
        update          = main.srvrequire('update'),

        exec            = main.child_process.exec,
        spawn           = main.child_process.spawn,

        Util            = main.util,
        path            = main.path,
        mainpackage     = main.mainpackage,
        equalPart       = Util.isContainStrAtBegin,
        CLOUDCMD        = mainpackage.name,
        ClientFuncs     = [],
        ClientDirs      = [],
        Clients         = [],
        INFO_LOG_LEVEL  = 2,
        ENV             = process.env,
        WIN32           = main.WIN32,
        ConNum          = 0,
        HELP            = {
            stdout  : CLOUDCMD + ' exit     \n' +
                      CLOUDCMD + ' update   \n',
        },

        /* windows commands thet require
         * unicode charset on locales
         * different then English
         */
        Win32Commands   = ['ASSOC', 'AT', 'ATTRIB', 'BREAK', 'CACLS', 'CALL',
                            'CD', 'CHCP', 'CHDIR', 'CHKDSK', 'CHKNTFS', 'CLS',
                            'CMD', 'COLOR', 'COMP', 'COMPACT', 'CONVERT', 'COPY',
                            'DATE', 'DEL', 'DIR', 'DISKCOMP', 'DISKCOPY', 'DOSKEY',
                            'ECHO', 'ENDLOCAL', 'ERASE', 'EXIT', 'FC', 'FIND',
                            'FINDSTR', 'FOR', 'FORMAT', 'FTYPE', 'GOTO', 'GRAFTABL',
                            'HELP', 'IF', 'LABEL', 'MD', 'MKDIR', 'MODE', 'MORE',
                            'MOVE', 'PATH', 'PAUSE', 'POPD', 'PRINT', 'PROMPT',
                            'PUSHD', 'RD', 'RECOVER', 'REM', 'REN', 'RENAME',
                            'REPLACE', 'RMDIR', 'SET', 'SETLOCAL', 'SHIFT', 'SORT',
                            'START', 'SUBST', 'TIME', 'TITLE', 'TREE', 'TYPE',
                            'VER', 'VERIFY', 'VOL', 'XCOPY'];

    /**
     * function listen on servers port
     * @pServer {Object} started server object
     */
    exports.init = function() {
        var ret;

        ret = socket.on('connection', function(clientSocket) {
            onConnection(clientSocket, function(json) {
                var msg = Util.stringifyJSON(json);
                socket.send(msg, clientSocket);
            });
        });

        return ret;
    };

    function onConnection(clientSocket, callback) {
        var msg, onDisconnect, onMessage;

        ++ConNum;

        if (!Clients[ConNum]) {
            msg = log(ConNum, 'connected\n');

            Util.exec(callback, {
                stdout : msg
            });

            Clients[ConNum]             = true;

            onMessage                   = getOnMessage(ConNum, callback);
            onDisconnect                = Util.retFunc(function(conNum) {
                Clients[conNum]         =
                ClientFuncs[conNum]     = null;

                log(conNum, 'disconnected');

                socket.removeListener('message', onMessage, clientSocket);
                socket.removeListener('disconnect', onDisconnect, clientSocket);
            }, ConNum);

            socket.on('message', onMessage, clientSocket);
            socket.on('disconnect', onDisconnect, clientSocket);
        } else {
            msg = log(ConNum, ' in use. Reconnecting...\n');

            Util.exec(callback, {
                stdout: msg
            });

            socket.disconnect();
        }
    }

    /**
     * function gets onMessage function
     * that execute needed command
     *
     * @param pConnNum
     * @param callback
     */
    function getOnMessage(pConnNum, callback) {
        return function(pCommand) {
            var lMsg, lWinCommand, lExec_func, firstChar,
                connName,
                lError, lRet, lExecSymbols, isContain,
                dir, options = {};

            dir = ClientDirs[pConnNum];

            if (!dir)
                dir = ClientDirs[pConnNum] = DIR;

            connName = '#' + pConnNum + ': ';
            Util.log(connName + pCommand);

            if (equalPart(pCommand, CLOUDCMD))
                lRet = onCloudCmd(pCommand, callback);
            else if (equalPart(pCommand, 'cd '))  {
                lRet = true;

                onCD(pCommand, dir, function(json) {
                    var error   = json.stderr,
                        stdout  = json.stdout;

                    if (error)
                        Util.exec(callback, json);
                    else
                        ClientDirs[pConnNum] = stdout;
                });
            }

            if (!lRet) {
                /* if we on windows and command is build in
                 * change code page to unicode becouse
                 * windows use unicode on non English versions
                 */
                if (WIN32) {
                    lWinCommand     = pCommand.toUpperCase();

                    if (Win32Commands.indexOf(lWinCommand) >= 0)
                        pCommand    = 'chcp 65001 |' + pCommand;
                }

                if (!ClientFuncs[pConnNum])
                    ClientFuncs[pConnNum] = getExec(function(json, pError, pStderr) {
                        log(pConnNum, pError, 'error');
                        log(pConnNum, pStderr, 'stderror');

                        Util.exec(callback, json);
                    });

                lExec_func      = ClientFuncs[pConnNum];
                lExecSymbols    = ['*', '&', '{', '}', '|', '\'', '"'];
                isContain       = Util.isContainStr(pCommand, lExecSymbols);
                firstChar       = pCommand[0];
                options.cwd     = dir;

                if (firstChar === '#') {
                    pCommand    = pCommand.slice(1);
                    pCommand    = connName + pCommand;
                    pCommand    = Util.addNewLine(pCommand);

                    lMsg    = Util.stringifyJSON({
                        stdout: pCommand
                    });

                    io.sockets.emit('message', lMsg);
                } else if (WIN32 || firstChar === ' ' || isContain)
                    exec(pCommand, options, lExec_func);
                else
                    getSpawn(pCommand, options, callback);
            }
        };
    }

    /**
     * function send result of command to client
     * @param callback
     */
    function getExec(callback) {
        return function(pError, pStdout, pStderr) {
            var lErrorStr, lExecStr, lExec,
                lError          = pStderr || pError;

            if (lError) {
                if (Util.isString(lError))
                    lErrorStr   = lError;
                else
                    lErrorStr   = lError.toString();

                lErrorStr = Util.addNewLine(lErrorStr);
            }

            lExec               = {
                stdout : pStdout,
                stderr : lErrorStr || lError
            };

            Util.exec(callback, lExec, pError, pStderr);
        };
    }

    function getSpawn(pCommand, options, callback) {
        var send, cmd, error,
            args    = pCommand.split(' ');

        pCommand    = args.shift();

        error       = Util.tryCatchLog(function() {
            cmd = spawn(pCommand, args, options);
        });

        if (!cmd)
            send(error + '', null);
        else {
            send        = function(error, data) {
                var exec    = {
                        stderr: error,
                        stdout: data
                    };

                Util.exec(callback, exec);
            };

            cmd.stdout.on('data', function(data) {
                send(null, data + '');
            });

            cmd.stderr.on('data', function(error) {
                send(error + '', null);
            });

            cmd.on('error', Util.retFalse);
            cmd.on('close', function (code) {
                cmd = null;
            });
        }
    }

    function onCloudCmd(pCommand, callback) {
        var lRet;

        pCommand = Util.removeStr(pCommand, CLOUDCMD);

        if (!equalPart(pCommand, ' ')) {
            lRet = true;
            Util.exec(callback, HELP);
        }
        else {
            pCommand = Util.removeStr(pCommand, ' ');

            if (equalPart(pCommand, 'update') && update) {
                lRet = true;
                update.get();

                Util.exec(callback, {
                    stdout: Util.addNewLine('update: ok')
                });
            }

            if (Util.strCmp(pCommand, 'exit'))
                process.exit();
        }

        return lRet;
    }

    function onCD(pCommand, currDir, callback) {
        var dir,
            getDir      = WIN32 ? 'chdir' : 'pwd',
            paramDir    = Util.removeStr(pCommand, 'cd ');

        if (equalPart(paramDir, ['/', '~']))
            dir = paramDir;
        else
            dir = path.join(currDir, paramDir);

        exec('cd ' + dir + ' && ' + getDir, function (error, stdout, stderr) {
            var lRet,
                lMsg    = '',
                lError = error || stderr;

            if (lError) {
                lError  = Util.stringifyJSON(lError);
                lMsg    = lError;
            }

            Util.exec(callback, {
                stderr  : lMsg,
                stdout  : Util.rmNewLine(stdout)
            });
        });
    }

    function log(pConnNum, pStr, pType) {
        var lRet,
            lType       = ' ';

        if (pStr) {

            if (pType)
                lType  += pType + ':';

            lRet        = 'client #' + pConnNum + lType + pStr;

            Util.log(lRet);
        }

        return lRet;
    }
})();
<commit_msg>fix(console) io - > exec<commit_after>(function() {
    'use strict';

    var main            = global.cloudcmd.main,
        DIR             = main.DIR,
        SRVDIR          = main.SRVDIR,

        socket          = main.socket,
        update          = main.srvrequire('update'),

        exec            = main.child_process.exec,
        spawn           = main.child_process.spawn,

        Util            = main.util,
        path            = main.path,
        mainpackage     = main.mainpackage,
        equalPart       = Util.isContainStrAtBegin,
        CLOUDCMD        = mainpackage.name,
        ClientFuncs     = [],
        ClientDirs      = [],
        Clients         = [],
        INFO_LOG_LEVEL  = 2,
        ENV             = process.env,
        WIN32           = main.WIN32,
        ConNum          = 0,
        HELP            = {
            stdout  : CLOUDCMD + ' exit     \n' +
                      CLOUDCMD + ' update   \n',
        },

        /* windows commands thet require
         * unicode charset on locales
         * different then English
         */
        Win32Commands   = ['ASSOC', 'AT', 'ATTRIB', 'BREAK', 'CACLS', 'CALL',
                            'CD', 'CHCP', 'CHDIR', 'CHKDSK', 'CHKNTFS', 'CLS',
                            'CMD', 'COLOR', 'COMP', 'COMPACT', 'CONVERT', 'COPY',
                            'DATE', 'DEL', 'DIR', 'DISKCOMP', 'DISKCOPY', 'DOSKEY',
                            'ECHO', 'ENDLOCAL', 'ERASE', 'EXIT', 'FC', 'FIND',
                            'FINDSTR', 'FOR', 'FORMAT', 'FTYPE', 'GOTO', 'GRAFTABL',
                            'HELP', 'IF', 'LABEL', 'MD', 'MKDIR', 'MODE', 'MORE',
                            'MOVE', 'PATH', 'PAUSE', 'POPD', 'PRINT', 'PROMPT',
                            'PUSHD', 'RD', 'RECOVER', 'REM', 'REN', 'RENAME',
                            'REPLACE', 'RMDIR', 'SET', 'SETLOCAL', 'SHIFT', 'SORT',
                            'START', 'SUBST', 'TIME', 'TITLE', 'TREE', 'TYPE',
                            'VER', 'VERIFY', 'VOL', 'XCOPY'];

    /**
     * function listen on servers port
     * @pServer {Object} started server object
     */
    exports.init = function() {
        var ret;

        ret = socket.on('connection', function(clientSocket) {
            onConnection(clientSocket, function(json) {
                var msg = Util.stringifyJSON(json);
                socket.send(msg, clientSocket);
            });
        });

        return ret;
    };

    function onConnection(clientSocket, callback) {
        var msg, onDisconnect, onMessage;

        ++ConNum;

        if (!Clients[ConNum]) {
            msg = log(ConNum, 'connected\n');

            Util.exec(callback, {
                stdout : msg
            });

            Clients[ConNum]             = true;

            onMessage                   = getOnMessage(ConNum, callback);
            onDisconnect                = Util.retFunc(function(conNum) {
                Clients[conNum]         =
                ClientFuncs[conNum]     = null;

                log(conNum, 'disconnected');

                socket.removeListener('message', onMessage, clientSocket);
                socket.removeListener('disconnect', onDisconnect, clientSocket);
            }, ConNum);

            socket.on('message', onMessage, clientSocket);
            socket.on('disconnect', onDisconnect, clientSocket);
        } else {
            msg = log(ConNum, ' in use. Reconnecting...\n');

            Util.exec(callback, {
                stdout: msg
            });

            socket.disconnect();
        }
    }

    /**
     * function gets onMessage function
     * that execute needed command
     *
     * @param pConnNum
     * @param callback
     */
    function getOnMessage(pConnNum, callback) {
        return function(pCommand) {
            var lWinCommand, lExec_func, firstChar,
                connName,
                lError, lRet, lExecSymbols, isContain,
                dir, options = {};

            dir = ClientDirs[pConnNum];

            if (!dir)
                dir = ClientDirs[pConnNum] = DIR;

            connName = '#' + pConnNum + ': ';
            Util.log(connName + pCommand);

            if (equalPart(pCommand, CLOUDCMD))
                lRet = onCloudCmd(pCommand, callback);
            else if (equalPart(pCommand, 'cd '))  {
                lRet = true;

                onCD(pCommand, dir, function(json) {
                    var error   = json.stderr,
                        stdout  = json.stdout;

                    if (error)
                        Util.exec(callback, json);
                    else
                        ClientDirs[pConnNum] = stdout;
                });
            }

            if (!lRet) {
                /* if we on windows and command is build in
                 * change code page to unicode becouse
                 * windows use unicode on non English versions
                 */
                if (WIN32) {
                    lWinCommand     = pCommand.toUpperCase();

                    if (Win32Commands.indexOf(lWinCommand) >= 0)
                        pCommand    = 'chcp 65001 |' + pCommand;
                }

                if (!ClientFuncs[pConnNum])
                    ClientFuncs[pConnNum] = getExec(function(json, pError, pStderr) {
                        log(pConnNum, pError, 'error');
                        log(pConnNum, pStderr, 'stderror');

                        Util.exec(callback, json);
                    });

                lExec_func      = ClientFuncs[pConnNum];
                lExecSymbols    = ['*', '&', '{', '}', '|', '\'', '"'];
                isContain       = Util.isContainStr(pCommand, lExecSymbols);
                firstChar       = pCommand[0];
                options.cwd     = dir;

                if (firstChar === '#') {
                    pCommand    = pCommand.slice(1);
                    pCommand    = connName + pCommand;
                    pCommand    = Util.addNewLine(pCommand);

                    Util.exec(callback, {
                        stdout: pCommand
                    });
                } else if (WIN32 || firstChar === ' ' || isContain)
                    exec(pCommand, options, lExec_func);
                else
                    getSpawn(pCommand, options, callback);
            }
        };
    }

    /**
     * function send result of command to client
     * @param callback
     */
    function getExec(callback) {
        return function(pError, pStdout, pStderr) {
            var lErrorStr, lExecStr, lExec,
                lError          = pStderr || pError;

            if (lError) {
                if (Util.isString(lError))
                    lErrorStr   = lError;
                else
                    lErrorStr   = lError.toString();

                lErrorStr = Util.addNewLine(lErrorStr);
            }

            lExec               = {
                stdout : pStdout,
                stderr : lErrorStr || lError
            };

            Util.exec(callback, lExec, pError, pStderr);
        };
    }

    function getSpawn(pCommand, options, callback) {
        var send, cmd, error,
            args    = pCommand.split(' ');

        pCommand    = args.shift();

        error       = Util.tryCatchLog(function() {
            cmd = spawn(pCommand, args, options);
        });

        if (!cmd)
            send(error + '', null);
        else {
            send        = function(error, data) {
                var exec    = {
                        stderr: error,
                        stdout: data
                    };

                Util.exec(callback, exec);
            };

            cmd.stdout.on('data', function(data) {
                send(null, data + '');
            });

            cmd.stderr.on('data', function(error) {
                send(error + '', null);
            });

            cmd.on('error', Util.retFalse);
            cmd.on('close', function (code) {
                cmd = null;
            });
        }
    }

    function onCloudCmd(pCommand, callback) {
        var lRet;

        pCommand = Util.removeStr(pCommand, CLOUDCMD);

        if (!equalPart(pCommand, ' ')) {
            lRet = true;
            Util.exec(callback, HELP);
        }
        else {
            pCommand = Util.removeStr(pCommand, ' ');

            if (equalPart(pCommand, 'update') && update) {
                lRet = true;
                update.get();

                Util.exec(callback, {
                    stdout: Util.addNewLine('update: ok')
                });
            }

            if (Util.strCmp(pCommand, 'exit'))
                process.exit();
        }

        return lRet;
    }

    function onCD(pCommand, currDir, callback) {
        var dir,
            getDir      = WIN32 ? 'chdir' : 'pwd',
            paramDir    = Util.removeStr(pCommand, 'cd ');

        if (equalPart(paramDir, ['/', '~']))
            dir = paramDir;
        else
            dir = path.join(currDir, paramDir);

        exec('cd ' + dir + ' && ' + getDir, function (error, stdout, stderr) {
            var lRet,
                lMsg    = '',
                lError = error || stderr;

            if (lError) {
                lError  = Util.stringifyJSON(lError);
                lMsg    = lError;
            }

            Util.exec(callback, {
                stderr  : lMsg,
                stdout  : Util.rmNewLine(stdout)
            });
        });
    }

    function log(pConnNum, pStr, pType) {
        var lRet,
            lType       = ' ';

        if (pStr) {

            if (pType)
                lType  += pType + ':';

            lRet        = 'client #' + pConnNum + lType + pStr;

            Util.log(lRet);
        }

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


<commit_before>'use strict';

var util = require('./util.js');

module.exports.read = (function () {
    var numbers = {
        '0': 'null',
        '1': 'eins',
        '2': 'zwei',
        '3': 'drei',
        '4': 'vier',
        '5': 'fünf',
        '6': 'sechs',
        '7': 'sieben',
        '8': 'acht',
        '9': 'neun',
        '10': 'zehn',
        '11': 'elf',
        '12': 'zwölf',
        '13': 'dreizehn',
        '14': 'vierzehn',
        '15': 'fünfzehn',
        '16': 'sechzehn',
        '17': 'siebzehn',
        '18': 'achtzehn',
        '19': 'neunzehn',
        '20': 'zwanzig',
        '30': 'dreißig',
        '40': 'vierzig',
        '50': 'fünfzig',
        '60': 'sechzig',
        '70': 'siebzig',
        '80': 'achtzig',
        '90': 'neunzig'
    };

    function NumberNode(number, nodeType) {
        this.number = number;
        this.nodeType = nodeType;
        this.next = null;
    }

    function processNumber(n) {
        var pattern = /(\d{1,3})(?=(\d{3})*$)/g;
        var matches = n.toString().match(pattern);
        var head = null;
        var prev = null;

        if (matches) {
            var length = matches.length;
            var nodeTypes = ['default', 'tausend', 'million', 'milliarde', 'billion'];

            matches.map(function (item, index) {
                var number = parseInt(item);
                var nodeType = nodeTypes[length - 1 - index];
                var node = new NumberNode(number, nodeType);

                if (head === null) {
                    head = node;
                }

                if (prev === null) {
                    prev = node;
                } else {
                    prev.next = node;
                }
            });

            return head;
        } else {
            return null;
        }
    }

    function oneDigit(n) {
        return numbers[n];
    }

    function twoDigits(n) {
        if (n < 20) {
            return numbers[n];
        } else {
            var firstInteger = parseInt(n / 10);
            var secondInteger = n % 10;

            if (secondInteger === 0) {
                return numbers[n];
            } else {
                return (secondInteger === 1 ? 'ein' : numbers[secondInteger]) + 'und' + numbers[firstInteger + '0'];
            }
        }
    }

    function threeDigits(n) {
        if (n === 100) {
            return 'hundert';
        }

        var hundert = parseInt(n / 100);
        var hundertPart = (hundert === 1 ? '' : numbers[hundert]) + 'hundert';
        var left = n - 100 * hundert;
        var length = util.numberLength(left);

        if (length === 2) {
            return hundertPart + twoDigits(left);
        } else if (length === 1) {
            return hundertPart + oneDigit(left);
        }
    }

    function DefaultProcessor(successor) {
        this.successor = successor;
    }

    DefaultProcessor.prototype.process = function (node) {
        if (!node) {
            return '';
        }

        if (node.nodeType === 'default') {
            var s = '';
            var length = util.numberLength(node.number);

            switch (length) {
                case 1:
                    s = oneDigit(node.number);
                    break;
                case 2:
                    s = twoDigits(node.number);
                    break;
                case 3:
                    s = threeDigits(node.number);
                    break;
                default:
                    s = '';
                    break;
            }

            return this.successor ? s + this.successor.process(node.next) : s;
        } else {
            return this.successor ? this.successor.process(node) : '';
        }
    };

    function TausendProcessor(successor) {
        this.successor = successor;
    }

    TausendProcessor.prototype.process = function (node) {
        if (!node) {
            return '';
        }

        if (node.nodeType === 'tausend') {
            var s = '';
            var length = util.numberLength(node.number);

            switch (length) {
                case 1:
                    s = (node.number === 1 ? '' : oneDigit(node.number)) + 'tausend';
                    break;
                case 2:
                    s = twoDigits(node.number) + 'tausend';
                    break;
                case 3:
                    if (node.number === 100) {
                        s = 'hundert';
                    } else {
                        var hundert = parseInt(node.number / 100);
                        var hundertPart = (hundert === 1 ? '' : numbers[hundert]) + 'hundert';
                        var left = node.number - 100 * hundert;
                        var length = util.numberLength(left);

                        if (length === 2) {
                            s = hundertPart + twoDigits(left);
                        } else if (length === 1) {
                            s = left === 1 ? hundertPart + 'ein' : hundertPart + oneDigit(left);
                        }
                    }

                    s += 'tausend';
                    break;
                default:
                    s = '';
                    break;
            }

            return this.successor && node.next.number !== 0 ? s + this.successor.process(node.next) : s;
        } else {
            return this.successor ? this.successor.process(node) : '';
        }
    };

    var read = function (n) {
        if (!util.isNumber(n)) {
            return '';
        }

        if (n > 999999999999999) {
            throw new Error('The number is too big.');
        }

        var head = processNumber(n);

        if (head) {
            var processor = new TausendProcessor(new DefaultProcessor());

            return processor.process(head);
        } else {
            return '';
        }
    };

    return read;
})();<commit_msg>Fix jshint issue<commit_after>'use strict';

var util = require('./util.js');

module.exports.read = (function () {
    var numbers = {
        '0': 'null',
        '1': 'eins',
        '2': 'zwei',
        '3': 'drei',
        '4': 'vier',
        '5': 'fünf',
        '6': 'sechs',
        '7': 'sieben',
        '8': 'acht',
        '9': 'neun',
        '10': 'zehn',
        '11': 'elf',
        '12': 'zwölf',
        '13': 'dreizehn',
        '14': 'vierzehn',
        '15': 'fünfzehn',
        '16': 'sechzehn',
        '17': 'siebzehn',
        '18': 'achtzehn',
        '19': 'neunzehn',
        '20': 'zwanzig',
        '30': 'dreißig',
        '40': 'vierzig',
        '50': 'fünfzig',
        '60': 'sechzig',
        '70': 'siebzig',
        '80': 'achtzig',
        '90': 'neunzig'
    };

    function NumberNode(number, nodeType) {
        this.number = number;
        this.nodeType = nodeType;
        this.next = null;
    }

    function processNumber(n) {
        var pattern = /(\d{1,3})(?=(\d{3})*$)/g;
        var matches = n.toString().match(pattern);
        var head = null;
        var prev = null;

        if (matches) {
            var length = matches.length;
            var nodeTypes = ['default', 'tausend', 'million', 'milliarde', 'billion'];

            matches.map(function (item, index) {
                var number = parseInt(item);
                var nodeType = nodeTypes[length - 1 - index];
                var node = new NumberNode(number, nodeType);

                if (head === null) {
                    head = node;
                }

                if (prev === null) {
                    prev = node;
                } else {
                    prev.next = node;
                }
            });

            return head;
        } else {
            return null;
        }
    }

    function oneDigit(n) {
        return numbers[n];
    }

    function twoDigits(n) {
        if (n < 20) {
            return numbers[n];
        } else {
            var firstInteger = parseInt(n / 10);
            var secondInteger = n % 10;

            if (secondInteger === 0) {
                return numbers[n];
            } else {
                return (secondInteger === 1 ? 'ein' : numbers[secondInteger]) + 'und' + numbers[firstInteger + '0'];
            }
        }
    }

    function threeDigits(n) {
        if (n === 100) {
            return 'hundert';
        }

        var hundert = parseInt(n / 100);
        var hundertPart = (hundert === 1 ? '' : numbers[hundert]) + 'hundert';
        var left = n - 100 * hundert;
        var length = util.numberLength(left);

        if (length === 2) {
            return hundertPart + twoDigits(left);
        } else if (length === 1) {
            return hundertPart + oneDigit(left);
        }
    }

    function DefaultProcessor(successor) {
        this.successor = successor;
    }

    DefaultProcessor.prototype.process = function (node) {
        if (!node) {
            return '';
        }

        if (node.nodeType === 'default') {
            var s = '';
            var length = util.numberLength(node.number);

            switch (length) {
                case 1:
                    s = oneDigit(node.number);
                    break;
                case 2:
                    s = twoDigits(node.number);
                    break;
                case 3:
                    s = threeDigits(node.number);
                    break;
                default:
                    s = '';
                    break;
            }

            return this.successor ? s + this.successor.process(node.next) : s;
        } else {
            return this.successor ? this.successor.process(node) : '';
        }
    };

    function TausendProcessor(successor) {
        this.successor = successor;
    }

    TausendProcessor.prototype.process = function (node) {
        if (!node) {
            return '';
        }

        if (node.nodeType === 'tausend') {
            var s = '';
            var length = util.numberLength(node.number);

            switch (length) {
                case 1:
                    s = (node.number === 1 ? '' : oneDigit(node.number)) + 'tausend';
                    break;
                case 2:
                    s = twoDigits(node.number) + 'tausend';
                    break;
                case 3:
                    if (node.number === 100) {
                        s = 'hundert';
                    } else {
                        var hundert = parseInt(node.number / 100);
                        var hundertPart = (hundert === 1 ? '' : numbers[hundert]) + 'hundert';
                        var left = node.number - 100 * hundert;
                        var lefLength = util.numberLength(left);

                        if (lefLength === 2) {
                            s = hundertPart + twoDigits(left);
                        } else if (lefLength === 1) {
                            s = left === 1 ? hundertPart + 'ein' : hundertPart + oneDigit(left);
                        }
                    }

                    s += 'tausend';
                    break;
                default:
                    s = '';
                    break;
            }

            return this.successor && node.next.number !== 0 ? s + this.successor.process(node.next) : s;
        } else {
            return this.successor ? this.successor.process(node) : '';
        }
    };

    var read = function (n) {
        if (!util.isNumber(n)) {
            return '';
        }

        if (n > 999999999999999) {
            throw new Error('The number is too big.');
        }

        var head = processNumber(n);

        if (head) {
            var processor = new TausendProcessor(new DefaultProcessor());

            return processor.process(head);
        } else {
            return '';
        }
    };

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


<commit_before>Ext.define('MyCustomer.view.main.MainController', {
	extend: 'Ext.app.ViewController',

	onStoreLoad: function(s) {
		var total = s.getTotalCount();
		this.getViewModel().set('numberOfCustomers', s.getTotalCount());
		Ext.getStore('categories-report').load();

		// if there is only 1 item in the list, autoselect it
		if (total === 1) {
			this.getViewModel().set('currentCustomer', s.first());
		}
		else {
			this.getViewModel().set('currentCustomer', null);
		}
	},

	onItemClick: function(button, record) {
		// reject any pending changes of previous selected record
		if (this.selectedRecord && this.selectedRecord.dirty) {
			this.selectedRecord.reject();
		}
		this.selectedRecord = record;
	},

	onNameChange: function(field, newValue) {
		this.getViewModel().set('nameFilter', newValue);
	},

	newCustomer: function() {
		var newCustomer = new MyCustomer.model.Customer();
		this.getViewModel().set('currentCustomer', newCustomer);

		Ext.defer(function() {
			this.lookup('customeredit').focus();
			this.lookup('customeredit').isValid();
		}, 5, this);
	},

	deleteCustomer: function() {
		var currentCustomer = this.getViewModel().get('currentCustomer');
		Ext.Msg.confirm('Confirm', 'Are you sure you want to
delete customer ' + currentCustomer.get('lastName') + '?', 'onConfirm', this);
	},

	onConfirm: function(choice) {
		if (choice === 'yes') {
			var currentCustomer = this.getViewModel().get('currentCustomer');
			currentCustomer.erase();
			this.getStore('customers').reload();
		}
	},

	onCustomerEditReset: function() {
		var cust = this.getViewModel().get('currentCustomer');
		cust.reject();
	},

	onCustomerEditSubmit: function() {
		var cust = this.getViewModel().get('currentCustomer');
		cust.save({
			success: function() {
				this.getStore('customers').reload();
			},
			failure: function(record, op) {
				var validations = op.getResponse().result.validations;
				if (validations) {
					var form = this.lookup('customeredit').getForm();
					validations.forEach(function(validation) {
						var field = form.findField(validation.field);
						field.markInvalid(validation.message);
					});
				}
			},
			scope: this
		});

	}

});
<commit_msg>Preselect gender. <commit_after>Ext.define('MyCustomer.view.main.MainController', {
	extend: 'Ext.app.ViewController',

	onStoreLoad: function(s) {
		var total = s.getTotalCount();
		this.getViewModel().set('numberOfCustomers', s.getTotalCount());
		Ext.getStore('categories-report').load();

		// if there is only 1 item in the list, autoselect it
		if (total === 1) {
			this.getViewModel().set('currentCustomer', s.first());
		}
		else {
			this.getViewModel().set('currentCustomer', null);
		}
	},

	onItemClick: function(button, record) {
		// reject any pending changes of previous selected record
		if (this.selectedRecord && this.selectedRecord.dirty) {
			this.selectedRecord.reject();
		}
		this.selectedRecord = record;
	},

	onNameChange: function(field, newValue) {
		this.getViewModel().set('nameFilter', newValue);
	},

	newCustomer: function() {
		var newCustomer = new MyCustomer.model.Customer({
			gender: 'M'
		});
		this.getViewModel().set('currentCustomer', newCustomer);

		Ext.defer(function() {
			this.lookup('customeredit').focus();
			this.lookup('customeredit').isValid();
		}, 5, this);
	},

	deleteCustomer: function() {
		var currentCustomer = this.getViewModel().get('currentCustomer');
		Ext.Msg.confirm('Confirm', 'Are you sure you want to
delete customer ' + currentCustomer.get('lastName') + '?', 'onConfirm', this);
	},

	onConfirm: function(choice) {
		if (choice === 'yes') {
			var currentCustomer = this.getViewModel().get('currentCustomer');
			currentCustomer.erase();
			this.getStore('customers').reload();
		}
	},

	onCustomerEditReset: function() {
		var cust = this.getViewModel().get('currentCustomer');
		cust.reject();
	},

	onCustomerEditSubmit: function() {
		var cust = this.getViewModel().get('currentCustomer');
		cust.save({
			success: function() {
				this.getStore('customers').reload();
			},
			failure: function(record, op) {
				var validations = op.getResponse().result.validations;
				if (validations) {
					var form = this.lookup('customeredit').getForm();
					validations.forEach(function(validation) {
						var field = form.findField(validation.field);
						field.markInvalid(validation.message);
					});
				}
			},
			scope: this
		});

	}

});
<|endoftext|>


<commit_before>// Load modules

var Path = require('path');
var Hapi = require('hapi');
var Lib = require('./lib');
var Hoek = require('hoek');
var Package = require('./package.json');

// Declare internals

var internals = {
    port: process.env.PORT || 8000
};

internals.main = function main() {

    // Create required directories before anything else is done
    Lib.initPaths(__dirname);

    var server = new Hapi.Server(internals.port, {
        app: {
            oneDay: 86400000,
            root: __dirname,
            db: Lib.data.initDb(),
            globalContext: {
                name: 'HapChat',
                year: new Date().getFullYear(),
                version: Package.version
            }
        }
    });

    // Register views
    server.views({
        engines: {
            html: require('handlebars')
        },
        path: Path.join(__dirname, 'static', 'views'),
        layoutPath: Path.join(__dirname, 'static', 'views', 'layout'),
        layout: true,
        layoutKeyword: 'partial'
    });

    // Register plugins

    // Register routes
    Lib.registerRoutes(server);
    Lib.registerMethods(server);

    // Server extension points
    server.ext('onPreResponse', function (request, reply) {

        if (request.response.variety === 'view') {
            request.response.source.context = Hoek.applyToDefaults(server.settings.app.globalContext, request.response.source.context || {});
            request.response.source.context.path = request.path;
            server.methods.getNav(false, function (error, result) {

                request.response.source.context.nav = result;
                reply();
            });
        }
        else {
            reply();
        }
    });

    // Start the server
    server.start(function start() {

        console.log('Hapchat started at ' + server.info.uri);
    });
};

internals.main();
<commit_msg>Updated to true so we can see the user pages.<commit_after>// Load modules

var Path = require('path');
var Hapi = require('hapi');
var Lib = require('./lib');
var Hoek = require('hoek');
var Package = require('./package.json');

// Declare internals

var internals = {
    port: process.env.PORT || 8000
};

internals.main = function main() {

    // Create required directories before anything else is done
    Lib.initPaths(__dirname);

    var server = new Hapi.Server(internals.port, {
        app: {
            oneDay: 86400000,
            root: __dirname,
            db: Lib.data.initDb(),
            globalContext: {
                name: 'HapChat',
                year: new Date().getFullYear(),
                version: Package.version
            }
        }
    });

    // Register views
    server.views({
        engines: {
            html: require('handlebars')
        },
        path: Path.join(__dirname, 'static', 'views'),
        layoutPath: Path.join(__dirname, 'static', 'views', 'layout'),
        layout: true,
        layoutKeyword: 'partial'
    });

    // Register plugins

    // Register routes
    Lib.registerRoutes(server);
    Lib.registerMethods(server);

    // Server extension points
    server.ext('onPreResponse', function (request, reply) {

        if (request.response.variety === 'view') {
            request.response.source.context = Hoek.applyToDefaults(server.settings.app.globalContext, request.response.source.context || {});
            request.response.source.context.path = request.path;
            server.methods.getNav(true, function (error, result) {

                request.response.source.context.nav = result;
                reply();
            });
        }
        else {
            reply();
        }
    });

    // Start the server
    server.start(function start() {

        console.log('Hapchat started at ' + server.info.uri);
    });
};

internals.main();
<|endoftext|>


<commit_before>import merge from 'lodash/merge'
import values from 'lodash/values'
import union from 'lodash/union'
import {
  STEPS_BY_PROJECT_FETCH_REQUEST,
  STEPS_BY_PROJECT_FETCH_SUCCESS,
  STEPS_BY_PROJECT_FETCH_FAILURE
} from '../actions/stepsByProject'
import {
  STEP_CREATE_SUCCESS
} from '../actions/steps'

export default function stepsByProject(state = {}, action) {
  switch(action.type) {
    case STEPS_BY_PROJECT_FETCH_REQUEST:
      return merge({}, state, {
        [action.projectId]: {
          isFetching: true
        }
      })

    case STEPS_BY_PROJECT_FETCH_SUCCESS:
      return merge({}, state, {
        [action.projectId]: {
          items: action.response.result,
          lastUpdated: (new Date()).toISOString(),
          isFetching: false,
          error: undefined
        }
      })

    case STEPS_BY_PROJECT_FETCH_FAILURE:
      return merge({}, state, {
        [action.projectId]: {
          isFetching: false,
          error: 'Something went terribly awry'
        }
      })

    case STEP_CREATE_SUCCESS:
      const project = state[action.projectId]
      const stepId = action.response.result

      const before = project.items
      const after = union(project.items, [stepId])

      const newState = merge({}, state, {
        [action.projectId]: {
          items: after
        }
      })

      if (project) {
        return newState
      }

    default:
      return state
  }
}<commit_msg>Clean up merge logic<commit_after>import merge from 'lodash/merge'
import values from 'lodash/values'
import union from 'lodash/union'
import {
  STEPS_BY_PROJECT_FETCH_REQUEST,
  STEPS_BY_PROJECT_FETCH_SUCCESS,
  STEPS_BY_PROJECT_FETCH_FAILURE
} from '../actions/stepsByProject'
import {
  STEP_CREATE_SUCCESS
} from '../actions/steps'

export default function stepsByProject(state = {}, action) {
  switch(action.type) {
    case STEPS_BY_PROJECT_FETCH_REQUEST:
      return merge({}, state, {
        [action.projectId]: {
          isFetching: true
        }
      })

    case STEPS_BY_PROJECT_FETCH_SUCCESS:
      return merge({}, state, {
        [action.projectId]: {
          items: action.response.result,
          lastUpdated: (new Date()).toISOString(),
          isFetching: false,
          error: undefined
        }
      })

    case STEPS_BY_PROJECT_FETCH_FAILURE:
      return merge({}, state, {
        [action.projectId]: {
          isFetching: false,
          error: 'Something went terribly awry'
        }
      })

    case STEP_CREATE_SUCCESS:
      const project = state[action.projectId]
      const stepId = action.response.result

      if (project) {
        return merge({}, state, {
          [action.projectId]: {
            items: union(project.items, [ stepId ])
          }
        })
      }

    default:
      return state
  }
}<|endoftext|>


<commit_before>"use strict";

var app = require('app'),  // Module to control application life.
    BrowserWindow = require('browser-window'),  // Module to create native browser window.
    ipcMain = require("electron").ipcMain,
    optimist = require('optimist');

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
var windows = {};
global.browserOpenFiles = []; // Track files for open-file event

var packageJSON = require(__dirname + '/package.json');

// Returns Window object
function createWindow() {
  var browserWindowOptions = packageJSON.browserWindowOptions;
  browserWindowOptions.icon = __dirname + '/' + browserWindowOptions.icon;
  var window = new BrowserWindow(browserWindowOptions);
  windows[window.id] = window;
  window.focus();
  window.webContents.on("will-navigate", function(e) {
      e.preventDefault();
      window.webContents.send("app", "will-navigate");
  });

  if (process.platform == 'win32') {
    window.on("blur", function() {
      if (window.webContents)
        window.webContents.send("app", "blur");
    });
    window.on("focus", function() {
      if (window.webContents)
        window.webContents.send("app", "focus");
    });
  } else {
    window.on("blur", function() {
      window.webContents.send("app", "blur");
    });
    window.on("focus", function() {
      window.webContents.send("app", "focus");
    });
  }
  window.on("devtools-opened", function() {
    window.webContents.send("devtools", "disconnect");
  });
  window.on("devtools-closed", function() {
    window.webContents.send("devtools", "reconnect!");
  });

  // and load the index.html of the app.
  window.loadUrl('file://' + __dirname + '/LightTable.html?id=' + window.id);

  // Notify LT that the user requested to close the window/app
  window.on("close", function(evt) {
    window.webContents.send("app", "close!");
    evt.preventDefault();
  });

  // Emitted when the window is closed.
  window.on('closed', function() {
    windows[window.id] = null;
  });

  return window;
};

function onReady() {
  ipcMain.on("createWindow", function(event, info) {
    createWindow();
  });

  ipcMain.on("initWindow", function(event, id) {
    // Moving this to createWindow() causes js loading issues
    windows[id].on("focus", function() {
      windows[id].webContents.send("app", "focus");
    });
  });

  ipcMain.on("toggleDevTools", function(event, windowId) {
    if(windowId && windows[windowId]) {
      windows[windowId].toggleDevTools();
    }
  });

  createWindow();
};

function parseArgs() {
  optimist.usage("\nLight Table " + app.getVersion() + "\n" +
                 // TODO: Use a consistent name for executables or vary executable
                 // name per platform. $0 currently gives an unwieldy name
                 "Usage: light [options] [path ...]\n\n"+
                 "Paths are either a file or a directory.\n"+
                 "Files can take a line number e.g. file:line.");
  optimist.alias('h', 'help').boolean('h').describe('h', 'Print help');
  optimist.alias('a', 'add').boolean('a').describe('a', 'Add path(s) to workspace');
  global.browserParsedArgs = optimist.parse(process.argv);

  if (global.browserParsedArgs.help) {
    optimist.showHelp();
    process.exit(0);
  }
}

function start() {
  app.commandLine.appendSwitch('remote-debugging-port', '8315');
  app.commandLine.appendSwitch('js-flags', '--harmony');

  // This method will be called when electron has done everything
  // initialization and ready for creating browser windows.
  app.on('ready', onReady);

  // Quit when all windows are closed.
  app.on('window-all-closed', function() {
    app.quit();
  });

  // open-file operates in two modes - before and after startup.
  // On startup and before a window has opened, event paths are
  // saved and then opened once windows are available.
  // After startup, event paths are sent to available windows.
  app.on('open-file', function(event, path) {
    if (Object.keys(windows).length > 0) {
      Object.keys(windows).forEach(function(id) {
        windows[id].webContents.send('openFileAfterStartup', path);
      });
    }
    else {
      global.browserOpenFiles.push(path);
    }
  });
  parseArgs();
};

// Set $IPC_DEBUG to debug incoming and outgoing ipcMain messages for the main process
if (process.env["IPC_DEBUG"]) {
  var oldOn = ipcMain.on;
  ipcMain.on = function (channel, cb) {
    oldOn.call(ipcMain, channel, function() {
      console.log("\t\t\t\t\t->MAIN", channel, Array.prototype.slice.call(arguments).join(', '));
      cb.apply(null, arguments);
    });
  };
  var logSend = function (window) {
    var oldSend = window.webContents.send;
    window.webContents.send = function () {
      console.log("\t\t\t\t\tMAIN->", Array.prototype.slice.call(arguments).join(', '));
      oldSend.apply(window.webContents, arguments);
    };
  };
  var oldCreateWindow = createWindow;
  var createWindow = function() { logSend(oldCreateWindow()); };
}

start();
<commit_msg>loadUrl has been replaced with loadURL<commit_after>"use strict";

var app = require('app'),  // Module to control application life.
    BrowserWindow = require('browser-window'),  // Module to create native browser window.
    ipcMain = require("electron").ipcMain,
    optimist = require('optimist');

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
var windows = {};
global.browserOpenFiles = []; // Track files for open-file event

var packageJSON = require(__dirname + '/package.json');

// Returns Window object
function createWindow() {
  var browserWindowOptions = packageJSON.browserWindowOptions;
  browserWindowOptions.icon = __dirname + '/' + browserWindowOptions.icon;
  var window = new BrowserWindow(browserWindowOptions);
  windows[window.id] = window;
  window.focus();
  window.webContents.on("will-navigate", function(e) {
      e.preventDefault();
      window.webContents.send("app", "will-navigate");
  });

  if (process.platform == 'win32') {
    window.on("blur", function() {
      if (window.webContents)
        window.webContents.send("app", "blur");
    });
    window.on("focus", function() {
      if (window.webContents)
        window.webContents.send("app", "focus");
    });
  } else {
    window.on("blur", function() {
      window.webContents.send("app", "blur");
    });
    window.on("focus", function() {
      window.webContents.send("app", "focus");
    });
  }
  window.on("devtools-opened", function() {
    window.webContents.send("devtools", "disconnect");
  });
  window.on("devtools-closed", function() {
    window.webContents.send("devtools", "reconnect!");
  });

  // and load the index.html of the app.
  window.loadURL('file://' + __dirname + '/LightTable.html?id=' + window.id);

  // Notify LT that the user requested to close the window/app
  window.on("close", function(evt) {
    window.webContents.send("app", "close!");
    evt.preventDefault();
  });

  // Emitted when the window is closed.
  window.on('closed', function() {
    windows[window.id] = null;
  });

  return window;
};

function onReady() {
  ipcMain.on("createWindow", function(event, info) {
    createWindow();
  });

  ipcMain.on("initWindow", function(event, id) {
    // Moving this to createWindow() causes js loading issues
    windows[id].on("focus", function() {
      windows[id].webContents.send("app", "focus");
    });
  });

  ipcMain.on("toggleDevTools", function(event, windowId) {
    if(windowId && windows[windowId]) {
      windows[windowId].toggleDevTools();
    }
  });

  createWindow();
};

function parseArgs() {
  optimist.usage("\nLight Table " + app.getVersion() + "\n" +
                 // TODO: Use a consistent name for executables or vary executable
                 // name per platform. $0 currently gives an unwieldy name
                 "Usage: light [options] [path ...]\n\n"+
                 "Paths are either a file or a directory.\n"+
                 "Files can take a line number e.g. file:line.");
  optimist.alias('h', 'help').boolean('h').describe('h', 'Print help');
  optimist.alias('a', 'add').boolean('a').describe('a', 'Add path(s) to workspace');
  global.browserParsedArgs = optimist.parse(process.argv);

  if (global.browserParsedArgs.help) {
    optimist.showHelp();
    process.exit(0);
  }
}

function start() {
  app.commandLine.appendSwitch('remote-debugging-port', '8315');
  app.commandLine.appendSwitch('js-flags', '--harmony');

  // This method will be called when electron has done everything
  // initialization and ready for creating browser windows.
  app.on('ready', onReady);

  // Quit when all windows are closed.
  app.on('window-all-closed', function() {
    app.quit();
  });

  // open-file operates in two modes - before and after startup.
  // On startup and before a window has opened, event paths are
  // saved and then opened once windows are available.
  // After startup, event paths are sent to available windows.
  app.on('open-file', function(event, path) {
    if (Object.keys(windows).length > 0) {
      Object.keys(windows).forEach(function(id) {
        windows[id].webContents.send('openFileAfterStartup', path);
      });
    }
    else {
      global.browserOpenFiles.push(path);
    }
  });
  parseArgs();
};

// Set $IPC_DEBUG to debug incoming and outgoing ipcMain messages for the main process
if (process.env["IPC_DEBUG"]) {
  var oldOn = ipcMain.on;
  ipcMain.on = function (channel, cb) {
    oldOn.call(ipcMain, channel, function() {
      console.log("\t\t\t\t\t->MAIN", channel, Array.prototype.slice.call(arguments).join(', '));
      cb.apply(null, arguments);
    });
  };
  var logSend = function (window) {
    var oldSend = window.webContents.send;
    window.webContents.send = function () {
      console.log("\t\t\t\t\tMAIN->", Array.prototype.slice.call(arguments).join(', '));
      oldSend.apply(window.webContents, arguments);
    };
  };
  var oldCreateWindow = createWindow;
  var createWindow = function() { logSend(oldCreateWindow()); };
}

start();
<|endoftext|>


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

    var fs                  = require('fs'),

        DIR                 = '../',
        DIR_SERVER          = DIR + 'server/',

        Util                = require(DIR           + 'util'),
        format              = require(DIR           + 'format'),
        nicki               = require(DIR_SERVER    + 'nicki'),

        WIN                 = process.platform === 'win32';

    module.exports = function(path, callback) {
        Util.checkArgs(arguments, ['path', 'callback'])
            .checkType('path', path, 'string')
            .checkType('callback', callback, 'function');

        fs.readdir(path, function(error, names) {
            if (error)
                callback(error);
            else
                getAllStats(path, names, callback);
        });
    };

    /**
     * @param path
     * @param names
     */
    function getAllStats(path, names, callback) {
        var length  = names.length,
            funcs   = names.length ? {} : [],
            dir     = format.addSlashToEnd(path);

        if (!length)
            funcs.push(Util.exec);
        else
            names.forEach(function(name) {
                var path    = dir + name;

                funcs[name] = Util.exec.with(getStat, name, path);
            });

        Util.exec.parallel(funcs, function(error, files) {
            fillJSON(dir, files || {}, callback);
        });
    }

    function getStat(name, path, callback) {
        fs.lstat(path, function(error, data) {
            callback(null, data || {
                'mode'          : 0,
                'size'          : 0,
                'isDirectory'   : Util.retFalse
            });
        });
    }

    function parseStats(stats) {
        var files;

        Util.checkArgs(arguments, ['stats']);

        files = Object.keys(stats).map(function(name) {
            var file, isDir, size, mode, modeStr,
                stat    = stats[name],
                owner   = stat.uid;

            if (stat) {
                /* Переводим права доступа в 8-ричную систему */
                modeStr = Number(stat.mode).toString(8);
                mode    = Number(modeStr);
                isDir   = stat.isDirectory();
                size    = isDir ? 'dir' : stat.size;
            }

            file = {
                'name'  : name,
                'size'  : format.size(size),
                'owner' : owner,
                'mode'  : format.permissions.symbolic(mode)
            };

            return file;
        });

        return files;
    }

    /**
     * Function fill JSON by file stats
     *
     * @param params - { files, stats, path }
     */
    function fillJSON(path, stats, callback) {
        var files,

            json    = {
                path    : '',
                files   : []
            };

        Util.checkArgs(arguments, ['params']);

        files       = parseStats(stats);

        /* sorting on Win and node v0.8.0 */
        files   = sort(files);

        json.files  = changeOrder(files);
        json.path   = format.addSlashToEnd(path);

        changeUIDToName(json, function() {
            callback(null, json);
        });
    }

    function changeUIDToName(json, callback) {
        if (WIN)
            callback();
        else
            nicki(function(error, names) {
                var files = json.files;

                if (error)
                    callback(error);
                else
                    files.forEach(function(file) {
                        var owner   = file.owner;
                            owner   = names[owner];

                        if (owner)
                            file.owner   = owner;
                    });

                callback();
            });
    }

      function sort(files) {
        var sorted  = files;

        sorted = files.sort(function(fileA, fileB) {
            var ret     = 0,
                more    = fileA.name > fileB.name,
                less    = fileA.name < fileB.name;

            if (more)
                ret = 1;
            else if (less)
                ret = -1;

            return ret;
        });

        return sorted;
    }

    function changeOrder(json) {
        var files   = [],
            dirs    = [],
            sorted  = [];

        json.forEach(function(current) {
            if (current.size === 'dir')
                dirs.push(current);
            else
                files.push(current);
        });

        sorted = dirs.concat(files);

        return sorted;
    }

})();
<commit_msg>feature(readify) lstat -> stat<commit_after>(function() {
    'use strict';

    var fs                  = require('fs'),

        DIR                 = '../',
        DIR_SERVER          = DIR + 'server/',

        Util                = require(DIR           + 'util'),
        format              = require(DIR           + 'format'),
        nicki               = require(DIR_SERVER    + 'nicki'),

        WIN                 = process.platform === 'win32';

    module.exports = function(path, callback) {
        Util.checkArgs(arguments, ['path', 'callback'])
            .checkType('path', path, 'string')
            .checkType('callback', callback, 'function');

        fs.readdir(path, function(error, names) {
            if (error)
                callback(error);
            else
                getAllStats(path, names, callback);
        });
    };

    /**
     * @param path
     * @param names
     */
    function getAllStats(path, names, callback) {
        var length  = names.length,
            funcs   = names.length ? {} : [],
            dir     = format.addSlashToEnd(path);

        if (!length)
            funcs.push(Util.exec);
        else
            names.forEach(function(name) {
                var path    = dir + name;

                funcs[name] = Util.exec.with(getStat, name, path);
            });

        Util.exec.parallel(funcs, function(error, files) {
            fillJSON(dir, files || {}, callback);
        });
    }

    function getStat(name, path, callback) {
        fs.stat(path, function(error, data) {
            callback(null, data || {
                'mode'          : 0,
                'size'          : 0,
                'isDirectory'   : Util.retFalse
            });
        });
    }

    function parseStats(stats) {
        var files;

        Util.checkArgs(arguments, ['stats']);

        files = Object.keys(stats).map(function(name) {
            var file, isDir, size, mode, modeStr,
                stat    = stats[name],
                owner   = stat.uid;

            if (stat) {
                /* Переводим права доступа в 8-ричную систему */
                modeStr = Number(stat.mode).toString(8);
                mode    = Number(modeStr);
                isDir   = stat.isDirectory();
                size    = isDir ? 'dir' : stat.size;
            }

            file = {
                'name'  : name,
                'size'  : format.size(size),
                'owner' : owner,
                'mode'  : format.permissions.symbolic(mode)
            };

            return file;
        });

        return files;
    }

    /**
     * Function fill JSON by file stats
     *
     * @param params - { files, stats, path }
     */
    function fillJSON(path, stats, callback) {
        var files,

            json    = {
                path    : '',
                files   : []
            };

        Util.checkArgs(arguments, ['params']);

        files       = parseStats(stats);

        /* sorting on Win and node v0.8.0 */
        files   = sort(files);

        json.files  = changeOrder(files);
        json.path   = format.addSlashToEnd(path);

        changeUIDToName(json, function() {
            callback(null, json);
        });
    }

    function changeUIDToName(json, callback) {
        if (WIN)
            callback();
        else
            nicki(function(error, names) {
                var files = json.files;

                if (error)
                    callback(error);
                else
                    files.forEach(function(file) {
                        var owner   = file.owner;
                            owner   = names[owner];

                        if (owner)
                            file.owner   = owner;
                    });

                callback();
            });
    }

      function sort(files) {
        var sorted  = files;

        sorted = files.sort(function(fileA, fileB) {
            var ret     = 0,
                more    = fileA.name > fileB.name,
                less    = fileA.name < fileB.name;

            if (more)
                ret = 1;
            else if (less)
                ret = -1;

            return ret;
        });

        return sorted;
    }

    function changeOrder(json) {
        var files   = [],
            dirs    = [],
            sorted  = [];

        json.forEach(function(current) {
            if (current.size === 'dir')
                dirs.push(current);
            else
                files.push(current);
        });

        sorted = dirs.concat(files);

        return sorted;
    }

})();
<|endoftext|>