<commit_before>var app = require('http').createServer(),
    io = require('socket.io').listen(app),
    spawn = require('child_process').spawn,
    fs = require('fs');

io.of('/ruby').on('connection', function(socket) {

    var ruby,
        socketOn = false;

    socket.on('codeBuild', function(data) {
        console.log(data);

        var fileSaveError,
            codeLoadError;

        // Save file
        fs.writeFile('games/game.rb', data.fileContent, function(error) {
            fileSaveError = error;

            // Emit file saved
            socket.emit('buildStatus', {
                output: error || 'Code saved.'
            });

            // Check file syntax?

            // Kill old IRB
            if (ruby) {
              oldRuby = ruby;
              oldRuby.kill();
            }

            // Start IRB
            ruby = spawn('irb');

            ruby.stdout.setEncoding('utf8');
            ruby.stderr.setEncoding('utf8');

            // Funnel file into IRB
            socketOn = false;
            ruby.stdin.write(data.fileContent + '\n', function(error) {
                codeLoadError = error;

                // Emit code loaded
                socket.emit('buildStatus', {
                    output: error || 'Game loaded.'
                });

                if (!fileSaveError && !codeLoadError) {
                    socket.emit('buildStatus', {
                        output: 'Build successful!'
                    });
                } else {
                    socket.emit('terminalError', {
                        output: 'Build failed!'
                    });
                }
            });

            // Bind events on IRB
            ruby.stdout.on('data', function(data) {
                console.log('stdout: ' + data);
                if (socketOn) {
                    console.log('socket on');
                    socket.emit('terminalOutput', {
                        output: data
                    });
                }
            });

            ruby.stderr.on('data', function(data) {
                console.log('stderr: ' + data);
                socket.emit('terminalError', {
                    output: data
                });
            });

            ruby.on('close', function(code) {
                console.log('Exit code: ' + code);
            });

        });
    });

    socket.on('terminalInput', function(data) {
        console.log(data);
        socketOn = true;
        if (ruby) {
            ruby.stdin.write(data.input + '\n');
        }
        else {
            socket.emit('terminalError', {
                output: 'Game not built!'
            });
        }
    });

    fs.readFile('games/game.rb', function(err, contents) {
        console.log(contents);
        socket.emit('ready', {
            output: 'Ready!',
            fileContent: contents.toString()
        });
    });
});

app.listen(process.env.PORT || 8888);
<commit_msg>Implement random assigned and unique user id<commit_after>var app = require('http').createServer(),
    io = require('socket.io').listen(app),
    spawn = require('child_process').spawn,
    fs = require('fs');

var generateUserid = function() {
    var id = (Math.random().toString(36)+'00000000000000000').slice(2, 8);
    if (connectedUsers[id] === undefined) return id;
    else return generateUserid();
};

var connectedUsers = {};

io.of('/ruby').on('connection', function(socket) {

    var ruby,
        userid,
        socketOn = false;

    socket.on('codeBuild', function(data) {
        console.log(data);

        var fileSaveError,
            codeLoadError;

        // Save file
        fs.writeFile('games/game.rb', data.fileContent, function(error) {
            fileSaveError = error;

            // Emit file saved
            socket.emit('buildStatus', {
                output: error || 'Code saved.'
            });

            // Check file syntax?

            // Kill old IRB
            if (ruby) {
              oldRuby = ruby;
              oldRuby.kill();
            }

            // Start IRB
            ruby = spawn('irb');

            ruby.stdout.setEncoding('utf8');
            ruby.stderr.setEncoding('utf8');

            // Funnel file into IRB
            socketOn = false;
            ruby.stdin.write(data.fileContent + '\n', function(error) {
                codeLoadError = error;

                // Emit code loaded
                socket.emit('buildStatus', {
                    output: error || 'Game loaded.'
                });

                if (!fileSaveError && !codeLoadError) {
                    socket.emit('buildStatus', {
                        output: 'Build successful!'
                    });
                } else {
                    socket.emit('terminalError', {
                        output: 'Build failed!'
                    });
                }
            });

            // Bind events on IRB
            ruby.stdout.on('data', function(data) {
                console.log('stdout: ' + data);
                if (socketOn) {
                    console.log('socket on');
                    socket.emit('terminalOutput', {
                        output: data
                    });
                }
            });

            ruby.stderr.on('data', function(data) {
                console.log('stderr: ' + data);
                socket.emit('terminalError', {
                    output: data
                });
            });

            ruby.on('close', function(code) {
                console.log('Exit code: ' + code);
            });

        });
    });

    socket.on('terminalInput', function(data) {
        console.log(data);
        socketOn = true;
        if (ruby) {
            ruby.stdin.write(data.input + '\n');
        }
        else {
            socket.emit('terminalError', {
                output: 'Game not built!'
            });
        }
    });

    socket.on('reportUserid', function(data) {
        if (data.userid && !connectedUsers[data.userid]) {
            userid = data.userid;
        } else userid = generateUserid();

        connectedUsers[userid] = true;
        socket.emit('confirmUserid', { userid: userid });
    });

    socket.on('disconnect', function() {
        connectedUsers[userid] = false;
    });

    fs.readFile('games/game.rb', function(err, contents) {
        console.log(contents);
        socket.emit('ready', {
            output: 'Ready!',
            fileContent: contents.toString()
        });
    });
});

app.listen(process.env.PORT || 8888);
<|endoftext|>


<commit_before>/* eslint-disable newline-per-chained-call, no-invalid-this */

"use strict";

const createContext = assert => {
    const context = {
        method() {
            assert.strictEqual( this, context );
        },
    };
    return context;
};

module.exports = require( `../both` )( {
    "use on": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).on( context )();
        prall( `method` ).on( context )();
        assert.done();
    },
    "use bind": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).bind( context )();
        prall( `method` ).bind( context )();
        assert.done();
    },
    "use call": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).call( context );
        prall( `method` ).call( context );
        assert.done();
    },
    "use apply": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).apply( context );
        prall( `method` ).apply( context );
        assert.done();
    },
    "on then on": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).on( {} ).on( context )();
        prall( `method` ).on( {} ).on( context )();
        assert.done();
    },
    "on then bind": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).on( {} ).bind( context )();
        prall( `method` ).on( {} ).bind( context )();
        assert.done();
    },
    "on then apply": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).on( {} ).apply( context );
        prall( `method` ).on( {} ).apply( context );
        assert.done();
    },
    "on then call": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).on( {} ).call( context );
        prall( `method` ).on( {} ).call( context );
        assert.done();
    },
    "bind then bind": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).bind( context ).bind( {} )();
        prall( `method` ).bind( context ).bind( {} )();
        assert.done();
    },
    "bind then on": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).bind( context ).on( {} )();
        prall( `method` ).bind( context ).on( {} )();
        assert.done();
    },
    "bind then apply": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).bind( context ).apply( {} );
        prall( `method` ).bind( context ).apply( {} );
        assert.done();
    },
    "bind then call": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).bind( context ).call( {} );
        prall( `method` ).bind( context ).call( {} );
        assert.done();
    },
} );
<commit_msg>Checks string-based pralls behaviour without context or with bad one<commit_after>/* eslint-disable newline-per-chained-call, no-invalid-this */

"use strict";

const createContext = assert => {
    const context = {
        method() {
            assert.strictEqual( this, context );
        },
    };
    return context;
};

module.exports = require( `../both` )( {
    "use on": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).on( context )();
        prall( `method` ).on( context )();
        assert.done();
    },
    "use bind": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).bind( context )();
        prall( `method` ).bind( context )();
        assert.done();
    },
    "use call": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).call( context );
        prall( `method` ).call( context );
        assert.done();
    },
    "use apply": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).apply( context );
        prall( `method` ).apply( context );
        assert.done();
    },
    "on then on": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).on( {} ).on( context )();
        prall( `method` ).on( {} ).on( context )();
        assert.done();
    },
    "on then bind": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).on( {} ).bind( context )();
        prall( `method` ).on( {} ).bind( context )();
        assert.done();
    },
    "on then apply": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).on( {} ).apply( context );
        prall( `method` ).on( {} ).apply( context );
        assert.done();
    },
    "on then call": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).on( {} ).call( context );
        prall( `method` ).on( {} ).call( context );
        assert.done();
    },
    "bind then bind": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).bind( context ).bind( {} )();
        prall( `method` ).bind( context ).bind( {} )();
        assert.done();
    },
    "bind then on": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).bind( context ).on( {} )();
        prall( `method` ).bind( context ).on( {} )();
        assert.done();
    },
    "bind then apply": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).bind( context ).apply( {} );
        prall( `method` ).bind( context ).apply( {} );
        assert.done();
    },
    "bind then call": prall => assert => {
        assert.expect( 2 );
        const context = createContext( assert );
        prall( context.method ).bind( context ).call( {} );
        prall( `method` ).bind( context ).call( {} );
        assert.done();
    },
    "method name with no context": prall => assert => {
        assert.expect( 1 );
        prall( `method` ).catch( () => assert.ok( true ) ).then( () => assert.done() );
    },
    "method is not a function": prall => assert => {
        assert.expect( 1 );
        prall( `method` ).on( {
            "method": `some string`,
        } ).catch( () => assert.ok( true ) ).then( () => assert.done() );
    },
} );
<|endoftext|>


<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.ui.form.AssignTo = Class.extend({
	init: function(opts) {
		$.extend(this, opts);
		this.btn = this.parent.find(".add-assignment-btn > button").on("click", () => this.add());
		this.btn_wrapper = this.btn.parent();

		this.refresh();
	},
	refresh: function() {
		if(this.frm.doc.__islocal) {
			this.parent.toggle(false);
			return;
		}
		this.parent.toggle(true);
		this.render(this.frm.get_docinfo().assignments);
	},
	render: function(assignments) {
		this.frm.get_docinfo().assignments = assignments;
		this.parent.find(".assignment-row").remove();

		if (this.primary_action) {
			this.primary_action.remove();
			this.primary_action = null;
		}

		if (this.dialog) {
			this.dialog.hide();
		}

		let add_assignment_button = this.parent.find('.add-assignment-btn');

		assignments.forEach(assignment => {
			let user_info = frappe.user_info(assignment.owner);
			user_info.assign_to_name = assignment.name;
			user_info.owner = assignment.owner;
			user_info.avatar = frappe.avatar(assignment.owner);
			user_info.description = assignment.description || "";

			this.get_assignment_block(user_info).insertBefore(add_assignment_button);
			if (assignment.owner === frappe.session.user) {
				this.primary_action = this.frm.page.add_menu_item(__("Assignment Complete"), () => {
					this.remove(frappe.session.user);
				}, "fa fa-check", "btn-success");
			}
		});

	},
	get_assignment_block(assignee_info) {
		let remove_action = false;
		if (assignee_info.owner === frappe.session.user || this.frm.perm[0].write) {
			remove_action = this.remove.bind(this);
		}
		return $(`<li class="assignment-row">`)
			.append(frappe.get_data_pill(assignee_info.owner, assignee_info.owner, remove_action));
	},
	add: function() {
		var me = this;

		if(this.frm.is_new()) {
			frappe.throw(__("Please save the document before assignment"));
			return;
		}

		if(!me.assign_to) {
			me.assign_to = new frappe.ui.form.AssignToDialog({
				method: "frappe.desk.form.assign_to.add",
				doctype: me.frm.doctype,
				docname: me.frm.docname,
				frm: me.frm,
				callback: function (r) {
					me.render(r.message);
				}
			});
		}
		me.assign_to.dialog.clear();
		me.assign_to.dialog.show();
	},
	remove: function(owner) {
		var me = this;

		if(this.frm.is_new()) {
			frappe.throw(__("Please save the document before removing assignment"));
			return;
		}

		frappe.call({
			method:'frappe.desk.form.assign_to.remove',
			args: {
				doctype: me.frm.doctype,
				name: me.frm.docname,
				assign_to: owner
			},
			callback:function(r,rt) {
				me.render(r.message);
			}
		});
	}
});

frappe.ui.form.AssignToDialog = Class.extend({
	init: function(opts){
		$.extend(this, opts);

		this.make();
		this.set_description_from_doc();
	},
	make: function() {
		let me = this;

		me.dialog = new frappe.ui.Dialog({
			title: __('Add to ToDo'),
			fields: me.get_fields(),
			primary_action_label: __("Add"),
			primary_action: function() {
				let args = me.dialog.get_values();

				if (args && args.assign_to) {
					me.dialog.set_message("Assigning...");

					frappe.call({
						method: me.method,
						args: $.extend(args, {
							doctype: me.doctype,
							name: me.docname,
							assign_to: args.assign_to,
							bulk_assign: me.bulk_assign || false,
							re_assign: me.re_assign || false
						}),
						btn: me.dialog.get_primary_btn(),
						callback: function(r) {
							if (!r.exc) {
								if (me.callback) {
									me.callback(r);
								}
								me.dialog && me.dialog.hide();
							} else {
								me.dialog.clear_message();
							}
						},
					});
				}
			},
		});
	},
	assign_to_me: function() {
		let me = this;
		let assign_to = [];

		if (me.dialog.get_value("assign_to_me")) {
			assign_to.push(frappe.session.user);
		}

		me.dialog.set_value("assign_to", assign_to);
	},
	set_description_from_doc: function() {
		let me = this;

		if (me.frm && me.frm.meta.title_field) {
			me.dialog.set_value("description", me.frm.doc[me.frm.meta.title_field]);
		}
	},
	get_fields: function() {
		let me = this;

		return [
			{
				fieldtype: 'MultiSelectPills',
				fieldname: 'assign_to',
				label: __("Assign To"),
				reqd: true,
				get_data: function(txt) {
					return frappe.db.get_link_options("User", txt, {user_type: "System User", enabled: 1});
				}
			},
			{
				label: __("Assign to me"),
				fieldtype: 'Check',
				fieldname: 'assign_to_me',
				default: 0,
				onchange: () => me.assign_to_me()
			},
			{
				label: __("Comment"),
				fieldtype: 'Small Text',
				fieldname: 'description'
			},
			{
				fieldtype: 'Section Break'
			},
			{
				fieldtype: 'Column Break'
			},
			{
				label: __("Complete By"),
				fieldtype: 'Date',
				fieldname: 'date'
			},
			{
				fieldtype: 'Column Break'
			},
			{
				label: __("Priority"),
				fieldtype: 'Select',
				fieldname: 'priority',
				options: [
					{
						value: 'Low',
						label: __('Low')
					},
					{
						value: 'Medium',
						label: __('Medium')
					},
					{
						value: 'High',
						label: __('High')
					}
				],
				// Pick up priority from the source document, if it exists and is available in ToDo
				default: ["Low", "Medium", "High"].includes(me.frm && me.frm.doc.priority ? me.frm.doc.priority : 'Medium')
			}
		];
	}
});
<commit_msg>feat: Init Assignment Dialog [WIP]<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.ui.form.AssignTo = Class.extend({
	init: function(opts) {
		$.extend(this, opts);
		this.btn = this.parent.find(".add-assignment-btn > button").on("click", () => this.add());
		this.btn_wrapper = this.btn.parent();

		this.refresh();
	},
	refresh: function() {
		if(this.frm.doc.__islocal) {
			this.parent.toggle(false);
			return;
		}
		this.parent.toggle(true);
		this.render(this.frm.get_docinfo().assignments);
	},
	render: function(assignments) {
		this.frm.get_docinfo().assignments = assignments;
		this.parent.find(".assignment-row").remove();

		if (this.primary_action) {
			this.primary_action.remove();
			this.primary_action = null;
		}

		if (this.dialog) {
			this.dialog.hide();
		}

		let add_assignment_button = this.parent.find('.add-assignment-btn');

		assignments.forEach(assignment => {
			let user_info = frappe.user_info(assignment.owner);
			user_info.assign_to_name = assignment.name;
			user_info.owner = assignment.owner;
			user_info.avatar = frappe.avatar(assignment.owner);
			user_info.description = assignment.description || "";

			this.get_assignment_block(user_info).insertBefore(add_assignment_button);
			if (assignment.owner === frappe.session.user) {
				this.primary_action = this.frm.page.add_menu_item(__("Assignment Complete"), () => {
					this.remove(frappe.session.user);
				}, "fa fa-check", "btn-success");
			}
		});

	},
	get_assignment_block(assignee_info) {
		let remove_action = false;
		if (assignee_info.owner === frappe.session.user || this.frm.perm[0].write) {
			remove_action = this.remove.bind(this);
		}
		return $(`<li class="assignment-row">`)
			.append(frappe.get_data_pill(assignee_info.owner, assignee_info.owner, remove_action));
	},
	add: function() {
		var me = this;

		if(this.frm.is_new()) {
			frappe.throw(__("Please save the document before assignment"));
			return;
		}

		if(!me.assign_to) {
			me.assign_to = new frappe.ui.form.AssignToDialog({
				method: "frappe.desk.form.assign_to.add",
				doctype: me.frm.doctype,
				docname: me.frm.docname,
				frm: me.frm,
				callback: function (r) {
					me.render(r.message);
				}
			});
		}
		me.assign_to.dialog.clear();
		me.assign_to.dialog.show();
	},
	remove: function(owner) {
		var me = this;

		if(this.frm.is_new()) {
			frappe.throw(__("Please save the document before removing assignment"));
			return;
		}

		frappe.call({
			method:'frappe.desk.form.assign_to.remove',
			args: {
				doctype: me.frm.doctype,
				name: me.frm.docname,
				assign_to: owner
			},
			callback:function(r,rt) {
				me.render(r.message);
			}
		});
	}
});

frappe.ui.form.AssignToDialog = Class.extend({
	init: function(opts){
		$.extend(this, opts);

		this.make();
		this.set_description_from_doc();
	},
	make: function() {
		let me = this;

		me.dialog = new frappe.ui.Dialog({
			title: __('Add to ToDo'),
			fields: me.get_fields(),
			primary_action_label: __("Add"),
			primary_action: function() {
				let args = me.dialog.get_values();

				if (args && args.assign_to) {
					me.dialog.set_message("Assigning...");

					frappe.call({
						method: me.method,
						args: $.extend(args, {
							doctype: me.doctype,
							name: me.docname,
							assign_to: args.assign_to,
							bulk_assign: me.bulk_assign || false,
							re_assign: me.re_assign || false
						}),
						btn: me.dialog.get_primary_btn(),
						callback: function(r) {
							if (!r.exc) {
								if (me.callback) {
									me.callback(r);
								}
								me.dialog && me.dialog.hide();
							} else {
								me.dialog.clear_message();
							}
						},
					});
				}
			},
		});
	},
	assign_to_me: function() {
		let me = this;
		let assign_to = [];

		if (me.dialog.get_value("assign_to_me")) {
			assign_to.push(frappe.session.user);
		}

		me.dialog.set_value("assign_to", assign_to);
	},
	set_description_from_doc: function() {
		let me = this;

		if (me.frm && me.frm.meta.title_field) {
			me.dialog.set_value("description", me.frm.doc[me.frm.meta.title_field]);
		}
	},
	get_fields: function() {
		let me = this;

		return [
			{
				fieldtype: 'MultiSelectPills',
				fieldname: 'assign_to',
				label: __("Assign To"),
				reqd: true,
				get_data: function(txt) {
					return frappe.db.get_link_options("User", txt, {user_type: "System User", enabled: 1});
				}
			},
			{
				label: __("Assign to me"),
				fieldtype: 'Check',
				fieldname: 'assign_to_me',
				default: 0,
				onchange: () => me.assign_to_me()
			},
			{
				label: __("Comment"),
				fieldtype: 'Small Text',
				fieldname: 'description'
			},
			{
				fieldtype: 'Section Break'
			},
			{
				fieldtype: 'Column Break'
			},
			{
				label: __("Complete By"),
				fieldtype: 'Date',
				fieldname: 'date'
			},
			{
				fieldtype: 'Column Break'
			},
			{
				label: __("Priority"),
				fieldtype: 'Select',
				fieldname: 'priority',
				options: [
					{
						value: 'Low',
						label: __('Low')
					},
					{
						value: 'Medium',
						label: __('Medium')
					},
					{
						value: 'High',
						label: __('High')
					}
				],
				// Pick up priority from the source document, if it exists and is available in ToDo
				default: ["Low", "Medium", "High"].includes(me.frm && me.frm.doc.priority ? me.frm.doc.priority : 'Medium')
			}
		];
	}
});

frappe.ui.form.AssignmentDialog = class {
	constructor(opts) {
		// this.frm = opts.frm;
		this.assignments = opts.assignments;
		this.make();
	}

	make() {
		this.dialog = new frappe.ui.Dialog({
			title: __('Assign Users'),
			fields: [{
				'fieldtype': 'Link',
				'fieldname': 'selected_user',
				'options': 'User',
				'label': 'User',
				'change': () => {
					let user = this.dialog.get_value('selected_user');
					if (user && user !== '') {
						this.update_assignment(user);
						this.dialog.set_value('selected_user', null);
					}
				}
			}, {
				'fieldtype': 'HTML',
				'fieldname': 'assignment_list'
			}]
		});

		this.assignment_list = $(this.dialog.get_field('assignment_list').wrapper);

		this.assignments.forEach(assignment => {
			this.update_assignment(assignment);
		});
		this.dialog.show();
	}
	update_assignment(assignment) {
		this.assignment_list.append(this.get_assignment_row(assignment));
	}
	get_assignment_row(assignment) {
		let row = $(`

					${frappe.avatar(assignment)}
					${frappe.user.full_name(assignment)}

					${frappe.utils.icon('close')}

		`);
		row.find('.remove-btn').click(() => {
			row.remove();
		});
		return row;
	}
};<|endoftext|>


<commit_before>// A reference configuration file.
exports.config = {
  // ----- How to setup Selenium -----
  //
  // There are three ways to specify how to use Selenium. Specify one of the
  // following:
  //
  // 1. seleniumServerJar - to start Selenium Standalone locally.
  // 2. seleniumAddress - to connect to a Selenium server which is already
  //    running.
  // 3. sauceUser/sauceKey - to use remote Selenium servers via SauceLabs.
  //
  // If the chromeOnly option is specified, no Selenium server will be started,
  // and chromeDriver will be used directly (from the location specified in
  // chromeDriver)

  // The location of the selenium standalone server .jar file, relative
  // to the location of this config. If no other method of starting selenium
  // is found, this will default to
  // node_modules/protractor/selenium/selenium-server...
  seleniumServerJar: null,
  // The port to start the selenium server on, or null if the server should
  // find its own unused port.
  seleniumPort: null,
  // Chromedriver location is used to help the selenium standalone server
  // find chromedriver. This will be passed to the selenium jar as
  // the system property webdriver.chrome.driver. If null, selenium will
  // attempt to find chromedriver using PATH.
  // chromeDriver: '/usr/local/lib/node_modules/protractor/selenium/chromedriver',
  // If true, only chromedriver will be started, not a standalone selenium.
  // Tests for browsers other than chrome will not run.
  chromeOnly: false,
  // Additional command line options to pass to selenium. For example,
  // if you need to change the browser timeout, use
  // seleniumArgs: ['-browserTimeout=60'],
  seleniumArgs: [],

  // If sauceUser and sauceKey are specified, seleniumServerJar will be ignored.
  // The tests will be run remotely using SauceLabs.
  sauceUser: null,
  sauceKey: null,

  // The address of a running selenium server. If specified, Protractor will
  // connect to an already running instance of selenium. This usually looks like

  // Depends on grunt-protractor-webdriver (default setting for selenium server)
  seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
  // seleniumAddress: null,

  // The timeout for each script run on the browser. This should be longer
  // than the maximum time your application needs to stabilize between tasks.
  allScriptsTimeout: 110000,

  // ----- What tests to run -----
  //
  // Spec patterns are relative to the location of this config.
  specs: [
    // No data in ALIEN at this point, only default admin user should exist.
    'e2e/setup-scenario/before-all.js',
    'e2e/scenarios/common/*.js',
    'e2e/scenarios/components/*.js',
    'e2e/scenarios/admin/plugins.js',
    'e2e/scenarios/security/*.js',
    'e2e/scenarios/topology_templates/*.js',
    'e2e/scenarios/application/*.js',
    'e2e/scenarios/application_topology/*.js',
    'e2e/scenarios/deployment/*/js'
  ],

  // Patterns to exclude.
  exclude: [],

  // ----- Capabilities to be passed to the webdriver instance ----
  //
  // For a full list of available capabilities, see
  // https://code.google.com/p/selenium/wiki/DesiredCapabilities
  // and
  // https://code.google.com/p/selenium/source/browse/javascript/webdriver/capabilities.js
  capabilities: {
    'browserName': 'chrome',
    'chromeOptions': {
      'args': ['--no-sandbox']
    }
  },

  // ----- More information for your tests ----
  //
  // A base URL for your application under test. Calls to protractor.get()
  // with relative paths will be prepended with this.
  // Depends on the cargo maven configuration
  baseUrl: 'http://localhost:8088/',

  // Selector for the element housing the angular app - this defaults to
  // body, but is necessary if ng-app is on a descendant of <body>
  rootElement: 'body',

  // A callback function called once protractor is ready and available, and
  // before the specs are executed
  // You can specify a file containing code to run by setting onPrepare to
  // the filename string.
  onPrepare: function() {
    // At this point, global 'protractor' object will be set up, and jasmine
    // will be available. For example, you can add a Jasmine reporter with:
    require('jasmine-reporters');
    jasmine.getEnv().addReporter(new jasmine.JUnitXmlReporter('outputdir/', true, true));
  },

  // ----- The test framework -----
  //
  // Jasmine is fully supported as a test and assertion framework.
  framework: 'jasmine',

  // ----- Options to be passed to minijasminenode -----
  //
  // See the full list at https://github.com/juliemr/minijasminenode
  jasmineNodeOpts: {
    // onComplete will be called just before the driver quits.
    onComplete: null,
    // If true, display spec names.
    isVerbose: true,
    // If true, print colors to the terminal.
    showColors: true,
    // If true, include stack traces in failures.
    includeStackTrace: true,
    // Default time to wait in ms before a test fails.
    defaultTimeoutInterval: 110000
  },

  // ----- The cleanup step -----
  //
  // A callback function called once the tests have finished running and
  // the webdriver instance has been shut down. It is passed the exit code
  // (0 if the tests passed or 1 if not).
  onCleanUp: function() {}
};
<commit_msg>increase jasmine timeout since operations take more and more time ...<commit_after>// A reference configuration file.
exports.config = {
  // ----- How to setup Selenium -----
  //
  // There are three ways to specify how to use Selenium. Specify one of the
  // following:
  //
  // 1. seleniumServerJar - to start Selenium Standalone locally.
  // 2. seleniumAddress - to connect to a Selenium server which is already
  //    running.
  // 3. sauceUser/sauceKey - to use remote Selenium servers via SauceLabs.
  //
  // If the chromeOnly option is specified, no Selenium server will be started,
  // and chromeDriver will be used directly (from the location specified in
  // chromeDriver)

  // The location of the selenium standalone server .jar file, relative
  // to the location of this config. If no other method of starting selenium
  // is found, this will default to
  // node_modules/protractor/selenium/selenium-server...
  seleniumServerJar: null,
  // The port to start the selenium server on, or null if the server should
  // find its own unused port.
  seleniumPort: null,
  // Chromedriver location is used to help the selenium standalone server
  // find chromedriver. This will be passed to the selenium jar as
  // the system property webdriver.chrome.driver. If null, selenium will
  // attempt to find chromedriver using PATH.
  // chromeDriver: '/usr/local/lib/node_modules/protractor/selenium/chromedriver',
  // If true, only chromedriver will be started, not a standalone selenium.
  // Tests for browsers other than chrome will not run.
  chromeOnly: false,
  // Additional command line options to pass to selenium. For example,
  // if you need to change the browser timeout, use
  // seleniumArgs: ['-browserTimeout=60'],
  seleniumArgs: [],

  // If sauceUser and sauceKey are specified, seleniumServerJar will be ignored.
  // The tests will be run remotely using SauceLabs.
  sauceUser: null,
  sauceKey: null,

  // The address of a running selenium server. If specified, Protractor will
  // connect to an already running instance of selenium. This usually looks like

  // Depends on grunt-protractor-webdriver (default setting for selenium server)
  seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
  // seleniumAddress: null,

  // The timeout for each script run on the browser. This should be longer
  // than the maximum time your application needs to stabilize between tasks.
  allScriptsTimeout: 110000,

  // ----- What tests to run -----
  //
  // Spec patterns are relative to the location of this config.
  specs: [
    // No data in ALIEN at this point, only default admin user should exist.
    'e2e/setup-scenario/before-all.js',
    'e2e/scenarios/common/*.js',
    'e2e/scenarios/components/*.js',
    'e2e/scenarios/admin/plugins.js',
    'e2e/scenarios/security/*.js',
    'e2e/scenarios/topology_templates/*.js',
    'e2e/scenarios/application/*.js',
    'e2e/scenarios/application_topology/*.js',
    'e2e/scenarios/deployment/*/js'
  ],

  // Patterns to exclude.
  exclude: [],

  // ----- Capabilities to be passed to the webdriver instance ----
  //
  // For a full list of available capabilities, see
  // https://code.google.com/p/selenium/wiki/DesiredCapabilities
  // and
  // https://code.google.com/p/selenium/source/browse/javascript/webdriver/capabilities.js
  capabilities: {
    'browserName': 'chrome',
    'chromeOptions': {
      'args': ['--no-sandbox']
    }
  },

  // ----- More information for your tests ----
  //
  // A base URL for your application under test. Calls to protractor.get()
  // with relative paths will be prepended with this.
  // Depends on the cargo maven configuration
  baseUrl: 'http://localhost:8088/',

  // Selector for the element housing the angular app - this defaults to
  // body, but is necessary if ng-app is on a descendant of <body>
  rootElement: 'body',

  // A callback function called once protractor is ready and available, and
  // before the specs are executed
  // You can specify a file containing code to run by setting onPrepare to
  // the filename string.
  onPrepare: function() {
    // At this point, global 'protractor' object will be set up, and jasmine
    // will be available. For example, you can add a Jasmine reporter with:
    require('jasmine-reporters');
    jasmine.getEnv().addReporter(new jasmine.JUnitXmlReporter('outputdir/', true, true));
  },

  // ----- The test framework -----
  //
  // Jasmine is fully supported as a test and assertion framework.
  framework: 'jasmine',

  // ----- Options to be passed to minijasminenode -----
  //
  // See the full list at https://github.com/juliemr/minijasminenode
  jasmineNodeOpts: {
    // onComplete will be called just before the driver quits.
    onComplete: null,
    // If true, display spec names.
    isVerbose: true,
    // If true, print colors to the terminal.
    showColors: true,
    // If true, include stack traces in failures.
    includeStackTrace: true,
    // Default time to wait in ms before a test fails.
    defaultTimeoutInterval: 220000
  },

  // ----- The cleanup step -----
  //
  // A callback function called once the tests have finished running and
  // the webdriver instance has been shut down. It is passed the exit code
  // (0 if the tests passed or 1 if not).
  onCleanUp: function() {}
};
<|endoftext|>


<commit_before>import { or } from '@ember/object/computed';
import { computed } from '@ember/object';
import { inject as service } from '@ember/service';
import Controller from '@ember/controller';
import utils from 'vault/lib/key-utils';
import BackendCrumbMixin from 'vault/mixins/backend-crumb';
import WithNavToNearestAncestor from 'vault/mixins/with-nav-to-nearest-ancestor';
import ListController from 'core/mixins/list-controller';

export default Controller.extend(ListController, BackendCrumbMixin, WithNavToNearestAncestor, {
  flashMessages: service(),
  queryParams: ['page', 'pageFilter', 'tab'],

  tab: '',

  filterIsFolder: computed('filter', function () {
    return !!utils.keyIsFolder(this.filter);
  }),

  isConfigurableTab: or('isCertTab', 'isConfigure'),

  actions: {
    chooseAction(action) {
      this.set('selectedAction', action);
    },

    toggleZeroAddress(item, backend) {
      item.toggleProperty('zeroAddress');
      this.set('loading-' + item.id, true);
      backend
        .saveZeroAddressConfig()
        .catch((e) => {
          item.set('zeroAddress', false);
          this.flashMessages.danger(e.message);
        })
        .finally(() => {
          this.set('loading-' + item.id, false);
        });
    },

    delete(item, type) {
      const name = item.id;
      item.destroyRecord().then(() => {
        this.flashMessages.success(`${name} was successfully deleted.`);
        this.send('reload');
        if (type === 'secret') {
          this.navToNearestAncestor.perform(name);
        }
      });
    },
  },
});
<commit_msg>fixes issue with error being swallowed from secrets backend list item delete (#15975)<commit_after>import { or } from '@ember/object/computed';
import { computed } from '@ember/object';
import { inject as service } from '@ember/service';
import Controller from '@ember/controller';
import utils from 'vault/lib/key-utils';
import BackendCrumbMixin from 'vault/mixins/backend-crumb';
import WithNavToNearestAncestor from 'vault/mixins/with-nav-to-nearest-ancestor';
import ListController from 'core/mixins/list-controller';

export default Controller.extend(ListController, BackendCrumbMixin, WithNavToNearestAncestor, {
  flashMessages: service(),
  queryParams: ['page', 'pageFilter', 'tab'],

  tab: '',

  filterIsFolder: computed('filter', function () {
    return !!utils.keyIsFolder(this.filter);
  }),

  isConfigurableTab: or('isCertTab', 'isConfigure'),

  actions: {
    chooseAction(action) {
      this.set('selectedAction', action);
    },

    toggleZeroAddress(item, backend) {
      item.toggleProperty('zeroAddress');
      this.set('loading-' + item.id, true);
      backend
        .saveZeroAddressConfig()
        .catch((e) => {
          item.set('zeroAddress', false);
          this.flashMessages.danger(e.message);
        })
        .finally(() => {
          this.set('loading-' + item.id, false);
        });
    },

    delete(item, type) {
      const name = item.id;
      item
        .destroyRecord()
        .then(() => {
          this.flashMessages.success(`${name} was successfully deleted.`);
          this.send('reload');
          if (type === 'secret') {
            this.navToNearestAncestor.perform(name);
          }
        })
        .catch((e) => {
          const error = e.errors ? e.errors.join('. ') : e.message;
          this.flashMessages.danger(error);
        });
    },
  },
});
<|endoftext|>


<commit_before>/*
 * This file is part of Invenio.
 * Copyright (C) 2013, 2014 CERN.
 *
 * Invenio is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * Invenio is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Invenio; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 */

define(function(require, exports, module) {
    "use strict";

    var $ = require('jquery'),
        Hogan = require('hogan')

    // provides $.fn.sortable
    require('ui/sortable')

  /**
   * Constructor.
   *
   * @param element DOM element/jQuery selector on which the plugin will
   *   be applied
   * @param options options dictionary
   * @constructor
   */
  function DynamicFieldList(element, options) {

    // ensure that there is jQuery selector available
    this.$element = $(element);
    // DOM element
    this.element = this.$element[0];
    this.options = $.extend({}, $.fn.dynamicFieldList.defaults, options);

    if (this.options.prefix === null) {
      this.options.prefix = this.$element.attr('id');
    }
    this.$template = this.$element.find('.' + this.options.empty_cssclass);
    this.last_index = $("#" + this.options.prefix + this.options.sep + this.options.last_index);
    this.field_regex = new RegExp(
      "(" + this.options.prefix + this.options.sep + "(\\d+|" +
        this.options.index_suffix + "))" + this.options.sep + "(.+)"
    );
    // Get template name from options or the empty elements data attribute
    this.tag_template = Hogan.compile(this.$element.data('tagTemplate') || '');

  }

  DynamicFieldList.prototype = {

    /**
     * Here initialization stuff. Especially the one which needs the plugin
     * to be already applied.
     */
    init: function () {

      // Make list sortable
      if (this.options.sortable) {
        var sortable_options = {
          items: "." + this.options.element_css_class,
          update: this.sort_element,
        };

        if (this.$element.find("." + this.options.sort_cssclass).length !== 0) {
          sortable_options.handle = "." + this.options.sort_cssclass;
        }
        this.$element.sortable(sortable_options);
      }
    },

    /**
     * Connecting events to functions, separated just to have them in one
     * place.
     */
    connectEvents: function () {

      // to have access to the class inside the events
      var that = this;

      // Hook add/remove buttons on already rendered elements
      $('#' + this.options.prefix + " ." + this.options.element_css_class + " ." + this.options.remove_cssclass)
        .click(function (event) {
          that.remove_element($(this), event);
        });
      $('#' + this.options.prefix + " ." + this.options.add_cssclass)
        .click(function (event) {
          that.append_element();
        });

      // Hook for detecting on paste events
      if (this.options.on_paste !== null && this.options.on_paste_elements !== null) {
        this.options.on_paste = this.create_paste_handler(that.options.on_paste);
        $('#' + this.options.prefix + " " + this.options.on_paste_elements).on('paste', function (event) {
          that.on_paste(event);
        });
      }
    },

    /**
     * Get next index
     */
    get_next_index: function () {
      return parseInt(this.last_index.val(), 10) + 1;
    },

    /**
     * Set value of last index
     */
    set_last_index: function (idx) {
      return this.last_index.val(idx);
    },

    /**
     * Update attributes in a single tag
     */
    update_attr_index: function (tag, idx) {
      var id_regex = new RegExp("(" + this.options.prefix + this.options.sep + "(\\d+|" + this.options.index_suffix + "))");
      var new_id = this.options.prefix + this.options.sep + idx;
      ['for', 'id', 'name'].forEach(function(attr_name){
        if($(tag).attr(attr_name)){
          $(tag).attr(attr_name, $(tag).attr(attr_name).replace(id_regex, new_id));
        }
      });
    },

    /**
     * Update index in attributes for a single element (i.e all tags inside
     * element)
     */
    update_element_index: function (element, idx) {
      this.update_attr_index(element, idx);
      var that = this;
      $(element).find('*').each(function(){
        that.update_attr_index(this, idx);
      });
    },

    /**
     * Update indexes of all elements
     */
    update_elements_indexes: function () {
      // Update elements indexes of all other elements
      var all_elements = $('#' + this.options.prefix + " ." + this.options.element_css_class);
      var num_elements = all_elements.length;
      for (var i=0; i<num_elements; i++) {
        this.update_element_index(all_elements[i], i);
      }
      this.set_last_index(num_elements - 1);
    },

    /**
     * Update values of fields for an element
     */
    update_element_values: function (root, data, field_prefix_index, selector_prefix) {
      var field_prefix, newdata;

      if(selector_prefix ===undefined){
        selector_prefix = '#' + this.options.prefix + this.options.sep + this.options.index_suffix + this.options.sep;
      }

      if(field_prefix_index === undefined){
        field_prefix = this.options.prefix + this.options.sep + this.options.index_suffix + this.options.sep;
      } else {
        field_prefix = this.options.prefix + this.options.sep + field_prefix_index + this.options.sep;
      }
      if(root === null) {
        root = $(document);
      }

      //Update field values if data exists
      if(data !== null && data !== undefined){
        // Remove prefix from field name
        newdata = {};
        if (typeof data == 'object'){
          for(var field in data) {
            if(field.indexOf(field_prefix) === 0){
              newdata[field.slice(field_prefix.length)] = data[field];
            } else {
              newdata[field] = data[field];
            }
          }
          // Update value for each field.
          $.each(newdata, function(field, value){
            var input = root.find(selector_prefix+field);
            if(input.length !== 0) {
              input.val(value);
            }
          });
        } else {
          newdata.value = data;
          var input = root.find('#' + this.options.prefix + this.options.sep + this.options.index_suffix);
          if(input.length !== 0) {
            // Keep old value
            input.val(input.val()+data);
          }
        }

        root.find("." + this.options.tag_title_cssclass).html(
          this.tag_template.render(newdata)
        );
      }
    },

    get_field_name: function (name_or_id) {
      var result = this.field_regex.exec(name_or_id);
      if(result !== null){
        return result[3];
      }
      return null;
    },

    get_field_prefix: function (name_or_id) {
      var result = this.field_regex.exec(name_or_id);
      if(result !== null){
        return result[1];
      }
      return null;
    },

    /**
     * Handler for remove element events
     */
    remove_element: function ($element, e) {
      //
      // Delete action
      //
      e.preventDefault();

      // Find and remove element
      var old_element = $element.parents("." + this.options.element_css_class);
      var that = this;
      old_element.hide('fast', function(){
        // Give hide animation time to complete
        old_element.remove();
        that.update_elements_indexes();

        // Callback
        if (that.options.removed) {
          that.options.removed(that.options, old_element);
        }
      });
    },

    /**
     * Handler for sort element events
     */
    sort_element: function (e, ui) {
      this.update_elements_indexes();
      // Callback
      if (this.options.updated) {
        this.options.updated(this.options, ui.item);
      }
    },

    update_element: function (data, idx) {
      //
      // Update action
      //

      // Update elements indexes of all other elements
      var all_elements = $('#' + this.options.prefix + " ." + this.options.element_css_class);
      var num_elements = all_elements.length;
      if (idx < num_elements){
        this.element = $(all_elements[idx]);
        this.update_element_values(this.$element, data, idx, '#' + this.options.prefix + this.options.sep + idx + this.options.sep);
      }
    },

    /**
     * Handler for add new element events
     */
    append_element: function (data, field_prefix_index) {
      //
      // Append action
      //
      var new_element = this.$template.clone();
      var next_index = this.get_next_index();
      // Remove class
      new_element.removeClass(this.options.empty_cssclass);
      new_element.addClass(this.options.element_css_class);
      // Pre-populate field values
      this.update_element_values(new_element, data, field_prefix_index);
      // Update ids
      this.update_element_index(new_element, next_index);
      // Insert before template element
      new_element.hide();
      new_element.insertBefore(this.$template);
      new_element.show('fast');
      // Update last_index
      this.set_last_index(next_index);
      var that = this;
      // Add delete button handler
      new_element.find('.' + this.options.remove_cssclass).click(function (event) {
        that.remove_element($(this), event);
      });
      // Add paste handler for some fields
      if (this.options.on_paste !== null && this.options.on_paste_elements !== null) {
        new_element.find(this.options.on_paste_elements).on('paste', function (event) {
          that.on_paste(event);
        });
      }
      // Callback
      if (this.options.added) {
        this.options.added(this.options, new_element);
      }
    },

    /**
     * On paste event handler, wrapping the user-defined paste handler to
     * for ease of use.
     */
    on_paste: function (e) {
      var element = $(e.target);
      var root_element = element.parents("." + this.options.element_css_class);
      var data = e.originalEvent.clipboardData.getData("text/plain");
      var field_name = this.get_field_name(element.attr("id"));
      var prefix = "#" + this.get_field_prefix(element.attr("id")) + this.options.sep;

      if (this.options.on_paste !== null && data !== null) {
        if (this.options.on_paste(root_element, element, prefix, field_name, data, this.append_element)) {
          e.preventDefault();
        }
      }
    },

    /**
     * Factory method for creating on paste event handlers. Allow handlers to
     * only care about splitting string into data elements.
     */
    create_paste_handler: function (splitter) {
      var on_paste_handler = function(root_element, element, selector_prefix, field, clipboard_data, append_element){
        var elements_values = splitter(field, clipboard_data);
        var that = this;
        if(elements_values.length > 0) {
          $.each(elements_values, function(idx, clipboard_data){
            if(idx === 0) {
              that.update_element_values(root_element, clipboard_data, undefined, selector_prefix);
            } else {
              that.append_element(clipboard_data);
            }
          });
          // Callback
          if (this.options.pasted) {
            this.options.pasted(this.options);
          }
          return true;
        } else {
          return false;
        }
      };

      return on_paste_handler;
    }

  }

  $.fn.dynamicFieldList = function (option) {

    var $elements = this;
    var dataLabel = 'dynamic-field-list';

    return $elements.map(function (idx, element) {
      var $element = $(element);
      var object = $element.data(dataLabel)
      var options = typeof option == 'object' && option;
      // attach jQuery plugin
      if (!object) {
        object = new DynamicFieldList($element, options)
        $element.data(dataLabel, object)
        object.init();
        object.connectEvents();
      }
      return object;
    });
  };

  $.fn.dynamicFieldList.defaults = {
    prefix: null,
    sep: '-',
    last_index: "__last_index__",
    index_suffix: "__index__",
    empty_cssclass: "empty-element",
    element_css_class: "field-list-element",
    remove_cssclass: "remove-element",
    add_cssclass: "add-element",
    sort_cssclass: "sort-element",
    tag_title_cssclass: "tag-title",
    added: null,
    removed: null,
    updated: null,
    pasted: null,
    on_paste_elements: "input",
    on_paste: null, //paste_newline_splitter,
    sortable: true,
    js_template: null,
  };

})
<commit_msg>deposit: fix for sort function for authors<commit_after>/*
 * This file is part of Invenio.
 * Copyright (C) 2013, 2014 CERN.
 *
 * Invenio is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * Invenio is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Invenio; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 */

define(function(require, exports, module) {
    "use strict";

    var $ = require('jquery'),
        Hogan = require('hogan')

    // provides $.fn.sortable
    require('ui/sortable')

  /**
   * Constructor.
   *
   * @param element DOM element/jQuery selector on which the plugin will
   *   be applied
   * @param options options dictionary
   * @constructor
   */
  function DynamicFieldList(element, options) {

    // ensure that there is jQuery selector available
    this.$element = $(element);
    // DOM element
    this.element = this.$element[0];
    this.options = $.extend({}, $.fn.dynamicFieldList.defaults, options);

    if (this.options.prefix === null) {
      this.options.prefix = this.$element.attr('id');
    }
    this.$template = this.$element.find('.' + this.options.empty_cssclass);
    this.last_index = $("#" + this.options.prefix + this.options.sep + this.options.last_index);
    this.field_regex = new RegExp(
      "(" + this.options.prefix + this.options.sep + "(\\d+|" +
        this.options.index_suffix + "))" + this.options.sep + "(.+)"
    );
    // Get template name from options or the empty elements data attribute
    this.tag_template = Hogan.compile(this.$element.data('tagTemplate') || '');

  }

  DynamicFieldList.prototype = {

    /**
     * Here initialization stuff. Especially the one which needs the plugin
     * to be already applied.
     */
    init: function () {

      var that = this;

      // Make list sortable
      if (this.options.sortable) {
        var sortable_options = {
          items: "." + this.options.element_css_class,
          update: function(e, ui) {
            that.sort_element(e, ui);
          }
        };

        if (this.$element.find("." + this.options.sort_cssclass).length !== 0) {
          sortable_options.handle = "." + this.options.sort_cssclass;
        }
        this.$element.sortable(sortable_options);
      }
    },

    /**
     * Connecting events to functions, separated just to have them in one
     * place.
     */
    connectEvents: function () {

      // to have access to the class inside the events
      var that = this;

      // Hook add/remove buttons on already rendered elements
      $('#' + this.options.prefix + " ." + this.options.element_css_class + " ." + this.options.remove_cssclass)
        .click(function (event) {
          that.remove_element($(this), event);
        });
      $('#' + this.options.prefix + " ." + this.options.add_cssclass)
        .click(function (event) {
          that.append_element();
        });

      // Hook for detecting on paste events
      if (this.options.on_paste !== null && this.options.on_paste_elements !== null) {
        this.options.on_paste = this.create_paste_handler(that.options.on_paste);
        $('#' + this.options.prefix + " " + this.options.on_paste_elements).on('paste', function (event) {
          that.on_paste(event);
        });
      }
    },

    /**
     * Get next index
     */
    get_next_index: function () {
      return parseInt(this.last_index.val(), 10) + 1;
    },

    /**
     * Set value of last index
     */
    set_last_index: function (idx) {
      return this.last_index.val(idx);
    },

    /**
     * Update attributes in a single tag
     */
    update_attr_index: function (tag, idx) {
      var id_regex = new RegExp("(" + this.options.prefix + this.options.sep + "(\\d+|" + this.options.index_suffix + "))");
      var new_id = this.options.prefix + this.options.sep + idx;
      ['for', 'id', 'name'].forEach(function(attr_name){
        if($(tag).attr(attr_name)){
          $(tag).attr(attr_name, $(tag).attr(attr_name).replace(id_regex, new_id));
        }
      });
    },

    /**
     * Update index in attributes for a single element (i.e all tags inside
     * element)
     */
    update_element_index: function (element, idx) {
      this.update_attr_index(element, idx);
      var that = this;
      $(element).find('*').each(function(){
        that.update_attr_index(this, idx);
      });
    },

    /**
     * Update indexes of all elements
     */
    update_elements_indexes: function () {
      // Update elements indexes of all other elements
      var all_elements = $('#' + this.options.prefix + " ." + this.options.element_css_class);
      var num_elements = all_elements.length;
      for (var i=0; i<num_elements; i++) {
        this.update_element_index(all_elements[i], i);
      }
      this.set_last_index(num_elements - 1);
    },

    /**
     * Update values of fields for an element
     */
    update_element_values: function (root, data, field_prefix_index, selector_prefix) {
      var field_prefix, newdata;

      if(selector_prefix ===undefined){
        selector_prefix = '#' + this.options.prefix + this.options.sep + this.options.index_suffix + this.options.sep;
      }

      if(field_prefix_index === undefined){
        field_prefix = this.options.prefix + this.options.sep + this.options.index_suffix + this.options.sep;
      } else {
        field_prefix = this.options.prefix + this.options.sep + field_prefix_index + this.options.sep;
      }
      if(root === null) {
        root = $(document);
      }

      //Update field values if data exists
      if(data !== null && data !== undefined){
        // Remove prefix from field name
        newdata = {};
        if (typeof data == 'object'){
          for(var field in data) {
            if(field.indexOf(field_prefix) === 0){
              newdata[field.slice(field_prefix.length)] = data[field];
            } else {
              newdata[field] = data[field];
            }
          }
          // Update value for each field.
          $.each(newdata, function(field, value){
            var input = root.find(selector_prefix+field);
            if(input.length !== 0) {
              input.val(value);
            }
          });
        } else {
          newdata.value = data;
          var input = root.find('#' + this.options.prefix + this.options.sep + this.options.index_suffix);
          if(input.length !== 0) {
            // Keep old value
            input.val(input.val()+data);
          }
        }

        root.find("." + this.options.tag_title_cssclass).html(
          this.tag_template.render(newdata)
        );
      }
    },

    get_field_name: function (name_or_id) {
      var result = this.field_regex.exec(name_or_id);
      if(result !== null){
        return result[3];
      }
      return null;
    },

    get_field_prefix: function (name_or_id) {
      var result = this.field_regex.exec(name_or_id);
      if(result !== null){
        return result[1];
      }
      return null;
    },

    /**
     * Handler for remove element events
     */
    remove_element: function ($element, e) {
      //
      // Delete action
      //
      e.preventDefault();

      // Find and remove element
      var old_element = $element.parents("." + this.options.element_css_class);
      var that = this;
      old_element.hide('fast', function(){
        // Give hide animation time to complete
        old_element.remove();
        that.update_elements_indexes();

        // Callback
        if (that.options.removed) {
          that.options.removed(that.options, old_element);
        }
      });
    },

    /**
     * Handler for sort element events
     */
    sort_element: function (e, ui) {
      this.update_elements_indexes();
      // Callback
      if (this.options.updated) {
        this.options.updated(this.options, ui.item);
      }
    },

    update_element: function (data, idx) {
      //
      // Update action
      //

      // Update elements indexes of all other elements
      var all_elements = $('#' + this.options.prefix + " ." + this.options.element_css_class);
      var num_elements = all_elements.length;
      if (idx < num_elements){
        this.element = $(all_elements[idx]);
        this.update_element_values(this.$element, data, idx, '#' + this.options.prefix + this.options.sep + idx + this.options.sep);
      }
    },

    /**
     * Handler for add new element events
     */
    append_element: function (data, field_prefix_index) {
      //
      // Append action
      //
      var new_element = this.$template.clone();
      var next_index = this.get_next_index();
      // Remove class
      new_element.removeClass(this.options.empty_cssclass);
      new_element.addClass(this.options.element_css_class);
      // Pre-populate field values
      this.update_element_values(new_element, data, field_prefix_index);
      // Update ids
      this.update_element_index(new_element, next_index);
      // Insert before template element
      new_element.hide();
      new_element.insertBefore(this.$template);
      new_element.show('fast');
      // Update last_index
      this.set_last_index(next_index);
      var that = this;
      // Add delete button handler
      new_element.find('.' + this.options.remove_cssclass).click(function (event) {
        that.remove_element($(this), event);
      });
      // Add paste handler for some fields
      if (this.options.on_paste !== null && this.options.on_paste_elements !== null) {
        new_element.find(this.options.on_paste_elements).on('paste', function (event) {
          that.on_paste(event);
        });
      }
      // Callback
      if (this.options.added) {
        this.options.added(this.options, new_element);
      }
    },

    /**
     * On paste event handler, wrapping the user-defined paste handler to
     * for ease of use.
     */
    on_paste: function (e) {
      var element = $(e.target);
      var root_element = element.parents("." + this.options.element_css_class);
      var data = e.originalEvent.clipboardData.getData("text/plain");
      var field_name = this.get_field_name(element.attr("id"));
      var prefix = "#" + this.get_field_prefix(element.attr("id")) + this.options.sep;

      if (this.options.on_paste !== null && data !== null) {
        if (this.options.on_paste(root_element, element, prefix, field_name, data, this.append_element)) {
          e.preventDefault();
        }
      }
    },

    /**
     * Factory method for creating on paste event handlers. Allow handlers to
     * only care about splitting string into data elements.
     */
    create_paste_handler: function (splitter) {
      var on_paste_handler = function(root_element, element, selector_prefix, field, clipboard_data, append_element){
        var elements_values = splitter(field, clipboard_data);
        var that = this;
        if(elements_values.length > 0) {
          $.each(elements_values, function(idx, clipboard_data){
            if(idx === 0) {
              that.update_element_values(root_element, clipboard_data, undefined, selector_prefix);
            } else {
              that.append_element(clipboard_data);
            }
          });
          // Callback
          if (this.options.pasted) {
            this.options.pasted(this.options);
          }
          return true;
        } else {
          return false;
        }
      };

      return on_paste_handler;
    }

  }

  $.fn.dynamicFieldList = function (option) {

    var $elements = this;
    var dataLabel = 'dynamic-field-list';

    return $elements.map(function (idx, element) {
      var $element = $(element);
      var object = $element.data(dataLabel)
      var options = typeof option == 'object' && option;
      // attach jQuery plugin
      if (!object) {
        object = new DynamicFieldList($element, options)
        $element.data(dataLabel, object)
        object.init();
        object.connectEvents();
      }
      return object;
    });
  };

  $.fn.dynamicFieldList.defaults = {
    prefix: null,
    sep: '-',
    last_index: "__last_index__",
    index_suffix: "__index__",
    empty_cssclass: "empty-element",
    element_css_class: "field-list-element",
    remove_cssclass: "remove-element",
    add_cssclass: "add-element",
    sort_cssclass: "sort-element",
    tag_title_cssclass: "tag-title",
    added: null,
    removed: null,
    updated: null,
    pasted: null,
    on_paste_elements: "input",
    on_paste: null, //paste_newline_splitter,
    sortable: true,
    js_template: null,
  };

})
<|endoftext|>


<commit_before>var Drone = require('../drone').Drone;
var blocks = require('blocks');

Drone.extend('skyscraper', function( floors ) {
  var i = 0;
  if ( typeof floors == 'undefined' ) {
    floors = 10;
  }
  this.chkpt('skyscraper');
  for ( i = 0; i < floors; i++ ) {
    this          //     w   h  d
      .box( blocks.iron, 20, 1, 20)  // iron floor
      .up()       //           w   h  d
      .box0(blocks.glass_pane, 20, 3, 20) // glass walls
      .up(3);
  }
  return this.move('skyscraper');
});
<commit_msg>Delete skyscraper-example.js<commit_after><|endoftext|>


<commit_before>'use strict'

var fs = require('fs')
var jsdom = require('mocha-jsdom')
var expect = require('chai').expect

describe('Prelodr', function () {
  var Prelodr

  this.timeout(15000)

  jsdom({
    src: fs.readFileSync('src/prelodr.js', 'utf-8')
  })

  before(function () {
    Prelodr = global.window.Prelodr
    document.body.innerHTML = fs.readFileSync('test/test.html', 'utf-8')
  })

  it('class should be initialized successfully.', function () {
    var prelodr = new Prelodr()
    expect(preloadr).to.be.an('object')
  })

  it('show() callback should be called successfully.', function (done) {
    var prelodr = new Prelodr({
      show: function () {
        done()
      }
    })

    prelodr.in('Loading...')
  })

  it('hide() callback should be called successfully.', function (done) {
    var prelodr = new Prelodr({
      hide: function () {
        done()
      }
    })

    prelodr.in('Loading...')

    setTimeout(function () {
      prelodr.out()
    }, 400)
  })

})
<commit_msg>Fix default test<commit_after>'use strict'

var fs = require('fs')
var jsdom = require('mocha-jsdom')
var expect = require('chai').expect

describe('Prelodr', function () {
  var Prelodr

  this.timeout(15000)

  jsdom({
    src: fs.readFileSync('src/prelodr.js', 'utf-8')
  })

  before(function () {
    Prelodr = global.window.Prelodr
    document.body.innerHTML = fs.readFileSync('test/test.html', 'utf-8')
  })

  it('class should be initialized successfully.', function () {
    var prelodr = new Prelodr()
    expect(prelodr).to.be.an('object')
  })

  it('show() callback should be called successfully.', function (done) {
    var prelodr = new Prelodr({
      show: function () {
        done()
      }
    })

    prelodr.in('Loading...')
  })

  it('hide() callback should be called successfully.', function (done) {
    var prelodr = new Prelodr({
      hide: function () {
        done()
      }
    })

    prelodr.in('Loading...')

    setTimeout(function () {
      prelodr.out()
    }, 400)
  })

})
<|endoftext|>


<commit_before>/**
 *  Dashboard filters.
 *
 *  - 'Order by' (time,likes,etc) collection.
 *  - 'Filter by' collection.
 *  - 'Search' any pattern within collection.
 *
 */

var cdb = require('cartodb-editor');

module.exports = cdb.core.View.extend({

  className: 'u-inner',

  events: {

  },

  initialize: function() {
    this.router = this.options.router;
    this.user = this.options.user;
    this.localStorage = this.options.localStorage;
    this.template = cdb.templates.getTemplate('new_dashboard/views/filters');

    this._initBinds();
  },

  render: function() {
    // Content
    this.$el.html(
      this.template(
        _.extend({
            order:  this.localStorage.get('dashboard.order'),
            org:    this.user.isInsideOrg(),
            prefix: cdb.config.prefixUrl()
          },
          this.router.model.attributes
        )
      )
    );

    // Animations?

    return this;
  },

  _initBinds: function() {
    this.router.model.on('change', this.render, this);
  },

  _navigate: function() {

  }

})<commit_msg>new routes for filter view<commit_after>/**
 *  Dashboard filters.
 *
 *  - 'Order by' (time,likes,etc) collection.
 *  - 'Filter by' collection.
 *  - 'Search' any pattern within collection.
 *
 */

var cdb = require('cartodb-editor');

module.exports = cdb.core.View.extend({

  className: 'u-inner',

  events: {
    'click .DashboardFilters-typeLink': '_navigate'
  },

  initialize: function() {
    this.router = this.options.router;
    this.user = this.options.user;
    this.localStorage = this.options.localStorage;
    this.template = cdb.templates.getTemplate('new_dashboard/views/filters');

    this._initBinds();
  },

  render: function() {
    // Content
    this.$el.html(
      this.template(
        _.extend({
            order:  this.localStorage.get('dashboard.order'),
            org:    this.user.isInsideOrg(),
            prefix: cdb.config.prefixUrl()
          },
          this.router.model.attributes
        )
      )
    );

    // Animations?

    return this;
  },

  _initBinds: function() {
    this.router.model.on('change', this.render, this);
  },

  _navigate: function(e) {
    if (e) e.preventDefault();
    var href = $(e.target).attr('href');
    this.router.navigate(href, {trigger: true});
  }

})<|endoftext|>


<commit_before>/**
 * grunt-check-dependencies
 * https://github.com/mzgol/grunt-check-dependencies
 *
 * Author Michał Gołębiowski <m.goleb@gmail.com>
 * Licensed under the MIT license.
 */

'use strict';

var findup = require('findup-sync'),
    _ = require('lodash'),
    path = require('path'),
    semver = require('semver'),
    spawn = require('child_process').spawn;

module.exports = function (grunt) {
    return function checkDependencies(options, done) {
        var mappings,
            validRun = true,
            packageDir = options.packageDir || findup('package.json').replace(/package\.json$/, ''),
            scopeList = options.scopeList || ['peerDependencies', 'dependencies', 'devDependencies'],
            npmInstall = !!options.npmInstall,
            packageJson = grunt.file.readJSON(path.join(packageDir, 'package.json'));

        // Get names of all packages specified in package.json together with specified version numbers.
        mappings = scopeList.reduce(function (result, scope) {
            return _.merge(result, packageJson[scope] || {});
        }, {});

        // Make sure each package is present and matches a required version.
        _(mappings).forEach(function (versionString, name) {
            if (!grunt.file.exists(path.join(packageDir, 'node_modules', name))) {
                grunt.log.error(name + ': ' + 'not installed!'.red);
                validRun = false;
                return;
            }

            // Quick and dirty check - make sure we're dealing with semver, not
            // a URL or a shortcut to the GitHub repo.
            if (/\//.test(versionString)) {
                return;
            }

            var version = grunt.file.readJSON(path.join(packageDir, 'node_modules', name, 'package.json')).version;
            if (!semver.satisfies(version, versionString)) {
                validRun = false;
                grunt.log.error(name + ': installed: ' + version.red + ', expected: ' + versionString.green);
            }

            if (validRun) {
                grunt.verbose.writeln(name + ': installed: ' + version.green + ', expected: ' + versionString.green);
            }
        });

        if (validRun) {
            done(true);
        } else {
            if (!npmInstall) {
                grunt.log.writeln('Invoke ' + 'npm install'.green + ' to install missing packages');
                done(false);
            } else {
                grunt.log.writeln('Invoking ' + 'npm install'.green + '...');
                // execSync errors on non-empty stderr; silent such output.
                spawn('npm', ['install'], {
                    cwd: packageDir || '.',
                    stdio: 'inherit',
                }).on('close', function (code) {
                        if (code !== 0) {
                            grunt.log.error('npm install failed with code: ' + (code + '').red);
                            done(false);
                        } else {
                            done(true);
                        }
                    });
            }
        }
    };
};
<commit_msg>Windows compatibility<commit_after>/**
 * grunt-check-dependencies
 * https://github.com/mzgol/grunt-check-dependencies
 *
 * Author Michał Gołębiowski <m.goleb@gmail.com>
 * Licensed under the MIT license.
 */

'use strict';

var findup = require('findup-sync'),
    _ = require('lodash'),
    path = require('path'),
    semver = require('semver'),
    spawn = require('child_process').spawn;

module.exports = function (grunt) {
    return function checkDependencies(options, done) {
        var mappings,
            win32 = process.platform === 'win32',
            validRun = true,
            packageDir = options.packageDir || findup('package.json').replace(/package\.json$/, ''),
            scopeList = options.scopeList || ['peerDependencies', 'dependencies', 'devDependencies'],
            npmInstall = !!options.npmInstall,
            packageJson = grunt.file.readJSON(path.join(packageDir, 'package.json'));

        // Get names of all packages specified in package.json together with specified version numbers.
        mappings = scopeList.reduce(function (result, scope) {
            return _.merge(result, packageJson[scope] || {});
        }, {});

        // Make sure each package is present and matches a required version.
        _(mappings).forEach(function (versionString, name) {
            if (!grunt.file.exists(path.join(packageDir, 'node_modules', name))) {
                grunt.log.error(name + ': ' + 'not installed!'.red);
                validRun = false;
                return;
            }

            // Quick and dirty check - make sure we're dealing with semver, not
            // a URL or a shortcut to the GitHub repo.
            if (/\//.test(versionString)) {
                return;
            }

            var version = grunt.file.readJSON(path.join(packageDir, 'node_modules', name, 'package.json')).version;
            if (!semver.satisfies(version, versionString)) {
                validRun = false;
                grunt.log.error(name + ': installed: ' + version.red + ', expected: ' + versionString.green);
            }

            if (validRun) {
                grunt.verbose.writeln(name + ': installed: ' + version.green + ', expected: ' + versionString.green);
            }
        });

        if (validRun) {
            done(true);
        } else {
            if (!npmInstall) {
                grunt.log.writeln('Invoke ' + 'npm install'.green + ' to install missing packages');
                done(false);
            } else {
                grunt.log.writeln('Invoking ' + 'npm install'.green + '...');
                // execSync errors on non-empty stderr; silent such output.
                spawn(win32 ? 'cmd' : 'npm', [win32 ? '/c npm install' : 'install'], {
                    cwd: packageDir || '.',
                    stdio: 'inherit',
                }).on('close', function (code) {
                        if (code !== 0) {
                            grunt.log.error('npm install failed with code: ' + (code + '').red);
                            done(false);
                        } else {
                            done(true);
                        }
                    });
            }
        }
    };
};
<|endoftext|>


<commit_before>function Archive(command, params, item) {
	if (command !== 'archive' || !Match.test(params, String)) {
		return;
	}

	let channel = params.trim();
	let room;

	if (channel === '') {
		room = RocketChat.models.Rooms.findOneById(item.rid);
		channel = room.name;
	} else {
		channel = channel.replace('#', '');
		room = RocketChat.models.Rooms.findOneByName(channel);
	}

	// You can not archive direct messages.
	if (room.t === 'd') {
		return;
	}

	const user = Meteor.users.findOne(Meteor.userId());

	if (room.archived) {
		RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', {
			_id: Random.id(),
			rid: item.rid,
			ts: new Date(),
			msg: TAPi18n.__('Duplicate_archived_channel_name', {
				postProcess: 'sprintf',
				sprintf: [channel]
			}, user.language)
		});
		return;
	}
	Meteor.call('archiveRoom', room._id);

	RocketChat.models.Messages.createRoomArchivedByRoomIdAndUser(room._id, Meteor.user());
	RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', {
		_id: Random.id(),
		rid: item.rid,
		ts: new Date(),
		msg: TAPi18n.__('Channel_Archived', {
			postProcess: 'sprintf',
			sprintf: [channel]
		}, user.language)
	});

	return Archive;
}

RocketChat.slashCommands.add('archive', Archive);
<commit_msg>Notify user if channel does not exist<commit_after>function Archive(command, params, item) {
	if (command !== 'archive' || !Match.test(params, String)) {
		return;
	}

	let channel = params.trim();
	let room;

	if (channel === '') {
		room = RocketChat.models.Rooms.findOneById(item.rid);
		channel = room.name;
	} else {
		channel = channel.replace('#', '');
		room = RocketChat.models.Rooms.findOneByName(channel);
	}

	const user = Meteor.users.findOne(Meteor.userId());

	if (!room) {
		return RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', {
			_id: Random.id(),
			rid: item.rid,
			ts: new Date(),
			msg: TAPi18n.__('Channel_doesnt_exist', {
				postProcess: 'sprintf',
				sprintf: [channel]
			}, user.language)
		});
	}

	// You can not archive direct messages.
	if (room.t === 'd') {
		return;
	}

	if (room.archived) {
		RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', {
			_id: Random.id(),
			rid: item.rid,
			ts: new Date(),
			msg: TAPi18n.__('Duplicate_archived_channel_name', {
				postProcess: 'sprintf',
				sprintf: [channel]
			}, user.language)
		});
		return;
	}
	Meteor.call('archiveRoom', room._id);

	RocketChat.models.Messages.createRoomArchivedByRoomIdAndUser(room._id, Meteor.user());
	RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', {
		_id: Random.id(),
		rid: item.rid,
		ts: new Date(),
		msg: TAPi18n.__('Channel_Archived', {
			postProcess: 'sprintf',
			sprintf: [channel]
		}, user.language)
	});

	return Archive;
}

RocketChat.slashCommands.add('archive', Archive);
<|endoftext|>


<commit_before>
var tape = require('tape')

var util = require('../util')
var tree = require('../slow')
var Merkle = require('../')
tree = Merkle.tree

function count (tree) {
  var s = 0
  if('string' === typeof tree)
    return 1
  else
    for (var k in tree.tree) {
      s += count(tree.tree[k])
    }
  return s + 1
}
var crypto = require('crypto')
function hash (n) {
  n = (n | 0).toString(16)
  if(n.length % 2)
    n = '0' + n
  return crypto.createHash('sha1').update(n, 'hex').digest('hex')
}

console.log('N, t, N/t')

var _t =  0.0001
var sqrt2 = Math.pow(2, 0.25)
var N = 1, j = 0
var a = []
//for(var i = 1; i <= 20; i ++) {
while(N < (1 << 21)) {
  while(a.length < N)
    a.push(hash(j++))
  var start = Date.now()
  var g = tree(a)

  var t = Date.now() - start || 0.0001
  var d = g.digest()
  console.log([~~N, t, N/t].join(', '))
  _t = t
  N = N * sqrt2
}

<commit_msg>iterate on tests that are small N<commit_after>
var tape = require('tape')

var util = require('../util')
var tree = require('../slow')
var Merkle = require('../')
tree = Merkle.tree

function count (tree) {
  var s = 0
  if('string' === typeof tree)
    return 1
  else
    for (var k in tree.tree) {
      s += count(tree.tree[k])
    }
  return s + 1
}
var crypto = require('crypto')
function hash (n) {
  n = (n | 0).toString(16)
  if(n.length % 2)
    n = '0' + n
  return crypto.createHash('sha1').update(n, 'hex').digest('hex')
}

console.log('N, t, N/t, hash')

var _t =  1
var sqrt2 = Math.pow(2, 0.25)
var N = 1, j = 0
var a = []

while(N < (1 << 21)) {
  while(a.length <= N)
    a.push(hash(j++))
  var start = Date.now()
  var m = 0, g
  while(Date.now() === start) {
    m ++
    g = tree(a)
  }

  var t = Date.now() - start || 1
  var d = g.digest()
  console.log([a.length, t/m, a.length/(t/m), d].join(', '))
  _t = t
  var _N = N
  while(N < _N + 1)
    N = N * sqrt2
}

<|endoftext|>