<commit_before>'use strict';

var logger = require('log4js').getLogger('cloudify.deployments');

/**
 * @typedef {object} Inputs
 */

/**
 * @typedef {object} Outputs
 */

/**
 * @typedef {object} Deployment
 * @property {string} id the identifier of the deployment
 * @property {string} blueprint_id the identifier of the blueprint this deployment elongs to.
 * @property {Array<Workflow>} the workflows of this deployment.
 * @property {Inputs} The inputs provided on deployment creation
 * @property {Outputs} The outputs definition of this deployment
 *
 */

/**
 * @typedef {object} Workflow
 * @property {string} id the workflow's id
 * @property {string} name the workflow's name
 * @property {???} parameters the workflows parameters
 */

/**
 * @typedef {object} DeploymentOutputs
 * @property {string} deployment_id
 * @property {???} outputs
 */

/**
 * @class DeploymentOutputsClient
 * @description
 * handles rest api calls specific for deployment outputs
 * @constructor
 */
function DeploymentOutputsClient( config ){
    this.config = config;
}

/**
 *
 * @description
 * gets the outputs for the provided deployment's id.
 * @param {string} deployment_id
 * @param {ApiCallback} callback the body gets the outputs.
 */
DeploymentOutputsClient.prototype.get = function( deployment_id, callback  ){
    logger.trace('getting deployment outputs');
    if ( !deployment_id ){
        callback(new Error('deployment_id is missing'));
        return;
    }

    this.config.request(
        {
            'method' : 'GET',
            'url' : String.format(this.config.endpoint + '/deployments/{0}/outputs', deployment_id )
        },
        callback
    );
};

/**
 * @typedef {object} DeploymentModificationNodeInstances
 * @property {???} added_and_related list of added nodes and nodes that related to them
 * @property {???} removed_and_related list of removed nodes and nodes that related to them
 */

/**
 * @typedef {object} DeploymentModification
 * @property {string} deployment_id deployment id the outputs belong to
 * @property {object} node_instances
 * @property {???} node_instances.added_and_related
 * @property {???} node_instances.remove_and_related
 * @property {???} modified_nodes original request modified nodes dict
 */

/**
 * @class DeploymentModificationClient
 * @param {ClientConfig} config
 * @constructor
 */
function DeploymentModificationClient( config ){
    this.config = config;
}

/**
 * @description
 * start deployment modification
 * @param {string} deployment_id the deployment id
 * @param {???} nodes the nodes to modify
 * @param {ApiCallback} callback body get the deployment modification
 */
DeploymentModificationClient.prototype.start = function( deployment_id, nodes, callback){
    logger.trace('starting deployment modification');
    if ( !deployment_id ){
        callback(new Error('deployment_id is missing'));
        return;
    }

    this.config.request(
        {
            'method' : 'PATCH',
            'json' : true,
            'url' : String.format(this.config.endpoint + '/deployments/{0}/modify', deployment_id ),
            'body' : {
                'stage' : 'start',
                'nodes' : nodes
            }
        },
        callback
    );
};

/**
 * @description
 * finish deployment modification
 * @param  {string} deployment_id the deployment id
 * @param {???} modification the modification response received on 'start'
 * @param {ApiCallback} callback body gets the deployment modification
 */
DeploymentModificationClient.prototype.finish = function( deployment_id, modification, callback ){
    logger.trace('finishing deployment modification');

    if ( !deployment_id ){
        callback(new Error('deployment_id is missing'));
        return;
    }
    this.config.request(
        {
            'method' : 'PATCH',
            'json' : true,
            'url' : String.format(this.config.endpoint + '/deployments/{0}/modify', deployment_id ),
            'body' : {
                'stage' : 'finish',
                'modification' : modification
            }
        },
        callback
    );
};

/**
 *
 * @class DeploymentsClient
 * @description api calls for deployments
 * @param {ClientConfig} config
 * @constructor
 */

function DeploymentsClient( config ){
    this.config = config;
}

/**
 * @description
 * returns a list of all deployments
 * @param {IncludeParam} [_include] list of fields to include in response
 * @param {ApiCallback} callback body gets a list of deployments
 */
DeploymentsClient.prototype.list = function( _include, callback ){
    logger.trace('lising deployments');
    var qs = {};

    if ( !!_include ){
        qs._include = _include;
    }

    this.config.request(
        {
            'method' : 'GET',
            'url' : String.format(this.config.endpoint + '/deployments'  ),
            qs : qs
        },
        callback
    );

};

/**
 * @description
 * returns a deployment by its id.
 * @param {string} deployment_id id of the deployment to get
 * @param {IncludeParam} [_include] list of fields to include in response
 * @param {ApiCallback} callback body gets deployment
 */
DeploymentsClient.prototype.get = function( deployment_id, _include, callback ){
    logger.trace('getting deployment');
  if ( !deployment_id ){
      callback(new Error('blueprint_id is missing'));
      return;
  }

    this.config.request(
        {
            'method' : 'GET',
            'url' : String.format( this.config.endpoint  + '/deployments/{0}', deployment_id )
        },
        callback
    );
};

/**
 * @description
 * creates a new deployment for the provided blueprint id and deployment id
 * @param {string} blueprint_id blueprint id to create a deployment of
 * @param {string} deployment_id deployment id of the new created deployment
 * @param {object|null} [inputs] inputs obj for the deployment
 * @param {ApiCallback} callback body get the created deployment
 */
DeploymentsClient.prototype.create = function( blueprint_id, deployment_id, inputs, callback ){
    logger.trace('creating deployment');
    if ( !blueprint_id ){
        callback( new Error('blueprint_id is missing'));
        return;
    }

    if ( !deployment_id ){
        callback( new Error('deployment_id is missing'));
        return;
    }

    var body = {
        'blueprint_id': blueprint_id
    };

    if ( !inputs ){
        body.inputs = inputs;
    }

    this.config.request(
        {
            'method' : 'PUT',
            'json' : true,
            'url' : String.format( this.config.endpoint + '/deployments/{0}', deployment_id ),
            'body' : body
        },
        callback // expected status code 201
    );
};

/**
 *
 * @description
 * delets the deployment whose id matches the provided deployment id.
 * by default, deployment with live nodes deletion is not allowed and
 * this behavior can be changed using the ignore_live_nodes arguments.
 *
 * @param {string} deployment_id the deployment's to be deleted id.
 * @param {boolean|null} [ignore_live_nodes=false] determines whether to ignore live nodes.
 * @param {ApiCallback} callback body gets the deleted deployment
 */
DeploymentsClient.prototype.delete = function( deployment_id, ignore_live_nodes, callback ){
    logger.trace('deleting deployment');
    if ( !deployment_id ){
        callback(new Error('deployment_id is missing'));
        return;
    }

    var qs = {};

    if ( ignore_live_nodes === true ){
        qs.ignore_live_nodes = 'true';
    }

    this.config.request(
        {
            'method' : 'DELETE',
            'url' : String.format( this.config.endpoint + '/deployments/{0}', deployment_id ),
            qs: qs
        },
        callback
    );
};

module.exports = DeploymentsClient;<commit_msg>Added deployment workflows get call<commit_after>'use strict';

var logger = require('log4js').getLogger('cloudify.deployments');

/**
 * @typedef {object} Inputs
 */

/**
 * @typedef {object} Outputs
 */

/**
 * @typedef {object} Deployment
 * @property {string} id the identifier of the deployment
 * @property {string} blueprint_id the identifier of the blueprint this deployment elongs to.
 * @property {Array<Workflow>} the workflows of this deployment.
 * @property {Inputs} The inputs provided on deployment creation
 * @property {Outputs} The outputs definition of this deployment
 *
 */

/**
 * @typedef {object} Workflow
 * @property {string} id the workflow's id
 * @property {string} name the workflow's name
 * @property {???} parameters the workflows parameters
 */

/**
 * @typedef {object} DeploymentOutputs
 * @property {string} deployment_id
 * @property {???} outputs
 */

/**
 * @class DeploymentOutputsClient
 * @description
 * handles rest api calls specific for deployment outputs
 * @constructor
 */
function DeploymentOutputsClient( config ){
    this.config = config;
}

/**
 *
 * @description
 * gets the outputs for the provided deployment's id.
 * @param {string} deployment_id
 * @param {ApiCallback} callback the body gets the outputs.
 */
DeploymentOutputsClient.prototype.get = function( deployment_id, callback  ){
    logger.trace('getting deployment outputs');
    if ( !deployment_id ){
        callback(new Error('deployment_id is missing'));
        return;
    }

    this.config.request(
        {
            'method' : 'GET',
            'url' : String.format(this.config.endpoint + '/deployments/{0}/outputs', deployment_id )
        },
        callback
    );
};

/**
 * @typedef {object} DeploymentModificationNodeInstances
 * @property {???} added_and_related list of added nodes and nodes that related to them
 * @property {???} removed_and_related list of removed nodes and nodes that related to them
 */

/**
 * @typedef {object} DeploymentModification
 * @property {string} deployment_id deployment id the outputs belong to
 * @property {object} node_instances
 * @property {???} node_instances.added_and_related
 * @property {???} node_instances.remove_and_related
 * @property {???} modified_nodes original request modified nodes dict
 */

/**
 * @class DeploymentModificationClient
 * @param {ClientConfig} config
 * @constructor
 */
function DeploymentModificationClient( config ){
    this.config = config;
}

/**
 * @description
 * start deployment modification
 * @param {string} deployment_id the deployment id
 * @param {???} nodes the nodes to modify
 * @param {ApiCallback} callback body get the deployment modification
 */
DeploymentModificationClient.prototype.start = function( deployment_id, nodes, callback){
    logger.trace('starting deployment modification');
    if ( !deployment_id ){
        callback(new Error('deployment_id is missing'));
        return;
    }

    this.config.request(
        {
            'method' : 'PATCH',
            'json' : true,
            'url' : String.format(this.config.endpoint + '/deployments/{0}/modify', deployment_id ),
            'body' : {
                'stage' : 'start',
                'nodes' : nodes
            }
        },
        callback
    );
};

/**
 * @description
 * finish deployment modification
 * @param  {string} deployment_id the deployment id
 * @param {???} modification the modification response received on 'start'
 * @param {ApiCallback} callback body gets the deployment modification
 */
DeploymentModificationClient.prototype.finish = function( deployment_id, modification, callback ){
    logger.trace('finishing deployment modification');

    if ( !deployment_id ){
        callback(new Error('deployment_id is missing'));
        return;
    }
    this.config.request(
        {
            'method' : 'PATCH',
            'json' : true,
            'url' : String.format(this.config.endpoint + '/deployments/{0}/modify', deployment_id ),
            'body' : {
                'stage' : 'finish',
                'modification' : modification
            }
        },
        callback
    );
};

/**
 *
 * @class DeploymentsClient
 * @description api calls for deployments
 * @param {ClientConfig} config
 * @constructor
 */

function DeploymentsClient( config ){
    this.config = config;
}

/**
 * @description
 * returns a list of all deployments
 * @param {IncludeParam} [_include] list of fields to include in response
 * @param {ApiCallback} callback body gets a list of deployments
 */
DeploymentsClient.prototype.list = function( _include, callback ){
    logger.trace('lising deployments');
    var qs = {};

    if ( !!_include ){
        qs._include = _include;
    }

    this.config.request(
        {
            'method' : 'GET',
            'url' : String.format(this.config.endpoint + '/deployments'  ),
            qs : qs
        },
        callback
    );

};

/**
 * @description
 * returns a deployment by its id.
 * @param {string} deployment_id id of the deployment to get
 * @param {IncludeParam} [_include] list of fields to include in response
 * @param {ApiCallback} callback body gets deployment
 */
DeploymentsClient.prototype.get = function( deployment_id, _include, callback ){
    logger.trace('getting deployment');
  if ( !deployment_id ){
      callback(new Error('blueprint_id is missing'));
      return;
  }

    this.config.request(
        {
            'method' : 'GET',
            'url' : String.format( this.config.endpoint  + '/deployments/{0}', deployment_id )
        },
        callback
    );
};

/**
 * @description
 * creates a new deployment for the provided blueprint id and deployment id
 * @param {string} blueprint_id blueprint id to create a deployment of
 * @param {string} deployment_id deployment id of the new created deployment
 * @param {object|null} [inputs] inputs obj for the deployment
 * @param {ApiCallback} callback body get the created deployment
 */
DeploymentsClient.prototype.create = function( blueprint_id, deployment_id, inputs, callback ){
    logger.trace('creating deployment');
    if ( !blueprint_id ){
        callback( new Error('blueprint_id is missing'));
        return;
    }

    if ( !deployment_id ){
        callback( new Error('deployment_id is missing'));
        return;
    }

    var body = {
        'blueprint_id': blueprint_id
    };

    if ( !inputs ){
        body.inputs = inputs;
    }

    this.config.request(
        {
            'method' : 'PUT',
            'json' : true,
            'url' : String.format( this.config.endpoint + '/deployments/{0}', deployment_id ),
            'body' : body
        },
        callback // expected status code 201
    );
};

/**
 *
 * @description
 * delets the deployment whose id matches the provided deployment id.
 * by default, deployment with live nodes deletion is not allowed and
 * this behavior can be changed using the ignore_live_nodes arguments.
 *
 * @param {string} deployment_id the deployment's to be deleted id.
 * @param {boolean|null} [ignore_live_nodes=false] determines whether to ignore live nodes.
 * @param {ApiCallback} callback body gets the deleted deployment
 */
DeploymentsClient.prototype.delete = function( deployment_id, ignore_live_nodes, callback ){
    logger.trace('deleting deployment');
    if ( !deployment_id ){
        callback(new Error('deployment_id is missing'));
        return;
    }

    var qs = {};

    if ( ignore_live_nodes === true ){
        qs.ignore_live_nodes = 'true';
    }

    this.config.request(
        {
            'method' : 'DELETE',
            'url' : String.format( this.config.endpoint + '/deployments/{0}', deployment_id ),
            qs: qs
        },
        callback
    );
};

/**
 * @description
 * returns a deployment workflows by deployment id
 * @param {string} deployment_id id of the deployment to get its workflows
 * @param {IncludeParam} [_include] list of fields to include in response
 * @param {ApiCallback} callback body gets workflows
 */
DeploymentsClient.prototype.get_workflows = function( deployment_id, _include, callback ){
    logger.trace('getting workflows');
    if ( !deployment_id ){
        callback(new Error('blueprint_id is missing'));
        return;
    }

    this.config.request(
        {
            'method' : 'GET',
            'url' : String.format( this.config.endpoint  + '/deployments/{0}/workflows', deployment_id )
        },
        callback
    );
};

module.exports = DeploymentsClient;<|endoftext|>


<commit_before>const spawn = require('cross-spawn');
const path = require('path');

const s = `\\${path.sep}`;
const pattern = process.argv[2] === 'e2e'
  ? `test${s}e2e${s}.+\\.spec\\.js`
  : `test${s}(?!e2e${s})[^${s}]+${s}.+\\.spec\\.js$`;

const result = spawn.sync(path.normalize('./node_modules/.bin/jest'), [pattern], { stdio: 'inherit' });

// console.log('resut',result)
process.exit(result.status);
<commit_msg>Remove debug<commit_after>const spawn = require('cross-spawn');
const path = require('path');

const s = `\\${path.sep}`;
const pattern = process.argv[2] === 'e2e'
  ? `test${s}e2e${s}.+\\.spec\\.js`
  : `test${s}(?!e2e${s})[^${s}]+${s}.+\\.spec\\.js$`;

const result = spawn.sync(path.normalize('./node_modules/.bin/jest'), [pattern], { stdio: 'inherit' });

process.exit(result.status);
<|endoftext|>


<commit_before>CodeMirror.defineMode("s", function(config, parserConfig) {
	'use strict';

	// If an architecture is specified, its initialization function may
	// populate this array with custom parsing functions which will be
	// tried in the event that the standard functions do not find a match.
	var custom = [];

	// The symbol used to start a line comment changes based on the target
	// architecture.
	// If no architecture is pased in "parserConfig" then only multiline
	// comments will have syntax support.
	var lineCommentStartSymbol = "";

	// These directives are architecture independent.
	// Machine specific directives should go in their respective
	// architecture initialization function.
	// Reference:
	// http://sourceware.org/binutils/docs/as/Pseudo-Ops.html#Pseudo-Ops
	var directives = {
		".abort" : "builtin",
		".align" : "builtin",
		".altmacro" : "builtin",
		".ascii" : "builtin",
		".asciz" : "builtin",
		".balign" : "builtin",
		".balignw" : "builtin",
		".balignl" : "builtin",
		".bundle_align_mode" : "builtin",
		".bundle_lock" : "builtin",
		".bundle_unlock" : "builtin",
		".byte" : "builtin",
		".cfi_startproc" : "builtin",
		".comm" : "builtin",
		".data" : "builtin",
		".def" : "builtin",
		".desc" : "builtin",
		".dim" : "builtin",
		".double" : "builtin",
		".eject" : "builtin",
		".else" : "builtin",
		".elseif" : "builtin",
		".end" : "builtin",
		".endef" : "builtin",
		".endfunc" : "builtin",
		".endif" : "builtin",
		".equ" : "builtin",
		".equiv" : "builtin",
		".eqv" : "builtin",
		".err" : "builtin",
		".error" : "builtin",
		".exitm" : "builtin",
		".extern" : "builtin",
		".fail" : "builtin",
		".file" : "builtin",
		".fill" : "builtin",
		".float" : "builtin",
		".func" : "builtin",
		".global" : "builtin",
		".gnu_attribute" : "builtin",
		".hidden" : "builtin",
		".hword" : "builtin",
		".ident" : "builtin",
		".if" : "builtin",
		".incbin" : "builtin",
		".include" : "builtin",
		".int" : "builtin",
		".internal" : "builtin",
		".irp" : "builtin",
		".irpc" : "builtin",
		".lcomm" : "builtin",
		".lflags" : "builtin",
		".line" : "builtin",
		".linkonce" : "builtin",
		".list" : "builtin",
		".ln" : "builtin",
		".loc" : "builtin",
		".loc_mark_labels" : "builtin",
		".local" : "builtin",
		".long" : "builtin",
		".macro" : "builtin",
		".mri" : "builtin",
		".noaltmacro" : "builtin",
		".nolist" : "builtin",
		".octa" : "builtin",
		".offset" : "builtin",
		".org" : "builtin",
		".p2align" : "builtin",
		".popsection" : "builtin",
		".previous" : "builtin",
		".print" : "builtin",
		".protected" : "builtin",
		".psize" : "builtin",
		".purgem" : "builtin",
		".pushsection" : "builtin",
		".quad" : "builtin",
		".reloc" : "builtin",
		".rept" : "builtin",
		".sbttl" : "builtin",
		".scl" : "builtin",
		".section" : "builtin",
		".set" : "builtin",
		".short" : "builtin",
		".single" : "builtin",
		".size" : "builtin",
		".skip" : "builtin",
		".sleb128" : "builtin",
		".space" : "builtin",
		".stab" : "builtin",
		".string" : "builtin",
		".struct" : "builtin",
		".subsection" : "builtin",
		".symver" : "builtin",
		".tag" : "builtin",
		".text" : "builtin",
		".title" : "builtin",
		".type" : "builtin",
		".uleb128" : "builtin",
		".val" : "builtin",
		".version" : "builtin",
		".vtable_entry" : "builtin",
		".vtable_inherit" : "builtin",
		".warning" : "builtin",
		".weak" : "builtin",
		".weakref" : "builtin",
		".word" : "builtin",
	};

	var registers = {};

	function x86(config, parserConfig) {
		lineCommentStartSymbol = "#";

		registers.ax  = "variable";
		registers.eax = "variable-2";
		registers.rax = "variable-3";

		registers.bx  = "variable";
		registers.ebx = "variable-2";
		registers.rbx = "variable-3";

		registers.cx  = "variable";
		registers.ecx = "variable-2";
		registers.rcx = "variable-3";

		registers.dx  = "variable";
		registers.edx = "variable-2";
		registers.rdx = "variable-3";

		registers.si  = "variable";
		registers.esi = "variable-2";
		registers.rsi = "variable-3";

		registers.di  = "variable";
		registers.edi = "variable-2";
		registers.rdi = "variable-3";

		registers.sp  = "variable";
		registers.esp = "variable-2";
		registers.rsp = "variable-3";

		registers.bp  = "variable";
		registers.ebp = "variable-2";
		registers.rbp = "variable-3";

		registers.ip  = "variable";
		registers.eip = "variable-2";
		registers.rip = "variable-3";

		registers.cs  = "keyword";
		registers.ds  = "keyword";
		registers.ss  = "keyword";
		registers.es  = "keyword";
		registers.fs  = "keyword";
		registers.gs  = "keyword";
	}

	function armv6(config, parserConfig) {
		// Reference:
		// http://infocenter.arm.com/help/topic/com.arm.doc.qrc0001l/QRC0001_UAL.pdf
		// http://infocenter.arm.com/help/topic/com.arm.doc.ddi0301h/DDI0301H_arm1176jzfs_r0p7_trm.pdf
		lineCommentStartSymbol = "@";
		directives.syntax = "builtin";

		registers.r0  = "variable";
		registers.r1  = "variable";
		registers.r2  = "variable";
		registers.r3  = "variable";
		registers.r4  = "variable";
		registers.r5  = "variable";
		registers.r6  = "variable";
		registers.r7  = "variable";
		registers.r8  = "variable";
		registers.r9  = "variable";
		registers.r10 = "variable";
		registers.r11 = "variable";
		registers.r12 = "variable";

		registers.sp  = "variable-2";
		registers.lr  = "variable-2";
		registers.pc  = "variable-2";
		registers.r13 = registers.sp;
		registers.r14 = registers.lr;
		registers.r15 = registers.pc;

		custom.push(function(ch, stream, state) {
			if (ch === '#') {
				stream.eatWhile(/\w/);
				return "number";
			}
		});
	}

	var arch = parserConfig.architecture.toLowerCase();
	if (arch === "x86") {
		x86(config, parserConfig);
	} else if (arch === "arm" || arch === "armv6") {
		armv6(config, parserConfig);
	}

	function nextUntilUnescaped(stream, end) {
		var escaped = false, next;
		while ((next = stream.next()) !== null) {
			if (next === end && !escaped) {
				return false;
			}
			escaped = !escaped && next === "\\";
		}
		return escaped;
	}

	function clikeComment(stream, state) {
		var maybeEnd = false, ch;
		while ((ch = stream.next()) !== null) {
			if (ch === "/" && maybeEnd) {
				state.tokenize = null;
				break;
			}
			maybeEnd = (ch === "*");
		}
		return "comment";
	}

	return {
		startState: function(basecolumn) {
			return {
				tokenize: null,
			};
		},

		token: function(stream, state) {
			if (state.tokenize) {
				return state.tokenize(stream, state);
			}

			if (stream.eatSpace()) {
				return null;
			}

			var style, cur, ch = stream.next();

			if (ch === "/") {
				if (stream.eat("*")) {
					state.tokenize = clikeComment;
					return clikeComment(stream, state);
				}
			}

			if (ch === lineCommentStartSymbol) {
				stream.skipToEnd();
				return "comment";
			}

			if (ch === '"') {
				nextUntilUnescaped(stream, '"');
				return "string";
			}

			if (ch === '.') {
				stream.eatWhile(/\w/);
				cur = stream.current().toLowerCase();
				style = directives[cur];
				return style || null;
			}

			if (ch === '=') {
				stream.eatWhile(/\w/);
				return "tag";
			}

			if (ch === '{') {
				return "braket";
			}

			if (ch === '}') {
				return "braket";
			}

			if (/\d/.test(ch)) {
				if (ch === "0" && stream.eat("x")) {
					stream.eatWhile(/[0-9a-fA-F]/);
					return "number";
				}
				stream.eatWhile(/\d/);
				return "number";
			}

			if (/\w/.test(ch)) {
				stream.eatWhile(/\w/);
				if (stream.eat(":")) {
					return 'tag';
				}
				cur = stream.current().toLowerCase();
				style = registers[cur];
				return style || null;
			}

			for (var i = 0; i < custom.length; i++) {
				style = custom[i](ch, stream, state);
				if (style) {
					return style;
				}
			}
		},
	}
});
<commit_msg>[gas mode] Fix overly precise comparisons<commit_after>CodeMirror.defineMode("s", function(config, parserConfig) {
	'use strict';

	// If an architecture is specified, its initialization function may
	// populate this array with custom parsing functions which will be
	// tried in the event that the standard functions do not find a match.
	var custom = [];

	// The symbol used to start a line comment changes based on the target
	// architecture.
	// If no architecture is pased in "parserConfig" then only multiline
	// comments will have syntax support.
	var lineCommentStartSymbol = "";

	// These directives are architecture independent.
	// Machine specific directives should go in their respective
	// architecture initialization function.
	// Reference:
	// http://sourceware.org/binutils/docs/as/Pseudo-Ops.html#Pseudo-Ops
	var directives = {
		".abort" : "builtin",
		".align" : "builtin",
		".altmacro" : "builtin",
		".ascii" : "builtin",
		".asciz" : "builtin",
		".balign" : "builtin",
		".balignw" : "builtin",
		".balignl" : "builtin",
		".bundle_align_mode" : "builtin",
		".bundle_lock" : "builtin",
		".bundle_unlock" : "builtin",
		".byte" : "builtin",
		".cfi_startproc" : "builtin",
		".comm" : "builtin",
		".data" : "builtin",
		".def" : "builtin",
		".desc" : "builtin",
		".dim" : "builtin",
		".double" : "builtin",
		".eject" : "builtin",
		".else" : "builtin",
		".elseif" : "builtin",
		".end" : "builtin",
		".endef" : "builtin",
		".endfunc" : "builtin",
		".endif" : "builtin",
		".equ" : "builtin",
		".equiv" : "builtin",
		".eqv" : "builtin",
		".err" : "builtin",
		".error" : "builtin",
		".exitm" : "builtin",
		".extern" : "builtin",
		".fail" : "builtin",
		".file" : "builtin",
		".fill" : "builtin",
		".float" : "builtin",
		".func" : "builtin",
		".global" : "builtin",
		".gnu_attribute" : "builtin",
		".hidden" : "builtin",
		".hword" : "builtin",
		".ident" : "builtin",
		".if" : "builtin",
		".incbin" : "builtin",
		".include" : "builtin",
		".int" : "builtin",
		".internal" : "builtin",
		".irp" : "builtin",
		".irpc" : "builtin",
		".lcomm" : "builtin",
		".lflags" : "builtin",
		".line" : "builtin",
		".linkonce" : "builtin",
		".list" : "builtin",
		".ln" : "builtin",
		".loc" : "builtin",
		".loc_mark_labels" : "builtin",
		".local" : "builtin",
		".long" : "builtin",
		".macro" : "builtin",
		".mri" : "builtin",
		".noaltmacro" : "builtin",
		".nolist" : "builtin",
		".octa" : "builtin",
		".offset" : "builtin",
		".org" : "builtin",
		".p2align" : "builtin",
		".popsection" : "builtin",
		".previous" : "builtin",
		".print" : "builtin",
		".protected" : "builtin",
		".psize" : "builtin",
		".purgem" : "builtin",
		".pushsection" : "builtin",
		".quad" : "builtin",
		".reloc" : "builtin",
		".rept" : "builtin",
		".sbttl" : "builtin",
		".scl" : "builtin",
		".section" : "builtin",
		".set" : "builtin",
		".short" : "builtin",
		".single" : "builtin",
		".size" : "builtin",
		".skip" : "builtin",
		".sleb128" : "builtin",
		".space" : "builtin",
		".stab" : "builtin",
		".string" : "builtin",
		".struct" : "builtin",
		".subsection" : "builtin",
		".symver" : "builtin",
		".tag" : "builtin",
		".text" : "builtin",
		".title" : "builtin",
		".type" : "builtin",
		".uleb128" : "builtin",
		".val" : "builtin",
		".version" : "builtin",
		".vtable_entry" : "builtin",
		".vtable_inherit" : "builtin",
		".warning" : "builtin",
		".weak" : "builtin",
		".weakref" : "builtin",
		".word" : "builtin",
	};

	var registers = {};

	function x86(config, parserConfig) {
		lineCommentStartSymbol = "#";

		registers.ax  = "variable";
		registers.eax = "variable-2";
		registers.rax = "variable-3";

		registers.bx  = "variable";
		registers.ebx = "variable-2";
		registers.rbx = "variable-3";

		registers.cx  = "variable";
		registers.ecx = "variable-2";
		registers.rcx = "variable-3";

		registers.dx  = "variable";
		registers.edx = "variable-2";
		registers.rdx = "variable-3";

		registers.si  = "variable";
		registers.esi = "variable-2";
		registers.rsi = "variable-3";

		registers.di  = "variable";
		registers.edi = "variable-2";
		registers.rdi = "variable-3";

		registers.sp  = "variable";
		registers.esp = "variable-2";
		registers.rsp = "variable-3";

		registers.bp  = "variable";
		registers.ebp = "variable-2";
		registers.rbp = "variable-3";

		registers.ip  = "variable";
		registers.eip = "variable-2";
		registers.rip = "variable-3";

		registers.cs  = "keyword";
		registers.ds  = "keyword";
		registers.ss  = "keyword";
		registers.es  = "keyword";
		registers.fs  = "keyword";
		registers.gs  = "keyword";
	}

	function armv6(config, parserConfig) {
		// Reference:
		// http://infocenter.arm.com/help/topic/com.arm.doc.qrc0001l/QRC0001_UAL.pdf
		// http://infocenter.arm.com/help/topic/com.arm.doc.ddi0301h/DDI0301H_arm1176jzfs_r0p7_trm.pdf
		lineCommentStartSymbol = "@";
		directives.syntax = "builtin";

		registers.r0  = "variable";
		registers.r1  = "variable";
		registers.r2  = "variable";
		registers.r3  = "variable";
		registers.r4  = "variable";
		registers.r5  = "variable";
		registers.r6  = "variable";
		registers.r7  = "variable";
		registers.r8  = "variable";
		registers.r9  = "variable";
		registers.r10 = "variable";
		registers.r11 = "variable";
		registers.r12 = "variable";

		registers.sp  = "variable-2";
		registers.lr  = "variable-2";
		registers.pc  = "variable-2";
		registers.r13 = registers.sp;
		registers.r14 = registers.lr;
		registers.r15 = registers.pc;

		custom.push(function(ch, stream, state) {
			if (ch === '#') {
				stream.eatWhile(/\w/);
				return "number";
			}
		});
	}

	var arch = parserConfig.architecture.toLowerCase();
	if (arch === "x86") {
		x86(config, parserConfig);
	} else if (arch === "arm" || arch === "armv6") {
		armv6(config, parserConfig);
	}

	function nextUntilUnescaped(stream, end) {
		var escaped = false, next;
		while ((next = stream.next()) != null) {
			if (next === end && !escaped) {
				return false;
			}
			escaped = !escaped && next === "\\";
		}
		return escaped;
	}

	function clikeComment(stream, state) {
		var maybeEnd = false, ch;
		while ((ch = stream.next()) != null) {
			if (ch === "/" && maybeEnd) {
				state.tokenize = null;
				break;
			}
			maybeEnd = (ch === "*");
		}
		return "comment";
	}

	return {
		startState: function(basecolumn) {
			return {
				tokenize: null,
			};
		},

		token: function(stream, state) {
			if (state.tokenize) {
				return state.tokenize(stream, state);
			}

			if (stream.eatSpace()) {
				return null;
			}

			var style, cur, ch = stream.next();

			if (ch === "/") {
				if (stream.eat("*")) {
					state.tokenize = clikeComment;
					return clikeComment(stream, state);
				}
			}

			if (ch === lineCommentStartSymbol) {
				stream.skipToEnd();
				return "comment";
			}

			if (ch === '"') {
				nextUntilUnescaped(stream, '"');
				return "string";
			}

			if (ch === '.') {
				stream.eatWhile(/\w/);
				cur = stream.current().toLowerCase();
				style = directives[cur];
				return style || null;
			}

			if (ch === '=') {
				stream.eatWhile(/\w/);
				return "tag";
			}

			if (ch === '{') {
				return "braket";
			}

			if (ch === '}') {
				return "braket";
			}

			if (/\d/.test(ch)) {
				if (ch === "0" && stream.eat("x")) {
					stream.eatWhile(/[0-9a-fA-F]/);
					return "number";
				}
				stream.eatWhile(/\d/);
				return "number";
			}

			if (/\w/.test(ch)) {
				stream.eatWhile(/\w/);
				if (stream.eat(":")) {
					return 'tag';
				}
				cur = stream.current().toLowerCase();
				style = registers[cur];
				return style || null;
			}

			for (var i = 0; i < custom.length; i++) {
				style = custom[i](ch, stream, state);
				if (style) {
					return style;
				}
			}
		},
	}
});
<|endoftext|>


<commit_before>import {
  loop,
  liftState,
  getModel,
  getEffect,
} from './loop';

import {
  batch,
  none,
  constant,
  promise,
  call,
  lift,
} from './effects';

import {
  install,
} from './install';

import {
  combineReducers,
} from './combineReducers';

const Effects = {
  constant,
  promise,
  call,
  batch,
  none,
  lift,
};

export {
  combineReducers,
  Effects,
  install,
  loop,
  liftState,
  getModel,
  getEffect,
};
<commit_msg>export isLoop<commit_after>import {
  loop,
  liftState,
  getModel,
  getEffect,
  isLoop
} from './loop';

import {
  batch,
  none,
  constant,
  promise,
  call,
  lift,
} from './effects';

import {
  install,
} from './install';

import {
  combineReducers,
} from './combineReducers';

const Effects = {
  constant,
  promise,
  call,
  batch,
  none,
  lift,
};

export {
  combineReducers,
  Effects,
  install,
  loop,
  isLoop,
  liftState,
  getModel,
  getEffect,
};
<|endoftext|>


<commit_before>/**
 * ExcellentExport.
 * A client side Javascript export to Excel.
 *
 * @author: Jordi Burgos (jordiburgos@gmail.com)
 *
 * Based on:
 * https://gist.github.com/insin/1031969
 * http://jsfiddle.net/insin/cmewv/
 *
 * CSV: http://en.wikipedia.org/wiki/Comma-separated_values
 */

/*
 * Base64 encoder/decoder from: http://jsperf.com/base64-optimized
 */

var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var fromCharCode = String.fromCharCode;
var INVALID_CHARACTER_ERR = ( function() {
        // fabricate a suitable error object
        try {
            document.createElement('$');
        } catch (error) {
            return error;
        }
    }());

// encoder
window.btoa || (window.btoa = function(string) {
    var a, b, b1, b2, b3, b4, c, i = 0, len = string.length, max = Math.max, result = '';

    while (i < len) {
        a = string.charCodeAt(i++) || 0;
        b = string.charCodeAt(i++) || 0;
        c = string.charCodeAt(i++) || 0;

        if (max(a, b, c) > 0xFF) {
            throw INVALID_CHARACTER_ERR;
        }

        b1 = (a >> 2) & 0x3F;
        b2 = ((a & 0x3) << 4) | ((b >> 4) & 0xF);
        b3 = ((b & 0xF) << 2) | ((c >> 6) & 0x3);
        b4 = c & 0x3F;

        if (!b) {
            b3 = b4 = 64;
        } else if (!c) {
            b4 = 64;
        }
        result += characters.charAt(b1) + characters.charAt(b2) + characters.charAt(b3) + characters.charAt(b4);
    }
    return result;
});

// decoder
window.atob || (window.atob = function(string) {
    string = string.replace(/=+$/, '');
    var a, b, b1, b2, b3, b4, c, i = 0, len = string.length, chars = [];

    if (len % 4 === 1)
        throw INVALID_CHARACTER_ERR;

    while (i < len) {
        b1 = characters.indexOf(string.charAt(i++));
        b2 = characters.indexOf(string.charAt(i++));
        b3 = characters.indexOf(string.charAt(i++));
        b4 = characters.indexOf(string.charAt(i++));

        a = ((b1 & 0x3F) << 2) | ((b2 >> 4) & 0x3);
        b = ((b2 & 0xF) << 4) | ((b3 >> 2) & 0xF);
        c = ((b3 & 0x3) << 6) | (b4 & 0x3F);

        chars.push(fromCharCode(a));
        b && chars.push(fromCharCode(b));
        c && chars.push(fromCharCode(c));
    }
    return chars.join('');
});

ExcellentExport = (function() {
    var version = "1.3";
    var uri = {excel: 'data:application/vnd.ms-excel;base64,', csv: 'data:application/csv;base64,'};
    var template = {excel: '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
{table}
'};
    var base64 = function(s) {
        return window.btoa(unescape(encodeURIComponent(s)));
    };
    var format = function(s, c) {
        return s.replace(/{(\w+)}/g, function(m, p) {
            return c[p];
        });
    };

    var get = function(element) {
        if (!element.nodeType) {
            return document.getElementById(element);
        }
        return element;
    };

    var fixCSVField = function(value) {
        var fixedValue = value;
        var addQuotes = (value.indexOf(',') !== -1) || (value.indexOf('\r') !== -1) || (value.indexOf('\n') !== -1);
        var replaceDoubleQuotes = (value.indexOf('"') !== -1);

        if (replaceDoubleQuotes) {
            fixedValue = fixedValue.replace(/"/g, '""');
        }
        if (addQuotes || replaceDoubleQuotes) {
            fixedValue = '"' + fixedValue + '"';
        }
        return fixedValue;
    };

    var tableToCSV = function(table) {
        var data = "";
        for (var i = 0, row; row = table.rows[i]; i++) {
            for (var j = 0, col; col = row.cells[j]; j++) {
                data = data + (j ? ',' : '') + fixCSVField(col.innerHTML);
            }
            data = data + "\r\n";
        }
        return data;
    };

    var ee = {
        /** @expose */
        excel: function(anchor, table, name) {
            table = get(table);
            var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML};
            var hrefvalue = uri.excel + base64(format(template.excel, ctx));
            anchor.href = hrefvalue;
            // Return true to allow the link to work
            return true;
        },
        /** @expose */
        csv: function(anchor, table) {
            table = get(table);
            var csvData = tableToCSV(table);
            var hrefvalue = uri.csv + base64(csvData);
            anchor.href = hrefvalue;
            return true;
        }
    };

    return ee;
}());
<commit_msg>Removed html inside table cell to export only text.<commit_after>/**
 * ExcellentExport.
 * A client side Javascript export to Excel.
 *
 * @author: Jordi Burgos (jordiburgos@gmail.com)
 *
 * Based on:
 * https://gist.github.com/insin/1031969
 * http://jsfiddle.net/insin/cmewv/
 *
 * CSV: http://en.wikipedia.org/wiki/Comma-separated_values
 */

/*
 * Base64 encoder/decoder from: http://jsperf.com/base64-optimized
 */

var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var fromCharCode = String.fromCharCode;
var INVALID_CHARACTER_ERR = ( function() {
        // fabricate a suitable error object
        try {
            document.createElement('$');
        } catch (error) {
            return error;
        }
    }());

// encoder
window.btoa || (window.btoa = function(string) {
    var a, b, b1, b2, b3, b4, c, i = 0, len = string.length, max = Math.max, result = '';

    while (i < len) {
        a = string.charCodeAt(i++) || 0;
        b = string.charCodeAt(i++) || 0;
        c = string.charCodeAt(i++) || 0;

        if (max(a, b, c) > 0xFF) {
            throw INVALID_CHARACTER_ERR;
        }

        b1 = (a >> 2) & 0x3F;
        b2 = ((a & 0x3) << 4) | ((b >> 4) & 0xF);
        b3 = ((b & 0xF) << 2) | ((c >> 6) & 0x3);
        b4 = c & 0x3F;

        if (!b) {
            b3 = b4 = 64;
        } else if (!c) {
            b4 = 64;
        }
        result += characters.charAt(b1) + characters.charAt(b2) + characters.charAt(b3) + characters.charAt(b4);
    }
    return result;
});

// decoder
window.atob || (window.atob = function(string) {
    string = string.replace(/=+$/, '');
    var a, b, b1, b2, b3, b4, c, i = 0, len = string.length, chars = [];

    if (len % 4 === 1)
        throw INVALID_CHARACTER_ERR;

    while (i < len) {
        b1 = characters.indexOf(string.charAt(i++));
        b2 = characters.indexOf(string.charAt(i++));
        b3 = characters.indexOf(string.charAt(i++));
        b4 = characters.indexOf(string.charAt(i++));

        a = ((b1 & 0x3F) << 2) | ((b2 >> 4) & 0x3);
        b = ((b2 & 0xF) << 4) | ((b3 >> 2) & 0xF);
        c = ((b3 & 0x3) << 6) | (b4 & 0x3F);

        chars.push(fromCharCode(a));
        b && chars.push(fromCharCode(b));
        c && chars.push(fromCharCode(c));
    }
    return chars.join('');
});

ExcellentExport = (function() {
    var version = "1.3";
    var uri = {excel: 'data:application/vnd.ms-excel;base64,', csv: 'data:application/csv;base64,'};
    var template = {excel: '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
{table}
'};
    var base64 = function(s) {
        return window.btoa(unescape(encodeURIComponent(s)));
    };
    var format = function(s, c) {
        return s.replace(/{(\w+)}/g, function(m, p) {
            return c[p];
        });
    };

    var get = function(element) {
        if (!element.nodeType) {
            return document.getElementById(element);
        }
        return element;
    };

    var fixCSVField = function(value) {
        var fixedValue = value;
        var addQuotes = (value.indexOf(',') !== -1) || (value.indexOf('\r') !== -1) || (value.indexOf('\n') !== -1);
        var replaceDoubleQuotes = (value.indexOf('"') !== -1);

        if (replaceDoubleQuotes) {
            fixedValue = fixedValue.replace(/"/g, '""');
        }
        if (addQuotes || replaceDoubleQuotes) {
            fixedValue = '"' + fixedValue + '"';
        }
        return fixedValue;
    };

    var tableToCSV = function(table) {
        var data = "";
        for (var i = 0, row; row = table.rows[i]; i++) {
            for (var j = 0, col; col = row.cells[j]; j++) {
                data = data + (j ? ',' : '') + fixCSVField(col.textContent.trim());
            }
            data = data + "\r\n";
        }
        return data;
    };

    var ee = {
        /** @expose */
        excel: function(anchor, table, name) {
            table = get(table);
            var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML};
            var hrefvalue = uri.excel + base64(format(template.excel, ctx));
            anchor.href = hrefvalue;
            // Return true to allow the link to work
            return true;
        },
        /** @expose */
        csv: function(anchor, table) {
            table = get(table);
            var csvData = tableToCSV(table);
            var hrefvalue = uri.csv + base64(csvData);
            anchor.href = hrefvalue;
            return true;
        }
    };

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


<commit_before>frappe.listview_settings['User Permission'] = {

	onload: function(list_view) {
		var me = this;
		list_view.page.add_inner_button( __("Add / Update"), function() {
			let dialog =new frappe.ui.Dialog({
				title : __('Add User Permissions'),
				fields: [
					{
						fieldname: 'user',
						label: __('For User'),
						fieldtype: 'Link',
						options: 'User',
						reqd: 1,
						onchange: function() {
							dialog.fields_dict.doctype.set_input(undefined);
							dialog.fields_dict.docname.set_input(undefined);
							dialog.set_df_property("docname", "hidden", 1);
							dialog.set_df_property("apply_to_all_doctypes", "hidden", 1);
							dialog.set_df_property("applicable_doctypes", "hidden", 1);
						}
					},
					{
						fieldname: 'doctype',
						label: __('Document Type'),
						fieldtype: 'Link',
						options: 'DocType',
						reqd: 1,
						onchange: function() {
							me.on_doctype_change(dialog);
						}
					},
					{
						fieldname: 'docname',
						label: __('Document Name'),
						fieldtype: 'Dynamic Link',
						options: 'doctype',
						hidden: 1,
						onchange:  function() {
							let field = dialog.fields_dict["docname"];
							if(field.value != field.last_value) {
								if(dialog.fields_dict.doctype.value && dialog.fields_dict.docname.value && dialog.fields_dict.user.value){
									me.get_applicable_doctype(dialog).then(applicable => {
										me.get_multi_select_options(dialog, applicable).then(options => {
											me.applicable_options = options;
											me.on_docname_change(dialog, options, applicable);
											if(options.length > 5){
												dialog.fields_dict.applicable_doctypes.setup_select_all()
											}
										});
									});
								}
							}
						}
					},
					{
						fieldname: 'apply_to_all_doctypes',
						label: __('Apply to all Documents Types'),
						fieldtype: 'Check',
						checked: 1,
						hidden: 1,
						onchange: function() {
							if(dialog.fields_dict.doctype.value && dialog.fields_dict.docname.value && dialog.fields_dict.user.value){
								me.on_apply_to_all_doctypes_change(dialog, me.applicable_options);
								if(me.applicable_options.length > 5){
									dialog.fields_dict.applicable_doctypes.setup_select_all()
								}
							}
						}
					},
					{
						label: __("Applicable Document Types"),
						fieldname: "applicable_doctypes",
						fieldtype: "MultiCheck",
						options: [],
						columns: 2,
						hidden: 1
					},
				],
				primary_action: (data) => {
					data = me.validate(dialog, data);
					frappe.call({
						async: false,
						method: "frappe.core.doctype.user_permission.user_permission.add_user_permissions",
						args: {
							data : data
						},
						callback: function(r) {
							if(r.message === 1) {
								frappe.show_alert({message:__("User Permissions created sucessfully"), indicator:'blue'});
							} else {
								frappe.show_alert({message:__("Nothing to update"), indicator:'red'});

							}
						}
					});
					dialog.hide();
					list_view.refresh();
				},
				primary_action_label: __('Submit')
			});
			dialog.show();
		});
		list_view.page.add_inner_button( __("Bulk Delete"), function() {
			const dialog = new frappe.ui.Dialog({
				title: __('Clear User Permissions'),
				fields: [
					{
						fieldname: 'user',
						label: __('For User'),
						fieldtype: 'Link',
						options: 'User',
						reqd: 1
					},
					{
						fieldname: 'for_doctype',
						label: __('For Document Type'),
						fieldtype: 'Link',
						options: 'DocType',
						reqd: 1
					},
				],
				primary_action: (data) => {
					// mandatory not filled
					if (!data) return;

					frappe.confirm(__('Are you sure?'), () => {
						frappe
							.xcall('frappe.core.doctype.user_permission.user_permission.clear_user_permissions', data)
							.then(data => {
								dialog.hide();
								let message = '';
								if (data === 0) {
									message = __('No records deleted');
								} else if(data === 1) {
									message = __('{0} record deleted', [data]);
								} else {
									message = __('{0} records deleted', [data]);
								}
								frappe.show_alert({
									message,
									indicator: 'green'
								});
								list_view.refresh();
							});
					});

				},
				primary_action_label: __('Delete')
			});

			dialog.show();
		});
	},

	validate: function(dialog, data) {
		if(dialog.fields_dict.applicable_doctypes.get_unchecked_options().length == 0) {
			data.apply_to_all_doctypes = 1;
			data.applicable_doctypes = [];
			return data;
		}
		if(data.apply_to_all_doctypes == 0 && !("applicable_doctypes" in data)) {
			frappe.throw("Please select applicable Doctypes");
		}
		return data;
	},

	get_applicable_doctype: function(dialog) {
		return new Promise(resolve => {
			frappe.call({
				method: 'frappe.core.doctype.user_permission.user_permission.check_applicable_doc_perm',
				async: false,
				args:{
					user: dialog.fields_dict.user.value,
					doctype: dialog.fields_dict.doctype.value,
					docname: dialog.fields_dict.docname.value
				}
			}).then(r => {
				resolve(r.message);
			});
		});
	},

	get_multi_select_options: function(dialog, applicable){
		return new Promise(resolve => {
			frappe.call({
				method: 'frappe.desk.form.linked_with.get_linked_doctypes',
				async: false,
				args:{
					user: dialog.fields_dict.user.value,
					doctype: dialog.fields_dict.doctype.value,
					docname: dialog.fields_dict.docname.value
				}
			}).then(r => {
				var options = [];
				for(var d in r.message){
					var checked = ($.inArray(d, applicable) != -1) ? 1 : 0;
					options.push({ "label":d, "value": d , "checked": checked});
				}
				resolve(options);
			});
		});
	},

	on_doctype_change: function(dialog) {
		dialog.set_df_property("docname", "hidden", 0);
		dialog.set_df_property("docname", "reqd", 1);
		dialog.set_df_property("apply_to_all_doctypes", "hidden", 0);
		dialog.set_value("apply_to_all_doctypes","checked",1);
	},

	on_docname_change: function(dialog, options, applicable) {
		if(applicable.length != 0 ) {
			dialog.set_primary_action("Update");
			dialog.set_title("Update User Permissions");
			dialog.set_df_property("applicable_doctypes", "options", options);
			if(dialog.fields_dict.applicable_doctypes.get_checked_options().length == options.length) {
				dialog.set_df_property("applicable_doctypes", "hidden", 1);
			} else {
				dialog.set_df_property("applicable_doctypes", "hidden", 0);
				dialog.set_df_property("apply_to_all_doctypes", "checked", 0);
			}
		} else {
			dialog.set_primary_action("Submit");
			dialog.set_title("Add User Permissions");
			dialog.set_df_property("applicable_doctypes", "options", options);
			dialog.set_df_property("applicable_doctypes", "hidden", 1);
		}
	},

	on_apply_to_all_doctypes_change: function(dialog, options) {
		if(dialog.fields_dict.apply_to_all_doctypes.get_value() == 0) {
			dialog.set_df_property("applicable_doctypes", "hidden", 0);
			dialog.set_df_property("applicable_doctypes", "options", options);
		} else {
			dialog.set_df_property("applicable_doctypes", "options", options);
			dialog.set_df_property("applicable_doctypes", "hidden", 1);
		}
	}
};<commit_msg>fix: codacy<commit_after>frappe.listview_settings['User Permission'] = {

	onload: function(list_view) {
		var me = this;
		list_view.page.add_inner_button( __("Add / Update"), function() {
			let dialog =new frappe.ui.Dialog({
				title : __('Add User Permissions'),
				fields: [
					{
						fieldname: 'user',
						label: __('For User'),
						fieldtype: 'Link',
						options: 'User',
						reqd: 1,
						onchange: function() {
							dialog.fields_dict.doctype.set_input(undefined);
							dialog.fields_dict.docname.set_input(undefined);
							dialog.set_df_property("docname", "hidden", 1);
							dialog.set_df_property("apply_to_all_doctypes", "hidden", 1);
							dialog.set_df_property("applicable_doctypes", "hidden", 1);
						}
					},
					{
						fieldname: 'doctype',
						label: __('Document Type'),
						fieldtype: 'Link',
						options: 'DocType',
						reqd: 1,
						onchange: function() {
							me.on_doctype_change(dialog);
						}
					},
					{
						fieldname: 'docname',
						label: __('Document Name'),
						fieldtype: 'Dynamic Link',
						options: 'doctype',
						hidden: 1,
						onchange:  function() {
							let field = dialog.fields_dict["docname"];
							if(field.value != field.last_value) {
								if(dialog.fields_dict.doctype.value && dialog.fields_dict.docname.value && dialog.fields_dict.user.value){
									me.get_applicable_doctype(dialog).then(applicable => {
										me.get_multi_select_options(dialog, applicable).then(options => {
											me.applicable_options = options;
											me.on_docname_change(dialog, options, applicable);
											if(options.length > 5){
												dialog.fields_dict.applicable_doctypes.setup_select_all();
											}
										});
									});
								}
							}
						}
					},
					{
						fieldname: 'apply_to_all_doctypes',
						label: __('Apply to all Documents Types'),
						fieldtype: 'Check',
						checked: 1,
						hidden: 1,
						onchange: function() {
							if(dialog.fields_dict.doctype.value && dialog.fields_dict.docname.value && dialog.fields_dict.user.value){
								me.on_apply_to_all_doctypes_change(dialog, me.applicable_options);
								if(me.applicable_options.length > 5){
									dialog.fields_dict.applicable_doctypes.setup_select_all();
								}
							}
						}
					},
					{
						label: __("Applicable Document Types"),
						fieldname: "applicable_doctypes",
						fieldtype: "MultiCheck",
						options: [],
						columns: 2,
						hidden: 1
					},
				],
				primary_action: (data) => {
					data = me.validate(dialog, data);
					frappe.call({
						async: false,
						method: "frappe.core.doctype.user_permission.user_permission.add_user_permissions",
						args: {
							data : data
						},
						callback: function(r) {
							if(r.message === 1) {
								frappe.show_alert({message:__("User Permissions created sucessfully"), indicator:'blue'});
							} else {
								frappe.show_alert({message:__("Nothing to update"), indicator:'red'});

							}
						}
					});
					dialog.hide();
					list_view.refresh();
				},
				primary_action_label: __('Submit')
			});
			dialog.show();
		});
		list_view.page.add_inner_button( __("Bulk Delete"), function() {
			const dialog = new frappe.ui.Dialog({
				title: __('Clear User Permissions'),
				fields: [
					{
						fieldname: 'user',
						label: __('For User'),
						fieldtype: 'Link',
						options: 'User',
						reqd: 1
					},
					{
						fieldname: 'for_doctype',
						label: __('For Document Type'),
						fieldtype: 'Link',
						options: 'DocType',
						reqd: 1
					},
				],
				primary_action: (data) => {
					// mandatory not filled
					if (!data) return;

					frappe.confirm(__('Are you sure?'), () => {
						frappe
							.xcall('frappe.core.doctype.user_permission.user_permission.clear_user_permissions', data)
							.then(data => {
								dialog.hide();
								let message = '';
								if (data === 0) {
									message = __('No records deleted');
								} else if(data === 1) {
									message = __('{0} record deleted', [data]);
								} else {
									message = __('{0} records deleted', [data]);
								}
								frappe.show_alert({
									message,
									indicator: 'green'
								});
								list_view.refresh();
							});
					});

				},
				primary_action_label: __('Delete')
			});

			dialog.show();
		});
	},

	validate: function(dialog, data) {
		if(dialog.fields_dict.applicable_doctypes.get_unchecked_options().length == 0) {
			data.apply_to_all_doctypes = 1;
			data.applicable_doctypes = [];
			return data;
		}
		if(data.apply_to_all_doctypes == 0 && !("applicable_doctypes" in data)) {
			frappe.throw("Please select applicable Doctypes");
		}
		return data;
	},

	get_applicable_doctype: function(dialog) {
		return new Promise(resolve => {
			frappe.call({
				method: 'frappe.core.doctype.user_permission.user_permission.check_applicable_doc_perm',
				async: false,
				args:{
					user: dialog.fields_dict.user.value,
					doctype: dialog.fields_dict.doctype.value,
					docname: dialog.fields_dict.docname.value
				}
			}).then(r => {
				resolve(r.message);
			});
		});
	},

	get_multi_select_options: function(dialog, applicable){
		return new Promise(resolve => {
			frappe.call({
				method: 'frappe.desk.form.linked_with.get_linked_doctypes',
				async: false,
				args:{
					user: dialog.fields_dict.user.value,
					doctype: dialog.fields_dict.doctype.value,
					docname: dialog.fields_dict.docname.value
				}
			}).then(r => {
				var options = [];
				for(var d in r.message){
					var checked = ($.inArray(d, applicable) != -1) ? 1 : 0;
					options.push({ "label":d, "value": d , "checked": checked});
				}
				resolve(options);
			});
		});
	},

	on_doctype_change: function(dialog) {
		dialog.set_df_property("docname", "hidden", 0);
		dialog.set_df_property("docname", "reqd", 1);
		dialog.set_df_property("apply_to_all_doctypes", "hidden", 0);
		dialog.set_value("apply_to_all_doctypes","checked",1);
	},

	on_docname_change: function(dialog, options, applicable) {
		if(applicable.length != 0 ) {
			dialog.set_primary_action("Update");
			dialog.set_title("Update User Permissions");
			dialog.set_df_property("applicable_doctypes", "options", options);
			if(dialog.fields_dict.applicable_doctypes.get_checked_options().length == options.length) {
				dialog.set_df_property("applicable_doctypes", "hidden", 1);
			} else {
				dialog.set_df_property("applicable_doctypes", "hidden", 0);
				dialog.set_df_property("apply_to_all_doctypes", "checked", 0);
			}
		} else {
			dialog.set_primary_action("Submit");
			dialog.set_title("Add User Permissions");
			dialog.set_df_property("applicable_doctypes", "options", options);
			dialog.set_df_property("applicable_doctypes", "hidden", 1);
		}
	},

	on_apply_to_all_doctypes_change: function(dialog, options) {
		if(dialog.fields_dict.apply_to_all_doctypes.get_value() == 0) {
			dialog.set_df_property("applicable_doctypes", "hidden", 0);
			dialog.set_df_property("applicable_doctypes", "options", options);
		} else {
			dialog.set_df_property("applicable_doctypes", "options", options);
			dialog.set_df_property("applicable_doctypes", "hidden", 1);
		}
	}
};<|endoftext|>


<commit_before>exports.channels = {};
exports.crypto_js = {};
exports.cryptography = {};
exports.dictionary = {};
exports.events = {};
exports.filter = {};
exports.invariant  = {};
exports.leemon = {};
exports.multivalue = {};
exports.serialization = {};
exports.sjcl = {};
exports.tools = {};
exports.urandom = {};

exports.channels.OverTlecBuilder = require("./channels/OverTlecBuilder");
exports.channels.Route = require("./channels/Route");
exports.channels.Tlec = require("./channels/Tlec");
exports.channels.TlecBuilder = require("./channels/TlecBuilder");
exports.channels.Tlgr = require("./channels/Tlgr");
exports.channels.Tlht = require("./channels/Tlht");
exports.channels.TlhtBuilder = require("./channels/TlhtBuilder");
exports.channels.Tlke = require("./channels/Tlke");
exports.channels.TlkeBuilder = require("./channels/TlkeBuilder");
exports.crypto_js.enc_base64 = require("./crypto-js/enc-base64");
exports.crypto_js.enc_hex = require("./crypto-js/enc-hex");
exports.crypto_js.enc_utf8 = require("./crypto-js/enc-utf8");
exports.cryptography.random = require("./cryptography/random");
exports.cryptography.sha1_crypto_js = require("./cryptography/sha1-crypto-js");
exports.dictionary.dictionary = require("./dictionary/dictionary");
exports.events.eventEmitter = require("./events/eventEmitter");
exports.filter.Filter = require("./filter/Filter");
exports.invariant = require("./invariant");
exports.leemon.BigInt = require("./leemon/BigInt");
exports.multivalue.base64 = require("./multivalue/base64");
exports.multivalue.base64url = require("./multivalue/base64url");
exports.multivalue.bigIntForge = require("./multivalue/bigIntForge");
exports.multivalue.bigIntSjcl = require("./multivalue/bigIntSjcl");
exports.multivalue.bitArray = require("./multivalue/bitArray");
exports.multivalue.byteBuffer = require("./multivalue/byteBuffer");
exports.multivalue.bytes = require("./multivalue/bytes");
exports.multivalue.converter = require("./multivalue/converter");
exports.multivalue.decBlocks = require("./multivalue/decBlocks");
exports.multivalue.hex = require("./multivalue/hex");
exports.multivalue.multivalue = require("./multivalue/multivalue");
exports.multivalue.utf8string = require("./multivalue/utf8string");
exports.multivalue.x32wordArray = require("./multivalue/x32wordArray");
exports.serialization.SerializationContext = require("./serialization/SerializationContext");
exports.serialization.SerializationPacket = require("./serialization/SerializationPacket");
exports.serialization.serializable = require("./serialization/serializable");
exports.sjcl.bitArray = require("./sjcl/bitArray");
exports.sjcl.bn = require("./sjcl/bn");
exports.sjcl.codecBase64 = require("./sjcl/codecBase64");
exports.sjcl.codecBytes = require("./sjcl/codecBytes");
exports.sjcl.codecHex = require("./sjcl/codecHex");
exports.sjcl.codecString = require("./sjcl/codecString");
exports.tools = require("./tools");
exports.urandom.urandom = require("./urandom/urandom");
<commit_msg>clear index.js in modules<commit_after>exports.channels = {};
exports.crypto_js = {};
exports.cryptography = {};
exports.dictionary = {};
exports.events = {};
exports.filter = {};
exports.invariant  = {};
exports.leemon = {};
exports.multivalue = {};
exports.serialization = {};
exports.sjcl = {};
exports.tools = {};
exports.urandom = {};

//exports.channels.OverTlecBuilder = require("./../OverTlecBuilder/OverTlecBuilder");
//exports.channels.Route = require("./../Route/Route");
exports.channels.Tlec = require("./channels/Tlec");
//exports.channels.TlecBuilder = require("./../TlecBuilder/TlecBuilder");
//exports.channels.Tlgr = require("./../Tlgr/Tlgr");
//exports.channels.Tlht = require("./../Tlht/Tlht");
//exports.channels.TlhtBuilder = require("./../Tlht/TlhtBuilder");
exports.channels.Tlke = require("./channels/Tlke");
//exports.channels.TlkeBuilder = require("./../TlkeBuilder/TlkeBuilder");
exports.crypto_js.enc_base64 = require("./crypto-js/enc-base64");
exports.crypto_js.enc_hex = require("./crypto-js/enc-hex");
exports.crypto_js.enc_utf8 = require("./crypto-js/enc-utf8");
exports.cryptography.random = require("./cryptography/random");
exports.cryptography.sha1_crypto_js = require("./cryptography/sha1-crypto-js");
exports.dictionary.dictionary = require("./dictionary/dictionary");
exports.events.eventEmitter = require("./events/eventEmitter");
//exports.filter.Filter = require("./../Filter/Filter");
exports.invariant = require("./invariant");
exports.leemon.BigInt = require("./leemon/BigInt");
exports.multivalue.base64 = require("./multivalue/base64");
exports.multivalue.base64url = require("./multivalue/base64url");
exports.multivalue.bigIntForge = require("./multivalue/bigIntForge");
exports.multivalue.bigIntSjcl = require("./multivalue/bigIntSjcl");
exports.multivalue.bitArray = require("./multivalue/bitArray");
exports.multivalue.byteBuffer = require("./multivalue/byteBuffer");
exports.multivalue.bytes = require("./multivalue/bytes");
exports.multivalue.converter = require("./multivalue/converter");
exports.multivalue.decBlocks = require("./multivalue/decBlocks");
exports.multivalue.hex = require("./multivalue/hex");
exports.multivalue.multivalue = require("./multivalue/multivalue");
exports.multivalue.utf8string = require("./multivalue/utf8string");
exports.multivalue.x32wordArray = require("./multivalue/x32wordArray");
//exports.serialization.SerializationContext = require("././SerializationContext");
exports.serialization.SerializationPacket = require("./serialization/SerializationPacket");
exports.serialization.serializable = require("./serialization/serializable");
exports.sjcl.bitArray = require("./sjcl/bitArray");
exports.sjcl.bn = require("./sjcl/bn");
exports.sjcl.codecBase64 = require("./sjcl/codecBase64");
exports.sjcl.codecBytes = require("./sjcl/codecBytes");
exports.sjcl.codecHex = require("./sjcl/codecHex");
exports.sjcl.codecString = require("./sjcl/codecString");
exports.tools = require("./tools");
exports.urandom.urandom = require("./urandom/urandom");
<|endoftext|>


<commit_before>window.whistlerr = require('./whistle');<commit_msg>removed unused demo file<commit_after><|endoftext|>


<commit_before>var lerp = require('lerp')
var loop = require('raf-loop')
var kelvinToRGB = require('./')
var colorStyle = require('color-style')
var commas = require('add-commas')

var text = document.querySelector('.temperature')
var start = 1500
var end = 40000
var time = -Math.PI / 2 // offset start value
loop(render).start()

function render (dt) {
  time += dt / 1000
  var anim = Math.sin(time) * 0.5 + 0.5
  var K = lerp(start, end, anim)
  K = 1550
  var rgb = kelvinToRGB(K)
  text.textContent = commas(Math.floor(K)) + ' Kelvin'
  document.body.style.background = colorStyle(rgb)
}
<commit_msg>remove hard code value<commit_after>var lerp = require('lerp')
var loop = require('raf-loop')
var kelvinToRGB = require('./')
var colorStyle = require('color-style')
var commas = require('add-commas')

var text = document.querySelector('.temperature')
var start = 1500
var end = 40000
var time = -Math.PI / 2 // offset start value
loop(render).start()

function render (dt) {
  time += dt / 1000
  var anim = Math.sin(time) * 0.5 + 0.5
  var K = lerp(start, end, anim)
  var rgb = kelvinToRGB(K)
  text.textContent = commas(Math.floor(K)) + ' Kelvin'
  document.body.style.background = colorStyle(rgb)
}
<|endoftext|>


<commit_before>var browserify = require('browserify');
var brfs = require('brfs');
var through = require('through');

require('browserify/lib/builtins').fs = 'create-webfs.js'; // TODO: find a better way to replace this module

var b = browserify();

// directly include rfile TODO: use brfs, but it replaces fs.readFileSync
b.transform(function(s) {
  var data = '';
  return through(write, end);

  function write(buf) { data += buf; }
  function end() {
    var fs = require('fs');
    var s = data;
    var includedFile = fs.readFileSync('node_modules//browserify/node_modules/umd/template.js', 'utf8');
    s = s.replace(/rfile\('.\/template.js'\)/, JSON.stringify(includedFile));
    this.queue(s);
    this.queue(null);
  };
}, { global: true });

b.transform('brfs');

b.add('./webnpm.js');
b.bundle().pipe(process.stdout);

<commit_msg>Refactor text replacement transform<commit_after>var browserify = require('browserify');
var brfs = require('brfs');
var through = require('through');
var fs = require('fs');

require('browserify/lib/builtins').fs = 'create-webfs.js'; // TODO: find a better way to replace this module

var b = browserify();

var textReplacements = [
  [/rfile\('.\/template.js'\)/, JSON.stringify(fs.readFileSync('node_modules//browserify/node_modules/umd/template.js', 'utf8'))],
];

// directly include rfile TODO: use brfs, but it replaces fs.readFileSync
b.transform(function(s) {
  var data = '';
  return through(write, end);

  function write(buf) { data += buf; }
  function end() {
    for (var i = 0; i < textReplacements.length; i += 1) {
      var regex = textReplacements[i][0];
      var replacement = textReplacements[i][1];

      data  = data.replace(regex, replacement);
    }

    this.queue(data);
    this.queue(null);
  };
}, { global: true });

b.transform('brfs');

b.add('./webnpm.js');
b.bundle().pipe(process.stdout);

<|endoftext|>


<commit_before>'use strict';

var colors   = require('colors')
  , Api      = require('./src/api')
  , Viewer2d = require('./src/viewer2d')
;

var api = new Api({ debug: true });

api.on('frame', function(data) {
	//console.log('Received frame:'.green);
	//console.log(data);
});

api.on('end', function(data) {
	console.log('No more data!'.red);
	//api.disconnect();
});

api.on('event', function(event) {
	console.log(event.name.yellow);
});

api.connect()
	.then(function() { return api.qtmVersion(); })
	.then(function(version) { return api.byteOrder(); })
	.then(function(byteOrder) { return api.getState(); })
	//.then(function() { api.discover(); })

	//.then(function(state) { return api.getCurrentFrame(qtmrt.COMPONENT_ANALOG); })
	//.then(function(frame) { console.log(frame); })
	//.then(function() { return api.getParameters('All'); })
	//.then(function(parameters) { console.log(parameters); })
	//.then(function() { return api.takeControl(); })
	.then(function() {
		var viewer = new Viewer2d(api);
		return viewer.render(1, { color: 'red' });
	})
	//.then(function() { return api.setParameters({
			//'Image': {
				//'Camera': {
					//'ID': 9,
					//'Enabled': 'True',
					//'Format': 'JPG',
					//'Width': 640,
					//'Height': 400
				//}
			//}
	//}); })
	//.then(function() { return api.setParameters({
			//'Image': {
				//'Camera': {
					//'ID': 10,
					//'Enabled': 'False',
				//}
			//}
	//}); })
	//.then(function() { return api.setParameters({ 'General': { 'Capture_Time': 2.5 } }); })
	//.then(function() { return api.releaseControl(); })
	//.then(function() { return api.newMeasurement(); })
	//.then(function() { return api.setQtmEvent('foo_event'); })
	//.then(function() { return api.newMeasurement(); })
	//.then(function() { return api.close(); })
	//.then(function() { return api.start(); })
	//.then(function() { return api.stop(); })
	//.then(function() { return api.load('dadida'); })
	//.then(function() { return api.save('dadida'); })
	//.then(function() { return api.loadProject('dadida'); })
	//.then(function() { return api.trig(); })
	//.then(function() { return api.getCaptureC3D(); })
	//.then(function() { return api.getCaptureQtm(); })
	//.then(function() { return api.stopStreaming(); })
	//.then(function() { return api.streamFrames() })
	//.then(function() { return api.streamFrames({ components: ['All'], frequency: 1/100 }) })
	//.then(function() { return api.stopStreaming() })
	//.then(function() { return api.streamFrames({ components: ['All'], frequency: 1/10 }) })
	//.then(function() { return api.streamFrames({ components: ['All'], frequency: 'AllFrames' }) })
	//.then(function() { return api.streamFrames({ components: ['2D'], frequency: '2' }) })
	//.then(function() { return api.streamFrames({ components: ['Image'], frequency: '2' }) })
	//.then(function() { return api.streamFrames({ components: ['3D'], frequency: 1/10 }) })
	//.then(function() { return api.streamFrames({ udpPort: 15000, components: ['3D'], frequency: 1/100 }) })
	//.then(function() { return api.streamFrames({ components: ['3D'] }) })
	//.then(function() { return api.streamFrames({ components: ['Force', 'Image', 'Analog', 'AnalogSingle', '6D', '3D', '2D'], frequency: 'AllFrames' }) })
	//.then(function() { return api.streamFrames({ frequency: 100, components: ['3DNoLabels'] }); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['3DRes']); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['3DNoLabelsRes']); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['6D'] }); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['6DRes'] }); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['6DEuler'] }); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['6DEulerRes'] }); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['Analog'] }); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['AnalogSingle'] }); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['Force'] }); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['ForceSingle'] }); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['Image'] }); })
	//.then(function() { return api.disconnect(); })

	.catch(function(err) {
		console.log(err);
	});

<commit_msg>Graceful shutdown fix.<commit_after>'use strict';

var colors   = require('colors')
  , Api      = require('./src/api')
  , Viewer2d = require('./src/viewer2d')
;

var api = new Api({ debug: true });

api.on('frame', function(data) {
	console.log('Received frame:'.green);
	console.log(data);
});

api.on('end', function(data) {
	console.log('No more data!'.red);
	//api.disconnect();
});

api.on('event', function(event) {
	console.log(event.name.yellow);
});

api.connect()
	.then(function() { return api.qtmVersion(); })
	.then(function(version) { return api.byteOrder(); })
	.then(function(byteOrder) { return api.getState(); })
	//.then(function() { api.discover(); })

	//.then(function(state) { return api.getCurrentFrame(qtmrt.COMPONENT_ANALOG); })
	//.then(function(frame) { console.log(frame); })
	//.then(function() { return api.getParameters('All'); })
	//.then(function(parameters) { console.log(parameters); })
	//.then(function() { return api.takeControl(); })
	//.then(function() {
		//var viewer = new Viewer2d(api);
		//return viewer.render(1, { color: 'red' });
	//})
	//.then(function() { return api.setParameters({
			//'Image': {
				//'Camera': {
					//'ID': 9,
					//'Enabled': 'True',
					//'Format': 'JPG',
					//'Width': 640,
					//'Height': 400
				//}
			//}
	//}); })
	//.then(function() { return api.setParameters({
			//'Image': {
				//'Camera': {
					//'ID': 10,
					//'Enabled': 'False',
				//}
			//}
	//}); })
	//.then(function() { return api.setParameters({ 'General': { 'Capture_Time': 2.5 } }); })
	//.then(function() { return api.releaseControl(); })
	//.then(function() { return api.newMeasurement(); })
	//.then(function() { return api.setQtmEvent('foo_event'); })
	//.then(function() { return api.newMeasurement(); })
	//.then(function() { return api.close(); })
	//.then(function() { return api.start(); })
	//.then(function() { return api.stop(); })
	//.then(function() { return api.load('dadida'); })
	//.then(function() { return api.save('dadida'); })
	//.then(function() { return api.loadProject('dadida'); })
	//.then(function() { return api.trig(); })
	//.then(function() { return api.getCaptureC3D(); })
	//.then(function() { return api.getCaptureQtm(); })
	//.then(function() { return api.stopStreaming(); })
	//.then(function() { return api.streamFrames() })
	//.then(function() { return api.streamFrames({ components: ['All'], frequency: 1/100 }) })
	//.then(function() { return api.stopStreaming() })
	//.then(function() { return api.streamFrames({ components: ['All'], frequency: 1/10 }) })
	//.then(function() { return api.streamFrames({ components: ['All'], frequency: 'AllFrames' }) })
	//.then(function() { return api.streamFrames({ components: ['2D'], frequency: '2' }) })
	//.then(function() { return api.streamFrames({ components: ['Image'], frequency: '2' }) })
	//.then(function() { return api.streamFrames({ components: ['3D'], frequency: 1/10 }) })
	//.then(function() { return api.streamFrames({ udpPort: 15000, components: ['3D'], frequency: 1/100 }) })
	//.then(function() { return api.streamFrames({ components: ['3D'] }) })
	//.then(function() { return api.streamFrames({ components: ['Force', 'Image', 'Analog', 'AnalogSingle', '6D', '3D', '2D'], frequency: 'AllFrames' }) })
	//.then(function() { return api.streamFrames({ frequency: 100, components: ['3DNoLabels'] }); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['3DRes']); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['3DNoLabelsRes']); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['6D'] }); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['6DRes'] }); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['6DEuler'] }); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['6DEulerRes'] }); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['Analog'] }); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['AnalogSingle'] }); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['Force'] }); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['ForceSingle'] }); })
	//.then(function() { return api.streamFrames({ frequency: 1/100, components: ['Image'] }); })
	//.then(function() { return api.disconnect(); })

	.catch(function(err) {
		console.log(err);
	})
;

// Handle graceful shutdown {{{
if (process.platform === 'win32') {
	var rl = require('readline').createInterface({
		input: process.stdin,
		output: process.stdout
	});

	rl.on('SIGINT', function () {
		process.emit('SIGINT');
	});
}

process.on('SIGINT', function () {
	process.exit();
});
// }}} End Handle graceful shutdown
<|endoftext|>


<commit_before>(function(exports) {

    var Window = new Class({
        initialize: function() {
            this.hasInput = true;
            this.backgroundColor = null;
        },
        connect: function(server) {
            this._server = server;
            this._server.clientConnected(this);
            this._windowId = this._server.createWindow();
            this._server.changeAttributes(this._windowId, { hasInput: this.hasInput, backgroundColor: this.backgroundColor });
            this._server.selectInput(this, this._windowId, ["Expose", "ConfigureNotify"]);
        },
        handleEvent: function(event) {
            switch (event.type) {
            case "ConfigureNotify":
                return this.configureNotify(event.x, event.y, event.width, event.height);
            case "Expose":
                return this.expose(event.ctx);
            }
        },
        configureNotify: function(x, y, width, height) {
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
        },
        reparent: function(newParent) {
            this._server.reparentWindow(this._windowId, newParent._windowId);
        },
        expose: function() {
        },
        configure: function(x, y, width, height) {
            x = x === undefined ? this.x : x;
            y = y === undefined ? this.y : y;
            width = width === undefined ? this.width : width;
            height = height === undefined ? this.height : height;
            this._server.configureRequest(this._windowId, x | 0, y | 0, width | 0, height | 0);
        }
    });

    var BackgroundWindow = new Class({
        Extends: Window,
        initialize: function() {
            this.parent();
            this._image = new Image();
            this._image.src = "WoodBackground.jpg";
            this.hasInput = false;
        },
        connect: function(server) {
            this.parent(server);
            this.configure(0, 0, server.width, server.height);
        },
        expose: function(wrapper) {
            wrapper.drawWithContext(function(ctx) {
                ctx.drawImage(this._image, 0, 0, this.width, this.height);
            }.bind(this));
            wrapper.clearDamage();
        },
    });

    var FakeWindow = new Class({
        Extends: Window,
        initialize: function(imageSrc) {
            this.parent();
            this._image = new Image();
            this._image.src = imageSrc;
        },
        expose: function(wrapper) {
            wrapper.drawWithContext(function(ctx) {
                ctx.drawImage(this._image, 0, 0, this.width, this.height);
            }.bind(this));
            wrapper.clearDamage();
        },
    });

    var SimpleButton = new Class({
        Extends: Window,
        initialize: function(standardColor, hoverColor) {
            this.parent();
            this._standardColor = standardColor;
            this._hoverColor = hoverColor;
        },
        connect: function(server) {
            this.parent(server);
            this._server.selectInput(this, this._windowId, ["Enter", "Leave"]);
            this._setHover(false);
        },
        _setHover: function(hover) {
            if (this._isHovering == hover)
                return;

            this._isHovering = hover;

            if (this._server) {
                var color = hover ? this._hoverColor : this._standardColor;
                this._server.changeAttributes(this._windowId, { backgroundColor: color });
                this._server.invalidateWindow(this._windowId);
            }
        },
        handleEvent: function(event) {
            switch(event.type) {
                case "Enter":
                return this._setHover(true);
                case "Leave":
                return this._setHover(false);
                default:
                return this.parent(event);
            }
        },
        expose: function(wrapper) {
            // Don't draw anything -- the backgroundColor will take
            // care of it for us.
            wrapper.clearDamage();
        },
    });

    var _server = new Server(1024, 768);
    var server = _server.publicServer;
    document.querySelector(".server").appendChild(_server.elem);

    var w = new BackgroundWindow();
    w.connect(server);

    var colors = [['#ff0000', '#ff6666'],
                  ['#ffaa00', '#ffcc00'],
                  ['#ffff00', '#ffffcc'],
                  ['#33ff33', '#99ff99'],
                  ['#00ffff', '#99ffff']];
    for (var i = 0; i < 5; i++) {
        var cascade = 40;
        var windowNumber = i + 1;
        var w = new FakeWindow("TerminalScreenshot.png");
        w.connect(server);
        w.configure(windowNumber * cascade, windowNumber * cascade, 735, 461);
        var freq = i * 0.25 + 0.5;

        var colorSet = colors[i];

        var sub = new SimpleButton(colorSet[0], colorSet[1]);
        sub.connect(server);
        sub.configure(50, 20, 100, 50);
        sub.reparent(w);
    }

    window.addEventListener("keydown", function(evt) {
        var letter = String.fromCharCode(evt.keyCode);
        if (letter === 'D')
            _server.toggleDebug();
        if (letter === 'R')
            _server.queueFullRedraw();
    });

})(window);
<commit_msg>demo: Use the pointer cursor for buttons<commit_after>(function(exports) {

    var Window = new Class({
        initialize: function() {
            this.hasInput = true;
            this.backgroundColor = null;
        },
        connect: function(server) {
            this._server = server;
            this._server.clientConnected(this);
            this._windowId = this._server.createWindow();
            this._server.changeAttributes(this._windowId, { hasInput: this.hasInput, backgroundColor: this.backgroundColor });
            this._server.selectInput(this, this._windowId, ["Expose", "ConfigureNotify"]);
        },
        handleEvent: function(event) {
            switch (event.type) {
            case "ConfigureNotify":
                return this.configureNotify(event.x, event.y, event.width, event.height);
            case "Expose":
                return this.expose(event.ctx);
            }
        },
        configureNotify: function(x, y, width, height) {
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
        },
        reparent: function(newParent) {
            this._server.reparentWindow(this._windowId, newParent._windowId);
        },
        expose: function() {
        },
        configure: function(x, y, width, height) {
            x = x === undefined ? this.x : x;
            y = y === undefined ? this.y : y;
            width = width === undefined ? this.width : width;
            height = height === undefined ? this.height : height;
            this._server.configureRequest(this._windowId, x | 0, y | 0, width | 0, height | 0);
        }
    });

    var BackgroundWindow = new Class({
        Extends: Window,
        initialize: function() {
            this.parent();
            this._image = new Image();
            this._image.src = "WoodBackground.jpg";
            this.hasInput = false;
        },
        connect: function(server) {
            this.parent(server);
            this.configure(0, 0, server.width, server.height);
        },
        expose: function(wrapper) {
            wrapper.drawWithContext(function(ctx) {
                ctx.drawImage(this._image, 0, 0, this.width, this.height);
            }.bind(this));
            wrapper.clearDamage();
        },
    });

    var FakeWindow = new Class({
        Extends: Window,
        initialize: function(imageSrc) {
            this.parent();
            this._image = new Image();
            this._image.src = imageSrc;
        },
        expose: function(wrapper) {
            wrapper.drawWithContext(function(ctx) {
                ctx.drawImage(this._image, 0, 0, this.width, this.height);
            }.bind(this));
            wrapper.clearDamage();
        },
    });

    var SimpleButton = new Class({
        Extends: Window,
        initialize: function(standardColor, hoverColor) {
            this.parent();
            this._standardColor = standardColor;
            this._hoverColor = hoverColor;
        },
        connect: function(server) {
            this.parent(server);
            this._server.selectInput(this, this._windowId, ["Enter", "Leave"]);
            this._server.defineCursor(this._windowId, "pointer");
            this._setHover(false);
        },
        _setHover: function(hover) {
            if (this._isHovering == hover)
                return;

            this._isHovering = hover;

            if (this._server) {
                var color = hover ? this._hoverColor : this._standardColor;
                this._server.changeAttributes(this._windowId, { backgroundColor: color });
                this._server.invalidateWindow(this._windowId);
            }
        },
        handleEvent: function(event) {
            switch(event.type) {
                case "Enter":
                return this._setHover(true);
                case "Leave":
                return this._setHover(false);
                default:
                return this.parent(event);
            }
        },
        expose: function(wrapper) {
            // Don't draw anything -- the backgroundColor will take
            // care of it for us.
            wrapper.clearDamage();
        },
    });

    var _server = new Server(1024, 768);
    var server = _server.publicServer;
    document.querySelector(".server").appendChild(_server.elem);

    var w = new BackgroundWindow();
    w.connect(server);

    var colors = [['#ff0000', '#ff6666'],
                  ['#ffaa00', '#ffcc00'],
                  ['#ffff00', '#ffffcc'],
                  ['#33ff33', '#99ff99'],
                  ['#00ffff', '#99ffff']];
    for (var i = 0; i < 5; i++) {
        var cascade = 40;
        var windowNumber = i + 1;
        var w = new FakeWindow("TerminalScreenshot.png");
        w.connect(server);
        w.configure(windowNumber * cascade, windowNumber * cascade, 735, 461);
        var freq = i * 0.25 + 0.5;

        var colorSet = colors[i];

        var sub = new SimpleButton(colorSet[0], colorSet[1]);
        sub.connect(server);
        sub.configure(50, 20, 100, 50);
        sub.reparent(w);
    }

    window.addEventListener("keydown", function(evt) {
        var letter = String.fromCharCode(evt.keyCode);
        if (letter === 'D')
            _server.toggleDebug();
        if (letter === 'R')
            _server.queueFullRedraw();
    });

})(window);
<|endoftext|>