<commit_before>var Stream = require("stream");

var libLineChomper = require("../lib/line-chomper");

describe("Basic chomping", function () {

	function verifySmallFileProcessedCorrectly(err, lines, lastEmptyLineKept) {
		expect(err).toBeNull();
		expect(lines).not.toBeNull();
		expect(lines.length).toEqual(lastEmptyLineKept ? 5 : 4);
		expect(lines[0]).toEqual("line1");
		expect(lines[3]).toEqual("line4");
		if (lastEmptyLineKept) {
			expect(lines[4]).toEqual("");
		}
	}

	it("should correctly chomp lines with *nix-style terminators (\\r)", function (done) {
		libLineChomper.chomp(__dirname + "/files/small-nix.txt", function (err, lines) {
			verifySmallFileProcessedCorrectly(err, lines, false);
			done();
		});
	});
	it("should correctly chomp lines with mac-style terminators (\\n)", function (done) {
		libLineChomper.chomp(__dirname + "/files/small-mac.txt", function (err, lines) {
			verifySmallFileProcessedCorrectly(err, lines, false);
			done();
		});
	});
	it("should correctly chomp lines with PC-style terminators (\\r\\n)", function (done) {
		libLineChomper.chomp(__dirname + "/files/small-pc.txt", function (err, lines) {
			verifySmallFileProcessedCorrectly(err, lines, false);
			done();
		});
	});

	it("should keep last empty line if specified", function (done) {
		libLineChomper.chomp(__dirname + "/files/small-nix.txt", { keepLastEmptyLine: true }, function (err, lines) {
			verifySmallFileProcessedCorrectly(err, lines, true);
			done();
		});
	});

	it("can handle empty files", function (done) {
		libLineChomper.chomp(__dirname + "/files/empty.txt", function (err, lines) {
			expect(err).toBeNull();
			expect(lines).not.toBeNull();
			expect(lines.length).toEqual(0);
			done();
		});
	});

	it("should accept custom stream", function (done) {
		var stream = new Stream.Readable();
		stream._read = function noop() {};

		stream.push("line1\n");
		stream.push("line2");

		libLineChomper.chomp(stream, function (err, lines) {
			expect(err).toBeNull();
			expect(lines).not.toBeNull();
			expect(lines.length).toEqual(2);
			expect(lines[0]).toEqual("line1");
			expect(lines[1]).toEqual("line2");
			done();
		});

		stream.resume();
		stream.push(null);
	});

	it("should return error for missing files", function (done) {
		libLineChomper.chomp(__dirname + "/files/not-there.txt", function (err, lines) {
			expect(err).not.toBeNull();
			expect(err.code).toEqual("ENOENT");
			done();
		});
	});
});<commit_msg>Advanced chomping tests<commit_after>var Stream = require("stream");

var libTools = require("../lib/tools"),
	libLineChomper = require("../lib/line-chomper");

describe("Basic chomping", function () {

	function verifySmallFileProcessedCorrectly(err, lines, lastEmptyLineKept) {
		expect(err).toBeNull();
		expect(lines).not.toBeNull();
		expect(lines.length).toEqual(lastEmptyLineKept ? 5 : 4);
		expect(lines[0]).toEqual("line1");
		expect(lines[3]).toEqual("line4");
		if (lastEmptyLineKept) {
			expect(lines[4]).toEqual("");
		}
	}

	it("should correctly chomp lines with *nix-style terminators (\\r)", function (done) {
		libLineChomper.chomp(__dirname + "/files/small-nix.txt", function (err, lines) {
			verifySmallFileProcessedCorrectly(err, lines, false);
			done();
		});
	});
	it("should correctly chomp lines with mac-style terminators (\\n)", function (done) {
		libLineChomper.chomp(__dirname + "/files/small-mac.txt", function (err, lines) {
			verifySmallFileProcessedCorrectly(err, lines, false);
			done();
		});
	});
	it("should correctly chomp lines with PC-style terminators (\\r\\n)", function (done) {
		libLineChomper.chomp(__dirname + "/files/small-pc.txt", function (err, lines) {
			verifySmallFileProcessedCorrectly(err, lines, false);
			done();
		});
	});

	it("should keep last empty line if specified", function (done) {
		libLineChomper.chomp(__dirname + "/files/small-nix.txt", { keepLastEmptyLine: true }, function (err, lines) {
			verifySmallFileProcessedCorrectly(err, lines, true);
			done();
		});
	});

	it("can handle empty files", function (done) {
		libLineChomper.chomp(__dirname + "/files/empty.txt", function (err, lines) {
			expect(err).toBeNull();
			expect(lines).not.toBeNull();
			expect(lines.length).toEqual(0);
			done();
		});
	});

	it("should accept custom stream", function (done) {
		var stream = new Stream.Readable();
		stream._read = function noop() {};

		stream.push("line1\n");
		stream.push("line2");

		libLineChomper.chomp(stream, function (err, lines) {
			expect(err).toBeNull();
			expect(lines).not.toBeNull();
			expect(lines.length).toEqual(2);
			expect(lines[0]).toEqual("line1");
			expect(lines[1]).toEqual("line2");
			done();
		});

		stream.resume();
		stream.push(null);
	});

	it("should return error for missing files", function (done) {
		libLineChomper.chomp(__dirname + "/files/not-there.txt", function (err, lines) {
			expect(err).not.toBeNull();
			expect(err.code).toEqual("ENOENT");
			done();
		});
	});
});

describe("Advanced chomping", function () {
	beforeEach(function () {
		this.addMatchers({
			toBeANumber: function () {
				return libTools.isNumber(this.actual);
			}
		})
	});

	it("can chomp file one line at a time, without buffering", function (done) {
		var counter = 0;
		libLineChomper.chomp(
			__dirname + "/files/small-nix.txt",
			function (line, offset, sizeInBytes) {
				expect(offset).toBeANumber();
				expect(sizeInBytes).toBeANumber();
				counter++;
			},
			function (err, lines) {
				expect(err).toBeNull();
				expect(lines).toBeFalsy();
				expect(counter).toEqual(4);
				done();
			}
		);
	});

	function verifySmallFileByteCounts(lines, singleCharTerminator) {
		if (singleCharTerminator) {
			expect(lines[3].offset).toEqual(13);
			expect(lines[3].sizeInBytes).toEqual(6);
		} else {
			expect(lines[3].offset).toEqual(16);
			expect(lines[3].sizeInBytes).toEqual(7);
		}
	}

	it("can correctly count bytes in file with *nix-styled line terminators", function (done) {
		libLineChomper.chomp(__dirname + "/files/small-nix.txt", { returnDetails: true }, function (err, lines) {
			verifySmallFileByteCounts(lines, true);
			done();
		});
	});

	it("can correctly count bytes in file with mac-styled line terminators", function (done) {
		libLineChomper.chomp(__dirname + "/files/small-mac.txt", { returnDetails: true }, function (err, lines) {
			verifySmallFileByteCounts(lines, true);
			done();
		});
	});

	it("can correctly count bytes in file with pc-styled line terminators", function (done) {
		libLineChomper.chomp(__dirname + "/files/small-pc.txt", { returnDetails: true }, function (err, lines) {
			verifySmallFileByteCounts(lines, false);
			done();
		});
	});
});<|endoftext|>


<commit_before>
function openerp_picking_widgets(instance){
    var module = instance.stock;

    module.PickingEditorWidget = instance.web.Widget.extend({
        template: 'PickingEditorWidget',
        init: function(parent,options){
            this._super(parent,options);
        },
        get_header: function(){
            var model = this.getParent();
            return 'Picking: '+model.picking.name;
        },
        get_rows: function(){
            var model = this.getParent();
            var rows = [];

            _.each( model.movelines, function(moveline){
                rows.push({
                    cols: { product: moveline.product_id[1],
                            qty: moveline.product_qty,
                            rem: moveline.remaining_qty,
                            uom: moveline.product_uom[1],
                            loc: moveline.location_id[1],
                            stat: moveline.state
                    },
                    classes: (moveline.qty_remaining < 0 ? 'oe_invalid' : '')
                });
            });

            return rows;
        },
    });

    module.PackageEditorWidget = instance.web.Widget.extend({
        template: 'PackageEditorWidget',
        get_header: function(){
            var model = this.getParent();
            var current_package = model.get_selected_package();
            return current_package ? 'Operations for Package: ' + current_package.name : 'Current Operations';
        },
        get_rows: function(){
            var model = this.getParent();
            var rows = [];
            var current_package_id = instance.session.user_context.current_package_id;
            _.each( model.operations, function(op){
                if((typeof current_package_id !== 'undefined') && op.result_package_id[0] !== current_package_id){
                    return;
                }
                rows.push({
                    cols: {
                        product: op.product_id[1],
                        uom: op.product_uom ? product_uom[1] : '',
                        qty: op.product_qty,
                    }
                });
            });

            return rows;
        },
    });

    module.PackageSelectorWidget = instance.web.Widget.extend({
        template: 'PackageSelectorWidget',
        get_header: function(){
            return this._header || 'Packages:';
        },
        get_rows: function(){
            var model = this.getParent();
            var current_package = model.get_selected_package();
            var rows = [];
            _.each( model.packages, function(pack){
                rows.push({
                    cols:{ pack: pack.name},
                    id: pack.id,
                    classes: pack === current_package ? ' oe_selected' : '' ,
                });
            });
            return rows;
        },
        renderElement: function(){
            this._super();
            var model = this.getParent();
            this.$('.js_pack_row').each(function(){
                var pack_id = parseInt($(this).attr('pack-id'));

                $('.js_pack_select', this).click(function(){ model.select_package(pack_id); });
                $('.js_pack_plus', this).click(function(){ model.copy_package(pack_id); });
                $('.js_pack_minus', this).click(function(){ model.delete_package(pack_id); });
            });
        },
    });

    module.PickingMainWidget = instance.web.Widget.extend({
        template: 'PickingMainWidget',
        init: function(parent,params){
            this._super(parent,params);
            var self = this;

            this.picking = null;
            this.movelines = null;
            this.operations = null;
            this.packages = null;

            window.pickwidget = this;

            console.log('Action params:', params);
            console.log('Session:',instance.session);

            this.loaded =  this.load();
        },
        load: function(picking_id){
            var self = this;

            if(picking_id){
                var picking = new instance.web.Model('stock.picking.in').call('read',[[picking_id], []]);
            }else{
                var picking = new instance.web.Model('stock.picking.in').query().first();
            }

            var loaded = picking.then(function(picking){
                    self.picking = picking instanceof Array ? picking[0] : picking;
                    console.log('Picking:',self.picking);
                    console.log('User Context:', instance.session.user_context);
                    console.log('Context:', new instance.web.CompoundContext().eval());

                    return new instance.web.Model('stock.move').call('read',[self.picking.move_lines, [], new instance.web.CompoundContext()]);
                }).then(function(movelines){
                    self.movelines = movelines;
                    console.log('Move Lines:',movelines);

                    return new instance.web.Model('stock.pack.operation').call('read',[self.picking.pack_operation_ids, [], new instance.web.CompoundContext()]);
                }).then(function(operations){
                    self.operations = operations;
                    console.log('Operations:',self.operations);

                    var package_ids = [];

                    for(var i = 0; i < operations.length; i++){
                        if(!_.contains(package_ids,operations[i].result_package_id[0])){
                            package_ids.push(operations[i].result_package_id[0]);
                        }
                    }

                    console.log('Package ids:',package_ids);

                    return new instance.web.Model('stock.quant.package').call('read',[package_ids, [], new instance.web.CompoundContext()]);
                }).then(function(packages){
                    self.packages = packages;
                    console.log('Packages:', self.packages);
                });

            return loaded;
        },
        start: function(){
            var self = this;
            instance.webclient.set_content_full_screen(true);
            this.connect_barcode_scanner();

            this.$('.js_pick_quit').click(function(){ self.quit(); });
            this.$('.js_pick_pack').click(function(){ self.pack(); });
            this.$('.js_pick_done').click(function(){ self.done(); });

            $.when(this.loaded).done(function(){
                self.picking_editor = new module.PickingEditorWidget(self);
                self.picking_editor.replace(self.$('.oe_placeholder_picking_editor'));

                self.package_editor = new module.PackageEditorWidget(self);
                self.package_editor.replace(self.$('.oe_placeholder_package_editor'));

                self.package_selector = new module.PackageSelectorWidget(self);
                self.package_selector.replace(self.$('.oe_placeholder_package_selector'));
            });

            return this._super();
        },
        // reloads the data from the provided picking and refresh the ui.
        // (if no picking_id is provided, gets the first picking in the db)
        refresh_ui: function(picking_id){
            var self = this;
            return this.load(picking_id)
                .then(function(){
                    console.log('Refreshing UI');
                    self.picking_editor.renderElement();
                    self.package_editor.renderElement();
                    self.package_selector.renderElement();
                });
        },
        scan: function(ean){
            var self = this;
            console.log('Scan: ',ean);
            new instance.web.Model('stock.picking')
                .call('get_barcode_and_return_todo_stuff', [self.picking.id, ean])
                .then(function(){
                    return self.refresh_ui(self.picking.id);
                });
        },
        pack: function(){
            var self = this;
            console.log('Pack');
            new instance.web.Model('stock.picking')
                .call('action_pack',[[self.picking.id]])
                .then(function(){
                    instance.session.user_context.current_package_id = false;
                    console.log('Context Reset');

                    return self.refresh_ui(self.picking.id);
                });
        },
        done: function(){
            var self = this;
            console.log('Done');
            new instance.web.Model('stock.picking')
                .call('action_done_from_packing_ui',[[self.picking.id]])
                .then(function(new_picking_id){
                    console.log('New picking id:',new_picking_id);
                    //return self.refresh_ui(new_picking_id);
                });
        },
        copy_package: function(package_id){
            console.log('Copy Package:',package_id);
            new instance.web.Model('stock.quant.package')
                .call('action_copy',[[package_id]])
                .then(function(){
                    return self.refresh_ui(self.picking.id);
                });
        },
        delete_package: function(package_id){
            console.log('Delete Package:',package_id);
            new instance.web.Model('stock.quant.package')
                .call('unlink',[[package_id]])
                .then(function(){
                    return self.refresh_ui(self.picking.id);
                });
        },
        select_package: function(package_id){
            console.log('Select Package:',package_id);
            instance.session.user_context.current_package_id = package_id;
            this.package_editor.renderElement();
            this.package_selector.renderElement();
        },
        get_selected_package: function(){
            var current_package;

            _.each( this.packages, function(pack){
                if(pack.id === instance.session.user_context.current_package_id){
                    current_package = pack;
                }
            });

            return current_package;
        },
        connect_barcode_scanner: function(){
            var self =this;
            var code = [];
            var timestamp = 0;
            $('body').delegate('','keyup',function(e){
                if (e.keyCode >= 48 && e.keyCode < 58){
                    if(timestamp + 30 < new Date().getTime()){
                        code = [];
                    }
                    timestamp = new Date().getTime();
                    code.push(e.keyCode - 48);
                    if(code.length === 13){
                        self.scan(code.join(''));
                        code = [];
                    }
                }else{
                    code = [];
                }
            });
        },
        disconnect_barcode_scanner: function(){
            $('body').undelegate('', 'keyup')
        },
        quit: function(){
            console.log('Quit');
            disconnect_barcode_scanner();
            instance.webclient.set_content_full_screen(false);
            window.location = '/'; // FIXME THIS IS SHIT NIV WILL KILL YOU (BY MULTIPLE FACE-STABBING) IF YOU MERGE THIS IN TRUNK
        },
    });
}
<commit_msg>[MERGE] stock.ui: package deselection<commit_after>
function openerp_picking_widgets(instance){
    var module = instance.stock;

    module.PickingEditorWidget = instance.web.Widget.extend({
        template: 'PickingEditorWidget',
        init: function(parent,options){
            this._super(parent,options);
        },
        get_header: function(){
            var model = this.getParent();
            return 'Picking: '+model.picking.name;
        },
        get_rows: function(){
            var model = this.getParent();
            var rows = [];

            _.each( model.movelines, function(moveline){
                rows.push({
                    cols: { product: moveline.product_id[1],
                            qty: moveline.product_qty,
                            rem: moveline.remaining_qty,
                            uom: moveline.product_uom[1],
                            loc: moveline.location_id[1],
                            stat: moveline.state
                    },
                    classes: (moveline.qty_remaining < 0 ? 'oe_invalid' : '')
                });
            });

            return rows;
        },
    });

    module.PackageEditorWidget = instance.web.Widget.extend({
        template: 'PackageEditorWidget',
        get_header: function(){
            var model = this.getParent();
            var current_package = model.get_selected_package();
            return current_package ? 'Operations for Package: ' + current_package.name : 'Current Operations';
        },
        get_rows: function(){
            var model = this.getParent();
            var rows = [];
            var current_package_id = instance.session.user_context.current_package_id;
            _.each( model.operations, function(op){
                if((typeof current_package_id !== 'undefined') && op.result_package_id[0] !== current_package_id){
                    return;
                }
                rows.push({
                    cols: {
                        product: op.product_id[1],
                        uom: op.product_uom ? product_uom[1] : '',
                        qty: op.product_qty,
                    }
                });
            });

            return rows;
        },
    });

    module.PackageSelectorWidget = instance.web.Widget.extend({
        template: 'PackageSelectorWidget',
        get_header: function(){
            return this._header || 'Packages:';
        },
        get_rows: function(){
            var model = this.getParent();
            var current_package = model.get_selected_package();
            var rows = [];
            _.each( model.packages, function(pack){
                rows.push({
                    cols:{ pack: pack.name},
                    id: pack.id,
                    classes: pack === current_package ? ' oe_selected' : '' ,
                });
            });
            return rows;
        },
        renderElement: function(){
            this._super();
            var model = this.getParent();
            this.$('.js_pack_row').each(function(){
                var pack_id = parseInt($(this).attr('pack-id'));

                $('.js_pack_plus', this).click(function(){ model.copy_package(pack_id); });
                $('.js_pack_minus', this).click(function(){ model.delete_package(pack_id); });
                $('.js_pack_select', this).click(function(){
                    if(model.get_selected_package() && model.get_selected_package().id === pack_id){
                        model.deselect_package();
                    }else{
                        model.select_package(pack_id);
                    }
                });
            });
        },
    });

    module.PickingMainWidget = instance.web.Widget.extend({
        template: 'PickingMainWidget',
        init: function(parent,params){
            this._super(parent,params);
            var self = this;

            this.picking = null;
            this.movelines = null;
            this.operations = null;
            this.packages = null;
            this.scan_timestamp = 0;

            window.pickwidget = this;

            console.log('Action params:', params);
            console.log('Session:',instance.session);

            this.loaded =  this.load();
        },
        load: function(picking_id){
            var self = this;

            if(picking_id){
                var picking = new instance.web.Model('stock.picking.in').call('read',[[picking_id], []]);
            }else{
                var picking = new instance.web.Model('stock.picking.in').query().first();
            }

            var loaded = picking.then(function(picking){
                    self.picking = picking instanceof Array ? picking[0] : picking;
                    console.log('Picking:',self.picking);
                    console.log('User Context:', instance.session.user_context);
                    console.log('Context:', new instance.web.CompoundContext().eval());

                    return new instance.web.Model('stock.move').call('read',[self.picking.move_lines, [], new instance.web.CompoundContext()]);
                }).then(function(movelines){
                    self.movelines = movelines;
                    console.log('Move Lines:',movelines);

                    return new instance.web.Model('stock.pack.operation').call('read',[self.picking.pack_operation_ids, [], new instance.web.CompoundContext()]);
                }).then(function(operations){
                    self.operations = operations;
                    console.log('Operations:',self.operations);

                    var package_ids = [];

                    for(var i = 0; i < operations.length; i++){
                        if(!_.contains(package_ids,operations[i].result_package_id[0])){
                            package_ids.push(operations[i].result_package_id[0]);
                        }
                    }

                    console.log('Package ids:',package_ids);

                    return new instance.web.Model('stock.quant.package').call('read',[package_ids, [], new instance.web.CompoundContext()]);
                }).then(function(packages){
                    self.packages = packages;
                    console.log('Packages:', self.packages);
                });

            return loaded;
        },
        start: function(){
            var self = this;
            instance.webclient.set_content_full_screen(true);
            this.connect_barcode_scanner();

            this.$('.js_pick_quit').click(function(){ self.quit(); });
            this.$('.js_pick_pack').click(function(){ self.pack(); });
            this.$('.js_pick_done').click(function(){ self.done(); });

            $.when(this.loaded).done(function(){
                self.picking_editor = new module.PickingEditorWidget(self);
                self.picking_editor.replace(self.$('.oe_placeholder_picking_editor'));

                self.package_editor = new module.PackageEditorWidget(self);
                self.package_editor.replace(self.$('.oe_placeholder_package_editor'));

                self.package_selector = new module.PackageSelectorWidget(self);
                self.package_selector.replace(self.$('.oe_placeholder_package_selector'));
            });

            return this._super();
        },
        // reloads the data from the provided picking and refresh the ui.
        // (if no picking_id is provided, gets the first picking in the db)
        refresh_ui: function(picking_id){
            var self = this;
            return this.load(picking_id)
                .then(function(){
                    console.log('Refreshing UI');
                    self.picking_editor.renderElement();
                    self.package_editor.renderElement();
                    self.package_selector.renderElement();
                });
        },
        scan: function(ean){
            var self = this;
            console.log('Scan: ',ean);
            new instance.web.Model('stock.picking')
                .call('get_barcode_and_return_todo_stuff', [self.picking.id, ean])
                .then(function(){
                    return self.refresh_ui(self.picking.id);
                });
            this.scan_timestamp = new Date().getTime();
        },
        pack: function(){
            var self = this;
            console.log('Pack');
            new instance.web.Model('stock.picking')
                .call('action_pack',[[self.picking.id]])
                .then(function(){
                    instance.session.user_context.current_package_id = false;
                    console.log('Context Reset');

                    return self.refresh_ui(self.picking.id);
                });
        },
        done: function(){
            var self = this;
            console.log('Done');
            new instance.web.Model('stock.picking')
                .call('action_done_from_packing_ui',[[self.picking.id]])
                .then(function(new_picking_id){
                    console.log('New picking id:',new_picking_id);
                    //return self.refresh_ui(new_picking_id);
                });
        },
        copy_package: function(package_id){
            console.log('Copy Package:',package_id);
            new instance.web.Model('stock.quant.package')
                .call('action_copy',[[package_id]])
                .then(function(){
                    return self.refresh_ui(self.picking.id);
                });
        },
        delete_package: function(package_id){
            console.log('Delete Package:',package_id);
            new instance.web.Model('stock.quant.package')
                .call('unlink',[[package_id]])
                .then(function(){
                    return self.refresh_ui(self.picking.id);
                });
        },
        deselect_package: function(){
            console.log('Deselect Package');
            instance.session.user_context.current_package_id = false;
            this.package_editor.renderElement();
            this.package_selector.renderElement();
        },
        select_package: function(package_id){
            console.log('Select Package:',package_id);
            instance.session.user_context.current_package_id = package_id;
            this.package_editor.renderElement();
            this.package_selector.renderElement();
        },
        get_selected_package: function(){
            var current_package;

            _.each( this.packages, function(pack){
                if(pack.id === instance.session.user_context.current_package_id){
                    current_package = pack;
                }
            });

            return current_package;
        },
        connect_barcode_scanner: function(){
            var self =this;
            var numbers = [];
            var timestamp = 0;
            var nocode_timeout_id = 0;
            var nocode_delay = 50;
            function nocode(){
                console.log('NoCode:',numbers);
                numbers = [];
            }
            $('body').delegate('','keyup',function(e){
                if (e.keyCode >= 48 && e.keyCode < 58){
                    clearTimeout(nocode_timeout_id);
                    nocode_timeout_id = setTimeout(nocode,nocode_delay);
                    numbers.push(e.keyCode - 48);
                    if(timestamp + 30 < new Date().getTime()){
                        clearTimeout(nocode_timeout_id);
                        nocode();
                    }
                    timestamp = new Date().getTime();
                    if(numbers.length === 13){
                        self.scan(numbers.join(''));
                        numbers = [];
                        clearTimeout(nocode_timeout_id);
                    }
                }else{
                    nocode();
                }
            });
        },
        disconnect_barcode_scanner: function(){
            $('body').undelegate('', 'keyup')
        },
        quit: function(){
            console.log('Quit');
            disconnect_barcode_scanner();
            instance.webclient.set_content_full_screen(false);
            window.location = '/'; // FIXME THIS IS SHIT NIV WILL KILL YOU (BY MULTIPLE FACE-STABBING) IF YOU MERGE THIS IN TRUNK
        },
    });
}
<|endoftext|>


<commit_before>define(["js/core/Component", "require", "flow", "underscore", "sprd/model/User"], function (Component, require, flow, _, User) {

    // necessary dependency
    var U = User;

    return Component.inherit("sprd.manager.VirtualProductManager", {

        defaults: {
            context: null,

            platform: "EU"
        },

        /***
         * initialized the vp lib
         * @param callback
         */
        initializeVPLib: function (callback) {

            if (!this.$.context) {
                callback && callback(new Error("No context given"));
                return;
            }

            this.synchronizeFunctionCall(this._initializeVPLib, "initializeVPLib", callback, this);
        },

        _initializeVPLib: function (callback) {

            var self = this;

            flow()
                .seq(function(cb) {
                    self.$.context.fetch(cb);
                })
                .par({
                    loadVPLib: function (cb) {
                        var loadComplete = "onSprdLoad",
                            originalSprdLoad = window[loadComplete];

                        window[loadComplete] = function () {
                            try {
                                // invoke original onSprdLoad
                                originalSprdLoad && originalSprdLoad.apply(this, Array.prototype.slice.call(arguments))
                            } catch (e) {
                            }

                            window[loadComplete] = originalSprdLoad;

                            cb();
                        };

                        require(["/sprd-vplib/vplib/vplib.nocache.js"], function () {
                            // complete will be called via onSprdLoad

                                var vpLib = window.vplib;
                                if (vpLib) {
                                    vpLib.onInjectionDone('vplib');
                                } else {
                                    cb(new Error("vplib not found"));
                                }

                        }, cb);

                    },
                    printTypes: function (cb) {
                        self.$.context.getCollection("printTypes").fetch({
                            fullData: true
                        }, cb);
                    }
                })
                .seq("vpCreator", function () {

                    var printTypes = _.map(this.vars.printTypes.$items, function(printType) {
                        return printType.$context.$dataSource.composeModel(printType);
                    });

                    return window["sprd"].getVPCreator(
                        (self.$.platform || "EU").toLowerCase(),
                        null,
                        null,
                        null,
                        printTypes,
                        null);
                })
                .exec(function (err, results) {
                    callback && callback(err, results.vpCreator);
                });

        },

        _generate: function (method, originalProduct, newProductType, callback) {

            var self = this;

            //noinspection JSValidateTypes
            flow()
                .par({
                    designs: function (cb) {
                        var designs = [];

                        //noinspection JSValidateTypes
                        flow()
                            .seq(function (cb) {
                                originalProduct.fetch({
                                    fetchSubModels: ["productType"]
                                }, cb);
                            })
                            .seq(function (cb) {

                                _.each(originalProduct.$data.configurations, function(configuration) {
                                    if (configuration.type === "design") {
                                        var designId = configuration.designs[0].href.split("/").pop();
                                        designs.push(self.$.context.$.designs.createItem(designId));
                                    }
                                });

                                flow()
                                    .parEach(designs, function (design, cb) {
                                        design.fetch(cb);
                                    })
                                    .exec(cb);
                            })
                            .exec(function (err) {
                                cb && cb(err, designs);
                            });

                    },
                    newProductType: function (cb) {
                        newProductType.fetch(cb);
                    },
                    vpCreator: function (cb) {
                        self.initializeVPLib(cb);
                    }
                })
                .seq("result", function () {
                    var vpCreator = this.vars.vpCreator,
                        designs = _.map(this.vars.designs, function (design) {
                            return design.$data;
                        }),
                        productType = originalProduct.$.productType;

                    var result = vpCreator[method](originalProduct.$data, newProductType.$.id, null, designs, [
                        productType.$data,
                        newProductType.$data
                    ]);

                    if (!result) {
                        throw new Error("No result returned");
                    }

                    return result;
                })
                .exec(function (err, results) {
                    callback && callback(err, results.result);
                });

        },

        generateVPString: function (originalProduct, newProductType, callback) {
            this._generate("generateVirtualProductString", originalProduct, newProductType, callback);
        },

        generateVirtualProduct: function(originalProduct, newProductType, callback) {
            this._generate("generateVirtualProduct", originalProduct, newProductType, callback);
        }

    });
});
<commit_msg>VirtualProductManager now returns a VirtualProduct<commit_after>define(["js/core/Component", "require", "flow", "underscore", "sprd/model/User", "sprd/bindable/VirtualProduct"], function (Component, require, flow, _, User, VirtualProduct) {

    // necessary dependency
    var U = User;

    return Component.inherit("sprd.manager.VirtualProductManager", {

        defaults: {
            context: null,

            platform: "EU"
        },

        /***
         * initialized the vp lib
         * @param callback
         */
        initializeVPLib: function (callback) {

            if (!this.$.context) {
                callback && callback(new Error("No context given"));
                return;
            }

            this.synchronizeFunctionCall(this._initializeVPLib, "initializeVPLib", callback, this);
        },

        _initializeVPLib: function (callback) {

            var self = this;

            flow()
                .seq(function(cb) {
                    self.$.context.fetch(cb);
                })
                .par({
                    loadVPLib: function (cb) {
                        var loadComplete = "onSprdLoad",
                            originalSprdLoad = window[loadComplete];

                        window[loadComplete] = function () {
                            try {
                                // invoke original onSprdLoad
                                originalSprdLoad && originalSprdLoad.apply(this, Array.prototype.slice.call(arguments))
                            } catch (e) {
                            }

                            window[loadComplete] = originalSprdLoad;

                            cb();
                        };

                        require(["/sprd-vplib/vplib/vplib.nocache.js"], function () {
                            // complete will be called via onSprdLoad

                                var vpLib = window.vplib;
                                if (vpLib) {
                                    vpLib.onInjectionDone('vplib');
                                } else {
                                    cb(new Error("vplib not found"));
                                }

                        }, cb);

                    },
                    printTypes: function (cb) {
                        self.$.context.getCollection("printTypes").fetch({
                            fullData: true
                        }, cb);
                    }
                })
                .seq("vpCreator", function () {

                    var printTypes = _.map(this.vars.printTypes.$items, function(printType) {
                        return printType.$context.$dataSource.composeModel(printType);
                    });

                    return window["sprd"].getVPCreator(
                        (self.$.platform || "EU").toLowerCase(),
                        null,
                        null,
                        null,
                        printTypes,
                        null);
                })
                .exec(function (err, results) {
                    callback && callback(err, results.vpCreator);
                });

        },

        _generate: function (originalProduct, newProductType, callback) {

            var self = this;

            //noinspection JSValidateTypes
            flow()
                .par({
                    designs: function (cb) {
                        var designs = [];

                        //noinspection JSValidateTypes
                        flow()
                            .seq(function (cb) {
                                originalProduct.fetch({
                                    fetchSubModels: ["productType"]
                                }, cb);
                            })
                            .seq(function (cb) {

                                _.each(originalProduct.$data.configurations, function(configuration) {
                                    if (configuration.type === "design") {
                                        var designId = configuration.designs[0].href.split("/").pop();
                                        designs.push(self.$.context.$.designs.createItem(designId));
                                    }
                                });

                                flow()
                                    .parEach(designs, function (design, cb) {
                                        design.fetch(cb);
                                    })
                                    .exec(cb);
                            })
                            .exec(function (err) {
                                cb && cb(err, designs);
                            });

                    },
                    newProductType: function (cb) {
                        newProductType.fetch(cb);
                    },
                    vpCreator: function (cb) {
                        self.initializeVPLib(cb);
                    }
                })
                .seq("result", function () {
                    var vpCreator = this.vars.vpCreator,
                        designs = _.map(this.vars.designs, function (design) {
                            return design.$data;
                        }),
                        productType = originalProduct.$.productType;

                    var productPayload = vpCreator["generateVirtualProduct"](originalProduct.$data, newProductType.$.id, null, designs, [
                        productType.$data,
                        newProductType.$data
                    ]);
                    var vpString = vpCreator["generateVirtualProductString"](originalProduct.$data, newProductType.$.id, null, designs, [
                        productType.$data,
                        newProductType.$data
                    ]);

                    if (!productPayload) {
                        throw new Error("No result returned");
                    }

                    return new VirtualProduct({
                        originalProduct: originalProduct,
                        productPayload: productPayload,
                        vpString: vpString,
                        productType: newProductType,
                        viewId: productPayload.defaultValues.defaultView.id
                    });

                })
                .exec(function (err, results) {
                    callback && callback(err, results.result);
                });

        },

        generate: function(originalProduct, newProductType, callback) {
            this._generate(originalProduct, newProductType, callback);
        }

    });
});
<|endoftext|>


<commit_before>/*
==================================================================================================
  Core - JavaScript Foundation
  Copyright 2010-2011 Sebastian Werner
==================================================================================================
*/

(function(global)
{
	// Jasy is replacing this call via the kernel permutation
	var translation = core.Env.getValue("translation");

	/**
	 *
	 *
	 */
	core.Module("core.Locale",
	{
		/**
		 * Quick and easy string templating using %1, %2, etc. as placeholders
		 * and an array for the data.
		 *
		 * @param msg {String} Input string with placeholders
		 * @param data {Array} List of values
		 * @param start {Integer?-1} Where to start in the array. Defaults to -1 which is
		 *	 useful when the template string should map %1 = data[0]
		 * @return {String} Result string
		 */
		template : function(msg, data, start)
		{
			// %1 = first, %2 = second, ...
			start = start == null ? -1 : start - 1;
			return msg.replace(/%([0-9])/g, function(match, pos) {
				return data[start+parseInt(pos)];
			});
		},

		/**
		 * Applies the plural rule of the current locale and returns the
		 * field index on the translation data. This is the data used
		 * by the classical GNU gettext tools. See also:
		 * http://www.gnu.org/software/hello/manual/gettext/Plural-forms.html
		 *
		 * @param n {Number} Number to test
		 * @return {String} One of 0, 1, 2, 3, 4, 5 or 6
		 */
		plural : (function(fields, Plural)
		{
			var code="", pos=0;
			var field, expr;

			for (var i=0; i<5; i++)
			{
				field = fields[i];
				if (expr = Plural[field]) {
					code += "if(" + expr + ")return " + (pos++) + ";";
				}
			}

			code += "return " + pos + ";"

			return new Function("n", code);
		})(["ZERO", "ONE", "TWO", "FEW", "MANY"], locale.Plural),

		/**
		 * Translates the given message and replaces placeholders in the result string.
		 *
		 * @param msg {String} Message to translate (used as a fallback when no translation is available)
		 * @param varargs {...} Placeholder values
		 * @return {String} Translated string
		 */
		tr : function(msg, varargs)
		{
			var replacement = translation[msg] || msg;
			return arguments.length <= 1 ? replacement : core.Locale.template(replacement, arguments, 1);
		},

		/**
		 * Translates the given message (with a hint for the translator) and
		 * replaces placeholders in the result string.
		 *
		 * @param hint {String} Hint for the translator of the message
		 * @param msg {String} Message to translate (used as a fallback when no translation is available)
		 * @param varargs {...} Placeholder values
		 * @return {String} Translated string
		 */
		trc : function(hint, msg, varargs)
		{
			var replacement = translation[msg] || msg;
			return arguments.length <= 2 ? replacement : core.Locale.template(replacement, arguments, 2);
		},

		/**
		 * Translates the given message and replaces placeholders in the result string.
		 *
		 * @param msgSingular {String} Fallback message for singular case
		 * @param msgPlural {String} Fallback message for plural case
		 * @param number {Integer} Number of items (chooses between the exact translation which is being used)
		 * @param varargs {...} Placeholder values
		 * @return {String} Translated string
		 */
		trn : function(msgSingular, msgPlural, number, varargs)
		{
			// Matching is based on singular "msgid"
			var replacement = translation[msgSingular];

			// Do numeric lookup
			if (typeof replacement == "object") {
				var result = replacement[core.Locale.plural(number)];
			}

			// Fallback to programmatically defined messages
			if (!result) {
				result = number == 1 ? msgSingular : msgPlural;
			}

			return arguments.length <= 3 ? result : core.Locale.template(result, arguments, 3);
		}
	});
})(this);
<commit_msg>Minor fix<commit_after>/*
==================================================================================================
  Core - JavaScript Foundation
  Copyright 2010-2011 Sebastian Werner
==================================================================================================
*/

(function(global)
{
	// Jasy is replacing this call via the kernel permutation
	var translation = core.Env.getValue("translation");

	/**
	 *
	 *
	 */
	core.Module("core.Locale",
	{
		/**
		 * Quick and easy string templating using %1, %2, etc. as placeholders
		 * and an array for the data.
		 *
		 * @param msg {String} Input string with placeholders
		 * @param data {Array} List of values
		 * @param start {Integer?-1} Where to start in the array. Defaults to -1 which is
		 *	 useful when the template string should map %1 = data[0]
		 * @return {String} Result string
		 */
		template : function(msg, data, start)
		{
			// %1 = first, %2 = second, ...
			start = start == null ? -1 : start - 1;
			return msg.replace(/%([0-9])/g, function(match, pos) {
				return data[start+parseInt(pos)];
			});
		},

		/**
		 * Applies the plural rule of the current locale and returns the
		 * field index on the translation data. This is the data used
		 * by the classical GNU gettext tools. See also:
		 * http://www.gnu.org/software/hello/manual/gettext/Plural-forms.html
		 *
		 * @param n {Number} Number to test
		 * @return {String} One of 0, 1, 2, 3, 4, 5 or 6
		 */
		plural : global.locale && (function(fields, Plural)
		{
			var code="", pos=0;
			var field, expr;

			for (var i=0; i<5; i++)
			{
				field = fields[i];
				if (expr = Plural[field]) {
					code += "if(" + expr + ")return " + (pos++) + ";";
				}
			}

			code += "return " + pos + ";"

			return new Function("n", code);
		})(["ZERO", "ONE", "TWO", "FEW", "MANY"], locale.Plural),

		/**
		 * Translates the given message and replaces placeholders in the result string.
		 *
		 * @param msg {String} Message to translate (used as a fallback when no translation is available)
		 * @param varargs {...} Placeholder values
		 * @return {String} Translated string
		 */
		tr : function(msg, varargs)
		{
			var replacement = translation[msg] || msg;
			return arguments.length <= 1 ? replacement : core.Locale.template(replacement, arguments, 1);
		},

		/**
		 * Translates the given message (with a hint for the translator) and
		 * replaces placeholders in the result string.
		 *
		 * @param hint {String} Hint for the translator of the message
		 * @param msg {String} Message to translate (used as a fallback when no translation is available)
		 * @param varargs {...} Placeholder values
		 * @return {String} Translated string
		 */
		trc : function(hint, msg, varargs)
		{
			var replacement = translation[msg] || msg;
			return arguments.length <= 2 ? replacement : core.Locale.template(replacement, arguments, 2);
		},

		/**
		 * Translates the given message and replaces placeholders in the result string.
		 *
		 * @param msgSingular {String} Fallback message for singular case
		 * @param msgPlural {String} Fallback message for plural case
		 * @param number {Integer} Number of items (chooses between the exact translation which is being used)
		 * @param varargs {...} Placeholder values
		 * @return {String} Translated string
		 */
		trn : global.locale && function(msgSingular, msgPlural, number, varargs)
		{
			// Matching is based on singular "msgid"
			var replacement = translation[msgSingular];

			// Do numeric lookup
			if (typeof replacement == "object") {
				var result = replacement[core.Locale.plural(number)];
			}

			// Fallback to programmatically defined messages
			if (!result) {
				result = number == 1 ? msgSingular : msgPlural;
			}

			return arguments.length <= 3 ? result : core.Locale.template(result, arguments, 3);
		}
	});
})(this);
<|endoftext|>


<commit_before>module.exports = function (context, message) {

    var err = null;

    var userdata = context.bindings.userdata[0];
    context.log(userdata);//TEMP LOGGING

    if (!userdata.twitter && !userdata.facebook || !userdata.instagram) {
        console.log('No social profiles');

        err = new Error('No social profiles');
    }

    if (!userdata.id) {
        console.log('No user id');

        err = new Error('No social profiles');
    }

    var data = {
        userid = message.userid
    };

    if (message.twitter) {
        console.log('adding twitter');

        data.twitter = {
            id: message.twitter.$id,
            token: message.twitter.token,
            username: message.twitter.username,
        };
    }

    if (message.instagram) {
        console.log('adding instagram');

        data.instagram = {
            id: message.instagram.$id,
            token: message.instagram.token,
            username: message.instagram.username,
        };
    }

    if (message.facebook) {
        console.log('adding facebook');

        data.facebook = {
            id: message.facebook.$id,
            token: message.facebook.token,
            username: message.facebook.email,
        };
    }

    context.done(err, data);
};<commit_msg>switching message<commit_after>module.exports = function (context, message) {

    var err = null;

    var userdata = context.bindings.userdata[0];
    context.log(userdata);//TEMP LOGGING

    if (!userdata.twitter && !userdata.facebook || !userdata.instagram) {
        console.log('No social profiles');

        err = new Error('No social profiles');
    }

    if (!userdata.id) {
        console.log('No user id');

        err = new Error('No social profiles');
    }

    var data = {
        userid = userdata.id,
        platform = message.platform,
        mediaid = message.mediaid
    };

    if (message.twitter) {
        console.log('adding twitter');

        data.twitter = {
            id: message.twitter.$id,
            token: message.twitter.token,
            username: message.twitter.username,
        };
    }

    if (message.instagram) {
        console.log('adding instagram');

        data.instagram = {
            id: message.instagram.$id,
            token: message.instagram.token,
            username: message.instagram.username,
        };
    }

    if (message.facebook) {
        console.log('adding facebook');

        data.facebook = {
            id: message.facebook.$id,
            token: message.facebook.token,
            username: message.facebook.email,
        };
    }

    context.done(err, data);
};<|endoftext|>


<commit_before><commit_msg>Add examples accessing Nod API to get Field and data feed content in main.js file<commit_after><|endoftext|>


<commit_before>/**
 * Copyright (c) 2015, Facebook, Inc.  All rights reserved.
 *
 * Facebook, Inc. ("Facebook") owns all right, title and interest, including
 * all intellectual property and other proprietary rights, in and to the React
 * Native CustomComponents software (the "Software").  Subject to your
 * compliance with these terms, you are hereby granted a non-exclusive,
 * worldwide, royalty-free copyright license to (1) use and copy the Software;
 * and (2) reproduce and distribute the Software as part of your own software
 * ("Your Software").  Facebook reserves all rights not expressly granted to
 * you in this license agreement.
 *
 * THE SOFTWARE AND DOCUMENTATION, IF ANY, ARE PROVIDED "AS IS" AND ANY EXPRESS
 * OR IMPLIED WARRANTIES (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED.
 * IN NO EVENT SHALL FACEBOOK OR ITS AFFILIATES, OFFICERS, DIRECTORS OR
 * EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
import React, {
  PropTypes,
} from 'react';
import {
  Platform,
  Animated,
  Image,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import Actions from './Actions';
import _drawerImage from './menu_burger.png';
import _backButtonImage from './back_chevron.png';

const styles = StyleSheet.create({
  title: {
    textAlign: 'center',
    marginTop: 10,
    fontSize: 18,
    fontWeight: '500',
    color: '#0A0A0A',
    position: 'absolute',
    ...Platform.select({
      ios: {
        top: 20,
      },
      android: {
        top: 5,
      },
    }),
    left: 0,
    right: 0,
  },
  header: {
    backgroundColor: '#EFEFF2',
    paddingTop: 0,
    top: 0,
    ...Platform.select({
      ios: {
        height: 64,
      },
      android: {
        height: 54,
      },
    }),
    right: 0,
    left: 0,
    borderBottomWidth: 0.5,
    borderBottomColor: '#828287',
    position: 'absolute',
  },
  backButton: {
    width: 130,
    height: 37,
    position: 'absolute',
    ...Platform.select({
      ios: {
        top: 22,
      },
      android: {
        top: 10,
      },
    }),
    left: 2,
    padding: 8,
    flexDirection: 'row',
  },
  rightButton: {
    width: 100,
    height: 37,
    position: 'absolute',
    ...Platform.select({
      ios: {
        top: 22,
      },
      android: {
        top: 10,
      },
    }),
    right: 2,
    padding: 8,
  },
  leftButton: {
    width: 100,
    height: 37,
    position: 'absolute',
    ...Platform.select({
      ios: {
        top: 20,
      },
      android: {
        top: 8,
      },
    }),
    left: 2,
    padding: 8,
  },
  barRightButtonText: {
    color: 'rgb(0, 122, 255)',
    textAlign: 'right',
    fontSize: 17,
  },
  barBackButtonText: {
    color: 'rgb(0, 122, 255)',
    textAlign: 'left',
    fontSize: 17,
    paddingLeft: 6,
  },
  barLeftButtonText: {
    color: 'rgb(0, 122, 255)',
    textAlign: 'left',
    fontSize: 17,
  },
  backButtonImage: {
    width: 13,
    height: 21,
  },
  rightButtonIconStyle: {

  },
  defaultImageStyle: {
    height: 24,
    resizeMode: 'contain',
  },
});

const propTypes = {
  navigationState: PropTypes.object,
  backButtonImage: Image.propTypes.source,
  wrapBy: PropTypes.any,
  component: PropTypes.any,
  backButtonTextStyle: Text.propTypes.style,
  leftButtonStyle: View.propTypes.style,
  leftButtonIconStyle: Image.propTypes.style,
  getTitle: PropTypes.func,
  titleStyle: Text.propTypes.style,
  titleOpacity: PropTypes.number,
  position: PropTypes.object,
  navigationBarStyle: View.propTypes.style,
  renderTitle: PropTypes.any,
};

const contextTypes = {
  drawer: PropTypes.object,
};

const defaultProps = {
  drawerImage: _drawerImage,
  backButtonImage: _backButtonImage,
  titleOpacity: 1,
};

class NavBar extends React.Component {

  constructor(props) {
    super(props);

    this.renderRightButton = this.renderRightButton.bind(this);
    this.renderBackButton = this.renderBackButton.bind(this);
    this.renderLeftButton = this.renderLeftButton.bind(this);
    this.renderTitle = this.renderTitle.bind(this);
  }

  renderBackButton() {
    const state = this.props.navigationState;
    const childState = state.children[state.index];
    const BackButton = (childState.component && childState.component.backButton) || state.backButton
      || childState.backButton;
    const textButtonStyle = [
      styles.barBackButtonText,
      this.props.backButtonTextStyle,
      state.backButtonTextStyle,
      childState.backButtonTextStyle,
    ];
    const style = [
      styles.backButton,
      this.props.leftButtonStyle,
      state.leftButtonStyle,
      childState.leftButtonStyle,
    ];
    if (BackButton) {
      return (
        <BackButton
          testID="backNavButton"
          textButtonStyle={textButtonStyle}
          style={style}
        />
      );
    }
    let buttonImage = childState.backButtonImage ||
      state.backButtonImage || this.props.backButtonImage;
    let onPress = childState.onBack || Actions.pop;

    if (state.index === 0) {
      return null;
    }

    let text = childState.backTitle ?
      <Text style={textButtonStyle}>
        {childState.backTitle}
      </Text>
      : null;

    return (
      <TouchableOpacity
        testID="backNavButton"
        style={style}
        onPress={onPress}
      >
        {buttonImage && !childState.hideBackImage &&
          <Image
            source={buttonImage}
            style={[
              styles.backButtonImage,
              this.props.leftButtonIconStyle,
              state.barButtonIconStyle,
              state.leftButtonIconStyle,
              childState.leftButtonIconStyle,
            ]}
          />
        }
        {text}
      </TouchableOpacity>
    );
  }

  renderRightButton() {
    const self = this;
    function tryRender(state, wrapBy) {
      if (!state) {
        return null;
      }
      const textStyle = [styles.barRightButtonText, self.props.rightButtonTextStyle,
        state.rightButtonTextStyle];
      const style = [styles.rightButton, self.props.rightButtonStyle, state.rightButtonStyle];
      if (state.rightButton) {
        let Button = state.rightButton;
        if (wrapBy) {
          Button = wrapBy(Button);
        }
        return (
          <Button
            {...self.props}
            {...state}
            key={'rightNavBarBtn'}
            testID="rightNavButton"
            style={style}
            textButtonStyle={textStyle}
          />
        );
      }
      if (state.onRight && (state.rightTitle || state.rightButtonImage)) {
        const onPress = state.onRight.bind(null, state);
        return (
          <TouchableOpacity
            key={'rightNavBarBtn'}
            testID="rightNavButton"
            style={style}
            onPress={onPress}
          >
            {state.rightTitle &&
              <Text style={textStyle}>
                {state.rightTitle}
              </Text>
            }
            {state.rightButtonImage &&
              <View style={{ flex: 1, justifyContent: 'center', alignItems: 'flex-end' }}>
                <Image
                  source={state.rightButtonImage}
                  style={state.rightButtonIconStyle}
                />
              </View>
            }
          </TouchableOpacity>
        );
      }
      if ((!!state.onRight ^ !!(typeof(state.rightTitle) !== 'undefined'
        || typeof(state.rightButtonImage) !== 'undefined'))) {
        console.warn(
          `Both onRight and rightTitle/rightButtonImage
            must be specified for the scene: ${state.name}`
        );
      }
      return null;
    }
    return tryRender(this.props.component, this.props.wrapBy) || tryRender(this.props);
  }

  renderLeftButton() {
    const self = this;
    const drawer = this.context.drawer;
    function tryRender(state, wrapBy) {
      let onPress = state.onLeft;
      let buttonImage = state.leftButtonImage;
      let menuIcon = state.drawerIcon;
      const style = [styles.leftButton, self.props.leftButtonStyle, state.leftButtonStyle];
      const textStyle = [styles.barLeftButtonText, self.props.leftButtonTextStyle,
        state.leftButtonTextStyle];
      const leftButtonStyle = [styles.defaultImageStyle, state.leftButtonIconStyle];

      if (state.leftButton) {
        let Button = state.leftButton;
        if (wrapBy) {
          Button = wrapBy(Button);
        }
        return (
          <Button
            {...self.props}
            {...state}
            key={'leftNavBarBtn'}
            testID="leftNavButton"
            style={style}
            textStyle={textStyle}
          />
        );
      }

      if (!onPress && !!drawer && typeof drawer.toggle === 'function') {
        buttonImage = state.drawerImage;
        if (buttonImage || menuIcon) {
          onPress = drawer.toggle;
        }
        if (!menuIcon) {
          menuIcon = (
            <Image
              source={buttonImage}
              style={leftButtonStyle}
            />
          );
        }
      }

      if (onPress && (state.leftTitle || buttonImage)) {
        onPress = onPress.bind(null, state);
        return (
          <TouchableOpacity
            key={'leftNavBarBtn'}
            testID="leftNavButton"
            style={style}
            onPress={onPress}
          >
            {state.leftTitle &&
              <Text style={textStyle}>
                {state.leftTitle}
              </Text>
            }
            {buttonImage &&
              <View style={{ flex: 1, justifyContent: 'center', alignItems: 'flex-start' }}>
                {menuIcon || <Image
                  source={buttonImage}
                  style={state.leftButtonIconStyle || styles.defaultImageStyle}
                />
                }
              </View>
            }
          </TouchableOpacity>
        );
      }
      if ((!!state.onLeft ^ !!(state.leftTitle || buttonImage))) {
        console.warn(
          `Both onLeft and leftTitle/leftButtonImage
            must be specified for the scene: ${state.name}`
        );
      }
      return null;
    }
    return tryRender(this.props.component, this.props.wrapBy) || tryRender(this.props);
  }

  renderTitle(childState, index:number) {
    const title = this.props.getTitle ? this.props.getTitle(childState) : childState.title;
    return (
      <Animated.Text
        key={childState.key}
        style={[
          styles.title,
          this.props.titleStyle,
          this.props.navigationState.titleStyle,
          childState.titleStyle,
          {
            opacity: this.props.position.interpolate({
              inputRange: [index - 1, index, index + 1],
              outputRange: [0, this.props.titleOpacity, 0],
            }),
            left: this.props.position.interpolate({
              inputRange: [index - 1, index + 1],
              outputRange: [200, -200],
            }),
            right: this.props.position.interpolate({
              inputRange: [index - 1, index + 1],
              outputRange: [-200, 200],
            }),
          },
        ]}
      >
        {title}
      </Animated.Text>
    );
  }

  render() {
    let state = this.props.navigationState;
    let selected = state.children[state.index];
    while (selected.hasOwnProperty('children')) {
      state = selected;
      selected = selected.children[selected.index];
    }
    const navProps = { ...this.props, ...selected };
    const renderLeftButton = selected.renderLeftButton ||
      selected.component.renderLeftButton ||
      this.renderLeftButton;
    const renderRightButton = selected.renderRightButton ||
      selected.component.renderRightButton ||
      this.renderRightButton;
    const renderBackButton = selected.renderBackButton ||
      selected.component.renderBackButton ||
      this.renderBackButton;
    const renderTitle = selected.renderTitle ||
      selected.component.renderTitle ||
      this.props.renderTitle;
    return (
      <Animated.View
        style={[
          styles.header,
          this.props.navigationBarStyle,
          state.navigationBarStyle,
          selected.navigationBarStyle,
        ]}
      >
        {renderTitle ? renderTitle(navProps) : state.children.map(this.renderTitle, this)}
        {renderBackButton(navProps) || renderLeftButton(navProps)}
        {renderRightButton(navProps)}
      </Animated.View>
    );
  }
}

NavBar.propTypes = propTypes;
NavBar.contextTypes = contextTypes;
NavBar.defaultProps = defaultProps;

export default NavBar;
<commit_msg>Removed fontWeight style from NavBar title (#873)<commit_after>/**
 * Copyright (c) 2015, Facebook, Inc.  All rights reserved.
 *
 * Facebook, Inc. ("Facebook") owns all right, title and interest, including
 * all intellectual property and other proprietary rights, in and to the React
 * Native CustomComponents software (the "Software").  Subject to your
 * compliance with these terms, you are hereby granted a non-exclusive,
 * worldwide, royalty-free copyright license to (1) use and copy the Software;
 * and (2) reproduce and distribute the Software as part of your own software
 * ("Your Software").  Facebook reserves all rights not expressly granted to
 * you in this license agreement.
 *
 * THE SOFTWARE AND DOCUMENTATION, IF ANY, ARE PROVIDED "AS IS" AND ANY EXPRESS
 * OR IMPLIED WARRANTIES (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED.
 * IN NO EVENT SHALL FACEBOOK OR ITS AFFILIATES, OFFICERS, DIRECTORS OR
 * EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
import React, {
  PropTypes,
} from 'react';
import {
  Platform,
  Animated,
  Image,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import Actions from './Actions';
import _drawerImage from './menu_burger.png';
import _backButtonImage from './back_chevron.png';

const styles = StyleSheet.create({
  title: {
    textAlign: 'center',
    marginTop: 10,
    fontSize: 18,
    color: '#0A0A0A',
    position: 'absolute',
    ...Platform.select({
      ios: {
        top: 20,
      },
      android: {
        top: 5,
      },
    }),
    left: 0,
    right: 0,
  },
  header: {
    backgroundColor: '#EFEFF2',
    paddingTop: 0,
    top: 0,
    ...Platform.select({
      ios: {
        height: 64,
      },
      android: {
        height: 54,
      },
    }),
    right: 0,
    left: 0,
    borderBottomWidth: 0.5,
    borderBottomColor: '#828287',
    position: 'absolute',
  },
  backButton: {
    width: 130,
    height: 37,
    position: 'absolute',
    ...Platform.select({
      ios: {
        top: 22,
      },
      android: {
        top: 10,
      },
    }),
    left: 2,
    padding: 8,
    flexDirection: 'row',
  },
  rightButton: {
    width: 100,
    height: 37,
    position: 'absolute',
    ...Platform.select({
      ios: {
        top: 22,
      },
      android: {
        top: 10,
      },
    }),
    right: 2,
    padding: 8,
  },
  leftButton: {
    width: 100,
    height: 37,
    position: 'absolute',
    ...Platform.select({
      ios: {
        top: 20,
      },
      android: {
        top: 8,
      },
    }),
    left: 2,
    padding: 8,
  },
  barRightButtonText: {
    color: 'rgb(0, 122, 255)',
    textAlign: 'right',
    fontSize: 17,
  },
  barBackButtonText: {
    color: 'rgb(0, 122, 255)',
    textAlign: 'left',
    fontSize: 17,
    paddingLeft: 6,
  },
  barLeftButtonText: {
    color: 'rgb(0, 122, 255)',
    textAlign: 'left',
    fontSize: 17,
  },
  backButtonImage: {
    width: 13,
    height: 21,
  },
  rightButtonIconStyle: {

  },
  defaultImageStyle: {
    height: 24,
    resizeMode: 'contain',
  },
});

const propTypes = {
  navigationState: PropTypes.object,
  backButtonImage: Image.propTypes.source,
  wrapBy: PropTypes.any,
  component: PropTypes.any,
  backButtonTextStyle: Text.propTypes.style,
  leftButtonStyle: View.propTypes.style,
  leftButtonIconStyle: Image.propTypes.style,
  getTitle: PropTypes.func,
  titleStyle: Text.propTypes.style,
  titleOpacity: PropTypes.number,
  position: PropTypes.object,
  navigationBarStyle: View.propTypes.style,
  renderTitle: PropTypes.any,
};

const contextTypes = {
  drawer: PropTypes.object,
};

const defaultProps = {
  drawerImage: _drawerImage,
  backButtonImage: _backButtonImage,
  titleOpacity: 1,
};

class NavBar extends React.Component {

  constructor(props) {
    super(props);

    this.renderRightButton = this.renderRightButton.bind(this);
    this.renderBackButton = this.renderBackButton.bind(this);
    this.renderLeftButton = this.renderLeftButton.bind(this);
    this.renderTitle = this.renderTitle.bind(this);
  }

  renderBackButton() {
    const state = this.props.navigationState;
    const childState = state.children[state.index];
    const BackButton = (childState.component && childState.component.backButton) || state.backButton
      || childState.backButton;
    const textButtonStyle = [
      styles.barBackButtonText,
      this.props.backButtonTextStyle,
      state.backButtonTextStyle,
      childState.backButtonTextStyle,
    ];
    const style = [
      styles.backButton,
      this.props.leftButtonStyle,
      state.leftButtonStyle,
      childState.leftButtonStyle,
    ];
    if (BackButton) {
      return (
        <BackButton
          testID="backNavButton"
          textButtonStyle={textButtonStyle}
          style={style}
        />
      );
    }
    let buttonImage = childState.backButtonImage ||
      state.backButtonImage || this.props.backButtonImage;
    let onPress = childState.onBack || Actions.pop;

    if (state.index === 0) {
      return null;
    }

    let text = childState.backTitle ?
      <Text style={textButtonStyle}>
        {childState.backTitle}
      </Text>
      : null;

    return (
      <TouchableOpacity
        testID="backNavButton"
        style={style}
        onPress={onPress}
      >
        {buttonImage && !childState.hideBackImage &&
          <Image
            source={buttonImage}
            style={[
              styles.backButtonImage,
              this.props.leftButtonIconStyle,
              state.barButtonIconStyle,
              state.leftButtonIconStyle,
              childState.leftButtonIconStyle,
            ]}
          />
        }
        {text}
      </TouchableOpacity>
    );
  }

  renderRightButton() {
    const self = this;
    function tryRender(state, wrapBy) {
      if (!state) {
        return null;
      }
      const textStyle = [styles.barRightButtonText, self.props.rightButtonTextStyle,
        state.rightButtonTextStyle];
      const style = [styles.rightButton, self.props.rightButtonStyle, state.rightButtonStyle];
      if (state.rightButton) {
        let Button = state.rightButton;
        if (wrapBy) {
          Button = wrapBy(Button);
        }
        return (
          <Button
            {...self.props}
            {...state}
            key={'rightNavBarBtn'}
            testID="rightNavButton"
            style={style}
            textButtonStyle={textStyle}
          />
        );
      }
      if (state.onRight && (state.rightTitle || state.rightButtonImage)) {
        const onPress = state.onRight.bind(null, state);
        return (
          <TouchableOpacity
            key={'rightNavBarBtn'}
            testID="rightNavButton"
            style={style}
            onPress={onPress}
          >
            {state.rightTitle &&
              <Text style={textStyle}>
                {state.rightTitle}
              </Text>
            }
            {state.rightButtonImage &&
              <View style={{ flex: 1, justifyContent: 'center', alignItems: 'flex-end' }}>
                <Image
                  source={state.rightButtonImage}
                  style={state.rightButtonIconStyle}
                />
              </View>
            }
          </TouchableOpacity>
        );
      }
      if ((!!state.onRight ^ !!(typeof(state.rightTitle) !== 'undefined'
        || typeof(state.rightButtonImage) !== 'undefined'))) {
        console.warn(
          `Both onRight and rightTitle/rightButtonImage
            must be specified for the scene: ${state.name}`
        );
      }
      return null;
    }
    return tryRender(this.props.component, this.props.wrapBy) || tryRender(this.props);
  }

  renderLeftButton() {
    const self = this;
    const drawer = this.context.drawer;
    function tryRender(state, wrapBy) {
      let onPress = state.onLeft;
      let buttonImage = state.leftButtonImage;
      let menuIcon = state.drawerIcon;
      const style = [styles.leftButton, self.props.leftButtonStyle, state.leftButtonStyle];
      const textStyle = [styles.barLeftButtonText, self.props.leftButtonTextStyle,
        state.leftButtonTextStyle];
      const leftButtonStyle = [styles.defaultImageStyle, state.leftButtonIconStyle];

      if (state.leftButton) {
        let Button = state.leftButton;
        if (wrapBy) {
          Button = wrapBy(Button);
        }
        return (
          <Button
            {...self.props}
            {...state}
            key={'leftNavBarBtn'}
            testID="leftNavButton"
            style={style}
            textStyle={textStyle}
          />
        );
      }

      if (!onPress && !!drawer && typeof drawer.toggle === 'function') {
        buttonImage = state.drawerImage;
        if (buttonImage || menuIcon) {
          onPress = drawer.toggle;
        }
        if (!menuIcon) {
          menuIcon = (
            <Image
              source={buttonImage}
              style={leftButtonStyle}
            />
          );
        }
      }

      if (onPress && (state.leftTitle || buttonImage)) {
        onPress = onPress.bind(null, state);
        return (
          <TouchableOpacity
            key={'leftNavBarBtn'}
            testID="leftNavButton"
            style={style}
            onPress={onPress}
          >
            {state.leftTitle &&
              <Text style={textStyle}>
                {state.leftTitle}
              </Text>
            }
            {buttonImage &&
              <View style={{ flex: 1, justifyContent: 'center', alignItems: 'flex-start' }}>
                {menuIcon || <Image
                  source={buttonImage}
                  style={state.leftButtonIconStyle || styles.defaultImageStyle}
                />
                }
              </View>
            }
          </TouchableOpacity>
        );
      }
      if ((!!state.onLeft ^ !!(state.leftTitle || buttonImage))) {
        console.warn(
          `Both onLeft and leftTitle/leftButtonImage
            must be specified for the scene: ${state.name}`
        );
      }
      return null;
    }
    return tryRender(this.props.component, this.props.wrapBy) || tryRender(this.props);
  }

  renderTitle(childState, index:number) {
    const title = this.props.getTitle ? this.props.getTitle(childState) : childState.title;
    return (
      <Animated.Text
        key={childState.key}
        style={[
          styles.title,
          this.props.titleStyle,
          this.props.navigationState.titleStyle,
          childState.titleStyle,
          {
            opacity: this.props.position.interpolate({
              inputRange: [index - 1, index, index + 1],
              outputRange: [0, this.props.titleOpacity, 0],
            }),
            left: this.props.position.interpolate({
              inputRange: [index - 1, index + 1],
              outputRange: [200, -200],
            }),
            right: this.props.position.interpolate({
              inputRange: [index - 1, index + 1],
              outputRange: [-200, 200],
            }),
          },
        ]}
      >
        {title}
      </Animated.Text>
    );
  }

  render() {
    let state = this.props.navigationState;
    let selected = state.children[state.index];
    while (selected.hasOwnProperty('children')) {
      state = selected;
      selected = selected.children[selected.index];
    }
    const navProps = { ...this.props, ...selected };
    const renderLeftButton = selected.renderLeftButton ||
      selected.component.renderLeftButton ||
      this.renderLeftButton;
    const renderRightButton = selected.renderRightButton ||
      selected.component.renderRightButton ||
      this.renderRightButton;
    const renderBackButton = selected.renderBackButton ||
      selected.component.renderBackButton ||
      this.renderBackButton;
    const renderTitle = selected.renderTitle ||
      selected.component.renderTitle ||
      this.props.renderTitle;
    return (
      <Animated.View
        style={[
          styles.header,
          this.props.navigationBarStyle,
          state.navigationBarStyle,
          selected.navigationBarStyle,
        ]}
      >
        {renderTitle ? renderTitle(navProps) : state.children.map(this.renderTitle, this)}
        {renderBackButton(navProps) || renderLeftButton(navProps)}
        {renderRightButton(navProps)}
      </Animated.View>
    );
  }
}

NavBar.propTypes = propTypes;
NavBar.contextTypes = contextTypes;
NavBar.defaultProps = defaultProps;

export default NavBar;
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.u2',
  name: 'DAOList',
  extends: 'foam.u2.View',

  requires: [
    'foam.u2.ViewSpec'
  ],

  // documentation: 'Expects its data to be a DAO, and renders one viewFactory for each one.',

  topics: [ 'rowClick' ],

  properties: [
    {
      class: 'foam.u2.ViewSpec',
      name: 'rowView'
    },
    {
      // deprecated
      class: 'foam.u2.ViewFactory',
      name: 'rowFactory'
    },
    {
      name: 'rows_',
      factory: function() { return {}; }
    }
  ],

  methods: [
    function initE() {
      // Just starts out empty.
      this.cssClass(this.myCls());

      // Kick off the select(), that will populate the view.
      this.data.on.put.sub(this.onDAOPut);
      this.data.on.remove.sub(this.onDAORemove);
      this.data.on.reset.sub(this.onDAOReset);
      this.reloadData();
    },

    function createRowView(obj, ctx) {
      // TODO: remove rowFactory support when all code ported
      return this.rowView ?
        this.ViewSpec.createView(this.rowView, {data: obj}, this, ctx) :
        this.rowFactory$f({data: obj}, ctx) ;
    },

    function reloadData() {
      this.data.select({
        put: this.daoPut,
        eof: function() { }
      });
    }
  ],

  listeners: [
    function daoPut(obj) {
      if ( this.rows_[obj.id] ) {
        this.rows_[obj.id].data = obj;
        return;
      }

      var child = this.createRowView(obj, this.__subContext__.createSubContext());

      // TODO: make a single listener of this
      child.on('click', function() {
        this.rowClick.pub(child.data);
      }.bind(this));
      this.rows_[obj.id] = child;
      this.add(child);
    },

    function onDAOPut(_, __, ___, obj) {
      this.daoPut(obj);
    },

    function daoRemove(obj) {
      if ( this.rows_[obj.id] ) {
        this.removeChild(this.rows_[obj.id]);
        delete this.rows_[obj.id];
      }
    },

    function onDAORemove(_, __, ___, obj) {
      this.daoRemove(obj);
    },

    function onDAOReset() {
      this.removeAllChildren();
      this.rows_ = {};
      this.reloadData();
    }
  ]
});
<commit_msg>DAOList(View) now adds a single click listener instead of one per row.<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.u2',
  name: 'DAOList',
  extends: 'foam.u2.View',

  requires: [
    'foam.u2.ViewSpec'
  ],

  // documentation: 'Expects its data to be a DAO, and renders one viewFactory for each one.',

  topics: [ 'rowClick' ],

  properties: [
    {
      class: 'foam.u2.ViewSpec',
      name: 'rowView'
    },
    {
      // deprecated
      class: 'foam.u2.ViewFactory',
      name: 'rowFactory'
    },
    {
      name: 'rows_',
      factory: function() { return {}; }
    }
  ],

  methods: [
    function initE() {
      // Just starts out empty.
      this.
        cssClass(this.myCls()).
        on('click', this.onClick);

      // Kick off the select(), that will populate the view.
      this.data.on.put.sub(this.onDAOPut);
      this.data.on.remove.sub(this.onDAORemove);
      this.data.on.reset.sub(this.onDAOReset);
      this.reloadData();
    },

    function createRowView(obj, ctx) {
      // TODO: remove rowFactory support when all code ported
      return this.rowView ?
        this.ViewSpec.createView(this.rowView, {data: obj}, this, ctx) :
        this.rowFactory$f({data: obj}, ctx) ;
    },

    function reloadData() {
      this.data.select({
        put: this.daoPut,
        eof: function() { }
      });
    }
  ],

  listeners: [
    function onClick(e) {
      var c = this.findChildForEvent(e);
      if ( c ) this.rowClick.pub(c.data);
    },

    function daoPut(obj) {
      if ( this.rows_[obj.id] ) {
        this.rows_[obj.id].data = obj;
        return;
      }

      var child = this.createRowView(obj, this.__subContext__.createSubContext());
      this.rows_[obj.id] = child;
      this.add(child);
    },

    function onDAOPut(_, __, ___, obj) {
      this.daoPut(obj);
    },

    function daoRemove(obj) {
      if ( this.rows_[obj.id] ) {
        this.removeChild(this.rows_[obj.id]);
        delete this.rows_[obj.id];
      }
    },

    function onDAORemove(_, __, ___, obj) {
      this.daoRemove(obj);
    },

    function onDAOReset() {
      this.removeAllChildren();
      this.rows_ = {};
      this.reloadData();
    }
  ]
});
<|endoftext|>


<commit_before>var base_url="//demos.techumber.com/cdn/";

var site_array=[
    base_url+"asserts/css/style.css",
    "//code.jquery.com/jquery-1.11.1.min.js",
    base_url+"js/lib/easing.js",
    base_url +"js/lib/motio.js",
    base_url+"js/lib/preload.js",
    base_url+"js/lib/hover.js",
    base_url+"js/site.js"
];

var index_array=[
  // base_url+"asserts/css/index.css",
  base_url+"js/lib/isotope.js",
  base_url+"js/index.js"
];

var item_array=[
  // base_url+"asserts/css/item.css",
  base_url+"js/lib/prettify/prettify-dark.css",
  base_url+"js/lib/prettify/prettify.js",
  base_url+"js/lib/related-items.js"
];

var static_array=[
	base_url+"asserts/css/static.css"
];

head.ready(document,function(){
  //load hole site
  head.load(site_array,function(){
    console.log("whole site loadded....");
    //test page type
    if(TU_PAGE == "index"){
     $("body").addClass('index').removeClass('static item');
    	head.load(index_array,function(){
    		console.log("index array loadded....");
    	});
    }
    if(TU_PAGE == "item"){
    	head.load(item_array,function(){
        $("body").addClass('item').removeClass('static index');
    		console.log("item array loadded....");
    	});
    }

    if(TU_PAGE == "static_page"){
    	head.load(static_array,function(){
          $("body").addClass('static').removeClass('item index');
    		console.log("item array loadded....");
    	});
    }

  });

});
<commit_msg>added<commit_after>var base_url="//demos.techumber.com/cdn/";

var site_array=[
    base_url+"asserts/css/style.css",
    "//code.jquery.com/jquery-1.11.1.min.js",
    base_url+"js/lib/easing.js",
    base_url +"js/lib/motio.js",
    base_url+"js/lib/preload.js",
    base_url+"js/lib/hover.js",
    base_url+"js/site.js"
];

var index_array=[
  // base_url+"asserts/css/index.css",
  base_url+"js/lib/isotope.js",
  base_url+"js/index.js"
];

var item_array=[
  // base_url+"asserts/css/item.css",
  base_url+"js/lib/prettify/prettify-dark.css",
  base_url+"js/lib/prettify/prettify.js",
  base_url+"js/lib/related-posts.js"
];

var static_array=[
	base_url+"asserts/css/static.css"
];

head.ready(document,function(){
  //load hole site
  head.load(site_array,function(){
    console.log("whole site loadded....");
    //test page type
    if(TU_PAGE == "index"){
     $("body").addClass('index').removeClass('static item');
    	head.load(index_array,function(){
    		console.log("index array loadded....");
    	});
    }
    if(TU_PAGE == "item"){
    	head.load(item_array,function(){
        $("body").addClass('item').removeClass('static index');
    		console.log("item array loadded....");
    	});
    }

    if(TU_PAGE == "static_page"){
    	head.load(static_array,function(){
          $("body").addClass('static').removeClass('item index');
    		console.log("item array loadded....");
    	});
    }

  });

});
<|endoftext|>


<commit_before><commit_msg>refactor: auto destroy pipe socket<commit_after><|endoftext|>


<commit_before>$p.currentIndex = function (array) {
    return array.indexOf($('#Id').val())
}

$p.switchTargets = function () {
    return $('#SwitchTargets').val().split(',')
}

$p.setCurrentIndex = function () {
    var array = $p.switchTargets();
    var index = $p.currentIndex(array);
    $('#CurrentIndex').text(index + 1 + '/' + array.length);
}<commit_msg>Bug fixed: SwitchTargetsが存在しない場合にエラーが発生する問題を解消。<commit_after>$p.currentIndex = function (array) {
    return array.indexOf($('#Id').val())
}

$p.switchTargets = function () {
    var $control = $('#SwitchTargets');
    return $control.length === 1
        ? $control.val().split(',')
        : [];
}

$p.setCurrentIndex = function () {
    var array = $p.switchTargets();
    var index = $p.currentIndex(array);
    $('#CurrentIndex').text(index + 1 + '/' + array.length);
}<|endoftext|>


<commit_before>import {parse} from 'babylon';

import {buildTokenList, buildElementTree} from './elementTree';

export default class Parser {
    constructor() {
        this._strictModeEnabled = true;
    }

    isStrictModeEnabled() {
        return this._strictModeEnabled;
    }

    enableStrictMode() {
        this._strictModeEnabled = true;
    }

    disableStrictMode() {
        this._strictModeEnabled = false;
    }

    parse(code) {
        let ast = this._parseAst(code);
        let tokens = this._processTokens(ast, code);
        return buildElementTree(ast, tokens);
    }

    _parseAst(code) {
        let opts = {
            sourceType: 'module',
            features: {
                'es7.asyncFunctions': true,
                'es7.classProperties': true,
                'es7.comprehensions': true,
                'es7.decorators': true,
                'es7.exponentiationOperator': true,
                'es7.exportExtensions': true,
                'es7.functionBind': true,
                'es7.objectRestSpread': true,
                'es7.trailingFunctionCommas': true,
            },
            plugins: {jsx: true, flow: true},
            strictMode: this._strictModeEnabled
        };
        let ast = parse(code, opts);
        let program = ast.program;
        program.tokens = ast.tokens;
        return program;
    }

    _processTokens(ast, code) {
        return buildTokenList(ast.tokens, code);
    }
}
<commit_msg>Use autogenerated feature option<commit_after>import {parse} from 'babylon';

import {buildTokenList, buildElementTree} from './elementTree';

export default class Parser {
    constructor() {
        this._strictModeEnabled = true;
    }

    isStrictModeEnabled() {
        return this._strictModeEnabled;
    }

    enableStrictMode() {
        this._strictModeEnabled = true;
    }

    disableStrictMode() {
        this._strictModeEnabled = false;
    }

    parse(code) {
        let ast = this._parseAst(code);
        let tokens = this._processTokens(ast, code);
        return buildElementTree(ast, tokens);
    }

    _parseAst(code) {
        let opts = {
            sourceType: 'module',
            ecmaVersion: Infinity,
            // generate with
            // $ node -p "Object.keys(require('babel-core/lib/transformation').pipeline.transformers)
            // .filter(/^$/.test.bind(/^es([7-9]|[0-9]{2,})./))
            // .sort().reduce(function(o, k) { o[k] = true; return o; }, {})"
            features: {
                'es7.asyncFunctions': true,
                'es7.classProperties': true,
                'es7.comprehensions': true,
                'es7.decorators': true,
                'es7.doExpressions': true,
                'es7.exponentiationOperator': true,
                'es7.exportExtensions': true,
                'es7.functionBind': true,
                'es7.objectRestSpread': true,
                'es7.trailingFunctionCommas': true,
            },
            plugins: {jsx: true, flow: true},
            strictMode: this._strictModeEnabled
        };
        let ast = parse(code, opts);
        let program = ast.program;
        program.tokens = ast.tokens;
        return program;
    }

    _processTokens(ast, code) {
        return buildTokenList(ast.tokens, code);
    }
}
<|endoftext|>


<commit_before>import { resolve } from 'path';

// cleaned-up `$HOME` (i.e.: no trailing slash)
const HOME = resolve(process.env.HOME);

/**
 * Attempts to show the given path in
 * a human-friendly form. For example,
 * `/Users/rauchg/test.js` becomes `~/test.js`
 */

export default function toHumanPath (path) {
  return path.replace(HOME, '~');
}
<commit_msg>fix for windows<commit_after>import { resolve } from 'path';
import { homedir } from 'os';

// cleaned-up `$HOME` (i.e.: no trailing slash)
const HOME = resolve(homedir());

/**
 * Attempts to show the given path in
 * a human-friendly form. For example,
 * `/Users/rauchg/test.js` becomes `~/test.js`
 */

export default function toHumanPath (path) {
  return path.replace(HOME, '~');
}
<|endoftext|>