Best JavaScript code snippet using appium-xcuitest-driver
cs.loadr.js
Source:cs.loadr.js
1/*! crux-loadr - v2.9.2 - 2015-08-062* Copyright (c) 2015 Advisory Board Company; Licensed */3/// <reference path="cs.base.js" />4/*global CanvasLoader, CRIMSON, CRUX, _, Handlebars, Modernizr */5/**6Takes a DOM element and makes a single ajax request based on the <code>data-cs-*</code> params provided and/or the parameters specified via JavaScript. After initialization Loadr checks to see if there are any active Loadr requests and will add each new instance into a request queue. As one request completes the next request from the queue is automatically processed.7Templates are written using <a href="http://mustache.github.com/" target="_blank">Mustache</a> syntax and rendered using the <a href="http://handlebarsjs.com/" target="_blank">Handlebars</a> templating engine.8All requests made by Loadr should be returned using JSON and at minimum be formatted like this:9<pre class="prettyprint">10{11 Results: []12}13</pre>14The Results array can contain any format you want, as that will be parsed by the template.15@class Loadr16@extends Base17@requires CRUX.Queue18@module Widgets19@tests loadr/index.html20@demo docs/demos/loadr.jade21**/22(function (window, define, factory, undefined) {23 "use strict";24 if (define !== undefined) {25 define(['./cs.queue.js', './cs.modernizr.js', './cs.spinner.js', './cs.helpers.js', './cs.base.js', 'inputsearch.js'], factory);26 } else {27 factory(CRUX.Queue, Modernizr);28 }29}(30 this,31 this.define,32 function (queue, modernizr) {33 "use strict";34 var Namespace = 'cs-loadr-',35 Css = {36 head: Namespace + 'head'37 },38 _removeLoadingImage = function () {39 var that = this;40 // Fixes issue with createWrapper where the current styles are applied to41 // element being wrapped. In our case some elements don't have a height,42 // meaning they get set to 0. When the wrapper is removed they don't remove43 // the set styles resulting in a 0 height element with content.44 this.options.target.removeAttr('style');45 this._html.loading.find('.cs-loadr-overlay').hide('fade', (modernizr.cssanimations ? 200 : 1), function () {46 $(this).spin('destroy').parent().replaceWith(that.options.target);47 that._html.loading = null;48 that._loadComplete();49 });50 },51 _addLoadingImage = function () {52 this._html.loading = $.effects.createWrapper(this.options.target)53 .height('auto')54 .append($('<div>').addClass('cs-loadr-overlay'))55 .spin();56 this._html.loading.css('min-height', this._html.loading.find('.cs-spinner-wrapper').height());57 },58 _clientSearch = function (results) {59 var search = $.trim(this.options.data.search).toLowerCase();60 if (search.length) {61 var mapFunction = function (value) {62 if ((typeof value === 'string' || typeof value === 'number') && value.toString().toLowerCase().indexOf(search) > -1) {63 return true;64 }65 return null;66 };67 results = $.grep(results, function (result, index) {68 var map = $.map(result, mapFunction);69 return map.length;70 });71 }72 return results;73 },74 _clientFilter = function (results) {75 return results;76 };77 $.widget('crux.loadr', {78 options: {79 /**80 When true the whole returned object is used and sent to the template to be parsed. When false only the Results object is used.81 @property allresults82 @type Boolean83 @default false84 **/85 allresults: false,86 /**87 Send the request asynchronously. This sets the <code>async</code> variable of the <a href="http://api.jquery.com/jQuery.ajax/">jQuery ajax object</a>.88 @property async89 @type Boolean90 @default true91 **/92 async: true,93 /**94 Process the ajax request as soon as the Loadr is initialized. The request may be added to the queue if there is a different request currently executing.95 @property autoload96 @type Boolean97 @default true98 **/99 autoload: true,100 /**101 Allow the browser to cache the ajax request. This sets the <code>cache</code> variable of the <a href="http://api.jquery.com/jQuery.ajax/">jQuery ajax object</a>.102 @property cache103 @type Boolean104 @default false105 **/106 cache: false,107 /**108 Function that is called when a resultsdata lookup is made. Default value returns all records.109 @property clientfilter110 @type Function111 @default _clientFilter112 **/113 clientfilter: _clientFilter,114 /**115 Function that is called when a resultsdata lookup is made. Default value uses <code>this.options.data.search</code> as a filter string, and does a partial string match against all records with numeric or string fields, returning those that match. This function is called as a prefilter, before any additional filters (like pagination) are applied.116 @property clientsearch117 @type Function118 @default _clientSearch119 **/120 clientsearch: _clientSearch,121 /**122 Function that is called after the ajax request is complete and the loading animation has been removed. This event is triggered whether the request resulted in success or an error.123 When providing the callback as a string the Loadr turns the string into a function before calling it. Note: This conversion does NOT use eval().124 @property complete125 @type Function126 @default null127 **/128 complete: null,129 /**130 Allow the browser to cache the ajax request. This sets the <code>contentType</code> variable of the <a href="http://api.jquery.com/jQuery.ajax/">jQuery ajax object</a>.131 @property contenttype132 @type String133 @default "application/json; charset=utf-8"134 **/135 contenttype: "application/json; charset=utf-8",136 /**137 Data to be sent to the server. Data must be in key/value pairs or a valid JSON object. This sets the <code>data</code> variable of the <a href="http://api.jquery.com/jQuery.ajax/">jQuery ajax object</a>.138 When passing a JSON object as an attribute on an element make sure to use the single quote (’) otherwise your JSON object won't be in the correect format.139 @property data140 @type Object141 @default {}142 **/143 data: {},144 /**145 The type of data that you are expecting back from the server. This sets the <code>dataType</code> variable of the <a href="http://api.jquery.com/jQuery.ajax/">jQuery ajax object</a>.146 @property datatype147 @type String148 @default "json"149 **/150 datatype: 'json',151 /**152 Function that is called after the ajax request results in an error. When providing the callback as a string the Loadr turns the string into a function before calling it. Note: This conversion does NOT use eval().153 @property error154 @type Function155 @default null156 **/157 error: null,158 /**159 The id (without the hash) or jQuery object of an input element on the page. When typing in this field the Loadr element will auto-update with matching results.160 @property filter161 @type String | HTMLElement | jQuery Object162 @default null163 **/164 filter: null,165 /**166 Message to be displayed when a request returns with no data.167 @property nodata168 @type String169 @default "There is no data available."170 **/171 nodata: 'There is no data available.',172 /**173 Function that is called after a successful ajax request where there is at least one result. This method is called before the template is rendered allowing you to modify the results object as needed. When providing the callback as a string the Loadr turns the string into a function before calling it. Note: This conversion does NOT use eval().174 In order for loadr to continue working you MUST return an object in your parse method and it has to contain a 'Results' property, just like the result from the server.175 @property parse176 @type Function177 @default null178 **/179 parse: function (results) {180 return results;181 },182 /**183 Adds the request to the request queue. If false the request will bypass the queue and be called immediately.184 @property queue185 @type Boolean186 @default true187 **/188 queue: true,189 /**190 The HTML of the DOM element will be replaced with the results of the Loadr request. If set to false the results of the Loadr request will be appended to the DOM element.191 @property replace192 @type Boolean193 @default true194 **/195 replace: true,196 /**197 Data object to be supplied for preloaded data sets, as opposed to requesting data from the server. This can be used to either save a server hit, in the case of small, unchanging data sets, or for integration with other frameworks that have their own methods for data transport and/or custom object types. This property takes precedence over Loadr's ajax functionality.198 @property resultsdata199 @type Object200 @default null201 **/202 resultsdata: null,203 /**204 Function that is called after a successful ajax request where there is at least one result. When providing the callback as a string the Loadr turns the string into a function before calling it. Note: This conversion does NOT use eval().205 @property success206 @type Function207 @default null208 **/209 success: null,210 /**211 The element where the rendered template will be added to the DOM.212 @property target213 @type jQuery Object214 @default null215 **/216 target: null,217 /**218 The template used to parse the JSON result set. When provided it can either be the id of the template without the '#' - or a snippet of HTML.219 To see the consturction of a template view the <a href="http://handlebarsjs.com/" target="_blank">Handlebars</a> documentation.220 @property template221 @type String222 @default null223 **/224 template: null,225 /**226 The type of request. This sets the <code>type</code> variable of the <a href="http://api.jquery.com/jQuery.ajax/">jQuery ajax object</a>.227 @property type228 @type String229 @default "GET"230 **/231 type: 'GET',232 /**233 The URL to request. This sets the <code>url</code> variable of the <a href="http://api.jquery.com/jQuery.ajax/">jQuery ajax object</a>.234 @property url235 @type String236 @default " "237 **/238 url: '',239 /**240 Function that is called when a request is made. Default value creates a spinnr instance inside the widget's instance. Can be overridden to change the location of spinnr and/or remove the spinnr altogether.241 @property addLoadingImage242 @type Function243 @default _addLoadingImage244 **/245 addLoadingImage: _addLoadingImage,246 /**247 Function that is called after the request is completed. Default value removes the spinnr from the widget's instance. Should be overridden if addLoadingImage is overridden.248 @property removeLoadingImage249 @type Function250 @default _removeLoadingImage251 **/252 removeLoadingImage: _removeLoadingImage253 },254 _create: function () {255 var keyCode = $.ui.keyCode, search;256 this._html = this._html || {};257 this._vars = this._vars || {};258 $.extend(true, this._html, {259 loading: null260 });261 $.extend(true, this._vars, {262 complete: $.Callbacks(),263 deferred: new $.Deferred(),264 error: $.Callbacks(),265 filterValue: '',266 oldFilterValue: '',267 isLoading: false,268 originalContent: this.element.contents(),269 resultsData: null,270 success: $.Callbacks(),271 template: null272 });273 if (this.options.target === null) {274 this.options.target = this.element;275 }276 if (this.options.filter !== null) {277 if (this.options.filter.constructor !== $) {278 if (typeof this.options.filter === 'string') {279 this.options.filter = $('#' + this.options.filter);280 } else {281 this.options.filter = $(this.options.filter);282 }283 }284 this.options.filter.on('keydown.loadr focusout.search-cancel-button', _.debounce($.proxy(function (e) {285 if (e.keyCode !== keyCode.ENTER && e.keyCode !== keyCode.NUMPAD_ENTER && e.keyCode !== keyCode.TAB) {286 search = $.trim(this.options.filter[0].value);287 if (this._vars.filterValue === search) {288 return;289 }290 this._vars.filterValue = this.options.data.search = search;291 this.reset();292 }293 }, this),294 300295 ));296 this._vars.filterValue = $.trim(this.options.filter[0].value);297 if (this._vars.filterValue.length) {298 this.options.data.search = this._vars.filterValue;299 }300 this.options.filter.wrap('<div class="' + Css.head + '">');301 }302 if (this.options.template) {303 this.option('template', this.options.template);304 }305 if (this.options.autoload) {306 this._process();307 }308 /**309 Start the Loadr request attached to the DOM element.310 @method start311 */312 this.start = this.reload;313 },314 _setOption: function (key, value) {315 var returnVal = this._super(key, value),316 optionMap = {317 resultsdata: function (value) {318 setTimeout($.proxy(this.reset, this), 1);319 },320 template: function (value) {321 var template = value, templateName, source;322 if (typeof template === 'function' || typeof (template = CRUX.stringToFunction(template)) === 'function') {323 templateName = 'compiledTemplate' + CRUX.guid();324 Handlebars.registerPartial(templateName, template);325 // _modifyTemplate is used as hook for further template manipulation if needed by other widgets326 if (this._modifyTemplate !== undefined) {327 source = this._modifyTemplate('{{> ' + templateName + '}}');328 } else {329 source = '{{#each_index .}}{{> ' + templateName + '}}{{/each_index}}';330 }331 } else {332 source = (document.getElementById(value) ? $('#' + value).html() : value);333 // _modifyTemplate is used as hook for further template manipulation if needed by other widgets334 if (this._modifyTemplate !== undefined) {335 source = this._modifyTemplate(source);336 } else {337 source = '{{#each_index .}}' + source + '{{/each_index}}';338 }339 }340 this._vars.template = Handlebars.compile(source);341 }342 };343 if (typeof optionMap[key] === 'function') {344 optionMap[key].call(this, value);345 }346 return returnVal;347 },348 _process: function () {349 if (this.element.parent().is(':visible')) {350 this.options.addLoadingImage.call(this);351 }352 if (this.options.queue) {353 queue.add(this, this._load);354 queue.start();355 } else {356 this._load();357 }358 },359 _load: function () {360 this._vars.isLoading = true;361 this._vars.resultsData = null;362 return this._call()363 .done($.proxy(this._successDecorator, this))364 .fail($.proxy(this._error, this))365 .always($.proxy(this._complete, this));366 },367 _call: function () {368 var dfd = new $.Deferred();369 if (this.options.resultsdata) {370 dfd.resolve();371 } else if (!this.options.url) {372 dfd.reject();373 } else {374 this._vars.request = $.ajax(this.options.url, {375 async: this.options.async,376 cache: this.options.cache,377 contentType: this.options.contenttype,378 context: this,379 data: this.options.type === 'POST' ? JSON.stringify(this.options.data) : this.options.data,380 dataType: this.options.datatype,381 error: dfd.reject,382 success: dfd.resolve,383 traditional: true,384 type: this.options.type385 });386 }387 return dfd;388 },389 _successDecorator: function () {390 // Adapter function for _success, which expects the legitimate callback parameters from $.ajax...391 // If we have arguments, we've received them from a legitimate $.ajax call, otherwise, we're392 // Pulling from the locally-supply data source, which we forward on... status and jxhr aren't393 // currently used in our own _success/_error/_complete methods, so it's ok that they're undefined.394 if (arguments.length) {395 this._success.apply(this, arguments);396 } else {397 var results = this.options.resultsdata,398 search = this.options.clientsearch,399 filter = this.options.clientfilter;400 if (typeof results === 'string') {401 results = CRUX.stringToObject(results);402 }403 if (typeof search === 'string') {404 search = CRUX.stringToFunction(search);405 }406 if (typeof filter === 'string') {407 filter = CRUX.stringToFunction(filter);408 }409 try {410 results = $.extend(true, (this.options.allresults === false ? {} : []), results);411 if (this.options.allresults === false && results.Results) {412 results.Results = search.call(this, results.Results);413 } else if (this.options.allresults === true) {414 results = search.call(this, results);415 }416 } catch (e) {417 this._error(undefined, 'parseerror', 'error');418 }419 this._success(filter.call(this, results));420 }421 },422 _success: function (results, status, jxhr) {423 var parser = this.options.parse;424 this.options.target.find('[class^="loadr-status"]').remove();425 if (this.options.replace === true || (this.options.filter instanceof jQuery && this._vars.filterValue !== this._vars.oldFilterValue)) {426 this.options.target.empty();427 }428 if (typeof parser === 'string') {429 parser = CRUX.stringToFunction(this.options.parse);430 }431 this._vars.resultsData = results = parser(results);432 if (this.options.allresults === false && results.Results === undefined) {433 this._error(jxhr, 'parseerror', 'error');434 return;435 }436 if ((this.options.allresults === true && !results.length) || (this.options.allresults === false && !results.Results.length)) {437 this._error(jxhr, 'nodata', 'error');438 return;439 }440 if (this.options.template && this._processOutput === undefined) {441 this.options.target.append(this._vars.template(this.options.allresults ? results : results.Results));442 } else if (this._processOutput) {443 this._processOutput();444 }445 /**446 Triggered after an successful server response from an ajax request where there is data.447 If you are binding to this event the widget name is automatically prefixed to the event.448 <code>449 $('.example').on( "{widgetname}success", function(event) {});450 </code>451 @event success452 **/453 this._trigger('success', null, [results]);454 this._vars.success.fireWith(this, [this.element[0], results]);455 },456 _contentHelper: function (message, status) {457 var html = '',458 err = 'loadr-status-';459 if (this.options.target.is('table')) {460 html = $('<tr><td></td></tr>');461 html.find('td').addClass(err + status).append(message);462 } else if (this.options.target.is('ol, ul')) {463 html = $('<li>').addClass(err + status).append(message);464 } else {465 html = $('<div>').addClass(err + status).append(message);466 }467 return html;468 },469 _error: function (jxhr, status, error) {470 var msg = 'There was an error retrieving data.';471 if (status === 'timeout') {472 msg = 'The request has timed out.';473 } else if (status === 'abort') {474 msg = 'The request has been aborted.';475 } else if (status === 'parseerror') {476 msg = 'The data returned is not in the correct format';477 } else if (status === 'nodata') {478 msg = this.options.nodata;479 }480 this.options.target.html(this._contentHelper(msg, status));481 /**482 Triggered after an unsuccessful server response from an ajax request or if there is no data returned in a successful response.483 If you are binding to this event the widget name is automatically prefixed to the event.484 <code>485 $('.example').on( "{widgetname}error", function(event) {});486 </code>487 @event error488 **/489 this._trigger('error', null, {textStatus: status, errorThrown: error});490 this._vars.error.fireWith(this, [this.element[0], status, error]);491 },492 _complete: function (xhr) {493 if (this._html.loading !== null) {494 this.options.removeLoadingImage.call(this);495 } else {496 this._loadComplete();497 }498 this._vars.oldFilterValue = this._vars.filterValue;499 },500 _loadComplete: function () {501 this._vars.isLoading = false;502 /**503 Triggered after a loadr request has been completed and the loading animation has been removed from the DOM.504 If you are binding to this event the widget name is automatically prefixed to the event.505 <code>506 $('.example').on( "{widgetname}complete", function(event) {});507 </code>508 @event complete509 **/510 this._trigger('complete', null, [this._vars.resultsData]);511 this._vars.complete.fireWith(this, [this.element[0], this._vars.resultsData]);512 if ($.fn.iconic) {513 this.options.target.find('[class^=iconic]').iconic();514 }515 },516 /**517 Add a callback to the stack (success, error, complete). See <a href="http://api.jquery.com/callbacks.add/" target="_blank">jQuery Callbacks (add)</a> for more details.518 @method add519 @param {String} type The type of callback to add.520 @param {Function | Array} fn A function or an array of functions.521 */522 add: function (type) {523 var args = Array.prototype.slice.call(arguments, 1);524 if (!args.length) {525 return;526 }527 this._vars[type].add(args);528 },529 /**530 Remove a callback from the stack (success, error, complete). See <a href="http://api.jquery.com/callbacks.remove/" target="_blank">jQuery Callbacks (remove)</a> for more details.531 @method remove532 @param {String} type The type of callback to remove.533 @param {Function | Array} fn A function or an array of functions.534 */535 remove: function (type) {536 var self = this,537 args = Array.prototype.slice.call(arguments, 1);538 if (!args.length) {539 return;540 }541 $.each(args, function (i, cb) {542 if ($.type(cb) === 'array') {543 $.each(cb, function (j, _cb) {544 self.remove(type, _cb);545 });546 } else {547 self._vars[type].remove(cb);548 }549 });550 },551 /**552 Reload the Loadr request attached to the DOM element. Aborts any currently executing request (that is attached to this element).553 @method reload554 */555 reload: function () {556 if (this._vars.request && this._vars.request.state() === 'pending') {557 this._vars.request.abort();558 }559 this._process();560 },561 reset: function () {562 this.reload();563 },564 destroy: function () {565 this.element.empty().append(this._vars.originalContent);566 $.Widget.prototype.destroy.call(this);567 }568 });569 $(function () {570 $('.deferred').loadr();571 });572 }...
record-screen.js
Source:record-screen.js
...119 await this._enforceTermination();120 log.warn(`Screen recording exited with error code ${code}, signal ${signal}`);121 }122 });123 await this._process.start(0);124 try {125 await waitForCondition(async () => {126 if (await this.getVideoPath()) {127 return true;128 }129 if (!this._process) {130 throw new Error(`${FFMPEG_BINARY} process died unexpectedly`);131 }132 return false;133 }, {134 waitMs: RETRY_TIMEOUT,135 intervalMs: RETRY_PAUSE,136 });137 } catch (e) {...
ui.16.window.js
Source:ui.16.window.js
1UI.Controls.Window.Threading = UI.Controls.Window.extend({2 3 _process: false,4 _params: false,5 _logTimeout: 2000,6 constructor: function(container, title, draggable, worker, timeout, prio, params, logTimeout) {7 this.base(container, title, draggable);8 this._process = new Threading.Process(worker, timeout, prio);9 this._params = params;10 this._logTimeout = logTimeout ? logTimeout : 2000;11 this.bind();12 },13 bind: function() {14 var self = this;15 this._process16 .addHandler('process.error', function(sender, args) {17 self.addResult('process error:', args.message); 18 })19 .addHandler('process.started', function(sender, args) {20 self._addResult('process is runned successfuly'); 21 this.StartProcessLog(self._logTimeout);22 })23 .addHandler('process.completed', function(sender, args) {24 self._addResult('process complete'); 25 self.controls('start').enable(true);26 self.controls('cancel').enable(true);27 })28 .addHandler('process.stoped', function(sender, args) {29 self._addResult('process stoped'); 30 })31 .addHandler('process.log', function(sender, args) {32 args.results.forEach(function(result) {33 self._addResult(result); 34 })35 });36 this37 .addHandler('ready', function(sender, args) {38 var self = this;39 self.Resize(750, 0);40 if(this._params && this._params.length) {41 this._params.forEach(function(param) {42 self.addControl(param);43 });44 }45 this.controls('resultLabel', new UI.Controls.Label('resultLabel', this.container('content'))).parent(this).Render().html('РезÑлÑÑаÑÑ').styles({fontWeight: 'bold', backgroundColor: 'transparent', border: '0px', paddingBottom: '5px'});46 this.controls('result', new UI.Controls.Pane('result', this.container('content'))).parent(this).Render().styles({width: '100%', height: '400px'});47 this.controls('start', new UI.Controls.Button('start', this.container('buttons'), 'ÐапÑÑÑиÑÑ', false, 'start').addHandler('click', function() { self.raiseEvent('dialogResult', {result: 'start'}); })).parent(this).Render();48 this.controls('cancel', new UI.Controls.Button('cancel', this.container('buttons'), 'ÐÑмениÑÑ', false, 'cancel').addHandler('click', function() { self.raiseEvent('dialogResult', {result: 'cancel'}); })).parent(this).Render();49 50 })51 .addHandler('dialogResult', function(sender, args) {52 switch(args.result) {53 case 'start': {54 this.controls('start').enable(false);55 this.controls('cancel').enable(false);56 var params = {};57 var self = this;58 this._params.forEach(function(param) {59 params[param.field] = self.controls(param.field).val();60 });61 this._process.StartProcess(params);62 break;63 }64 case 'cancel': {65 this.Hide();66 break;67 }68 }69 });70 },71 _addResult: function(result) {72 var label = new UI.Controls.Label(Date.Now().getTime(), this.controls('result')).Render().styles({display: 'block', width: '100%', fontSize: '14px', padding: '5px'}).html(result);73 label.ensureVisible();74 },...
FiresheepSession.js
Source:FiresheepSession.js
1//2// FiresheepSession.js3// Part of the Firesheep project.4//5// Copyright (C) 2010 Eric Butler6//7// Authors:8// Eric Butler <eric@codebutler.com>9//10// This program is free software: you can redistribute it and/or modify11// it under the terms of the GNU General Public License as published by12// the Free Software Foundation, either version 3 of the License, or13// (at your option) any later version.14//15// This program is distributed in the hope that it will be useful,16// but WITHOUT ANY WARRANTY; without even the implied warranty of17// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the18// GNU General Public License for more details.19//20// You should have received a copy of the GNU General Public License21// along with this program. If not, see <http://www.gnu.org/licenses/>.22Components.utils.import('resource://firesheep/util/Observers.js');23Components.utils.import('resource://firesheep/util/Utils.js');24Components.utils.import('resource://firesheep/FiresheepWorker.js');25var EXPORTED_SYMBOLS = [ 'FiresheepSession' ];26function FiresheepSession (fs, iface, filter) {27 this._core = fs;28 this._iface = iface;29 this._filter = filter;30 this._resultCache = {};31 this._handlers = fs.handlers;32}33FiresheepSession.prototype = {34 start: function () {35 try {36 if (this.isCapturing)37 return;38 39 // Ensure the binary is actually executable.40 var osString = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime).OS; 41 if (osString != 'WINNT') {42 // FIXME: This should really use chmod(2) directly.43 Utils.runCommand('chmod', [ 'a+x', this._core.backendPath ]);44 // Tell backend to repair owner/setuid. Will return succesfully if everything is already OK.45 this._process = Cc["@codebutler.com/mozpopen/process;1"].createInstance(Ci.IMozPopenProcess);46 this._process.Init(this._core.backendPath, [ '--fix-permissions' ], 1);47 this._process.Start();48 var exitCode = this._process.Wait();49 if (exitCode != 0) {50 throw "Failed to fix permissions";51 }52 }53 54 this._process = Cc["@codebutler.com/mozpopen/process;1"].createInstance(Ci.IMozPopenProcess);55 this._process.Init(this._core.backendPath, [ this._iface, this._filter ], 2);56 this._process.Start();57 if (this._process.IsRunning()) {58 this._thread = Cc["@mozilla.org/thread-manager;1"].getService().newThread(0);59 this._thread.dispatch(new FiresheepWorker(this), Ci.nsIThread.DISPATCH_NORMAL);60 } else {61 throw "Failed to start capture.";62 }63 } catch (e) {64 this.handleError(e);65 }66 },67 68 stop: function () {69 if (!this.isCapturing)70 return;71 if (this._process.IsRunning())72 this._process.Stop();73 this._process = null;74 this._thread = null;75 76 Observers.notify('Firesheep', { action: 'capture_stopped' });77 },78 79 get isCapturing () {80 return !!this._process81 },82 83 /* Called by worker */84 postResult: function (result) {85 this._core._handleResult.apply(this._core, [ result ]);86 },87 88 handleError: function (e) {89 dump('Error: ' + e + '\n');90 Observers.notify('Firesheep', { action: 'error', error: e });91 this.stop();92 }...
ShairportSync.js
Source:ShairportSync.js
1import assert from 'assert';2import childProcess from 'child_process';3import _ from 'lodash';4import {Output} from './Output';5import {Stdout} from './Output/Stream/Stdout';6import {EventEmitter} from 'events';7const _name = Symbol("name");8const _output = Symbol("output");9const _process = Symbol("process");10export class ShairportSync extends EventEmitter11{12 constructor (output = new Stdout()) {13 super();14 assert(output instanceof Output, 'new ShairportSync() Argument#1 must be an Output instance.')15 this[_output] = output;16 this[_process] = null;17 }18 set name (name) {19 if (this.process) return;20 this[_name] = name;21 }22 get name () {23 return this[_name];24 }25 get output () {26 return this[_output];27 }28 get process () {29 return this[_process];30 }31 start (config = []) {32 if (this.process) return;33 const spawn = childProcess.spawn;34 assert(_.isArray(config), 'ShairportSync::start() Argument#1 must be an Array.');35 let args = _.chain(config)36 .clone(true)37 .filter(opt => !_.includes(['--name', '--output', "-n", "-o"], opt[0]));38 if (this.name) args = args.concat([['--name', this.name]]);39 args = args.concat([['--output', this.output.name]]);40 if (this.output.args.length) {41 args = args.concat([["--"]]).concat(this.output.args);42 }43 args = args.flatten().value();44 this[_process] = spawn(ShairportSync.command, args);45 this.output.start(this.process);46 this.emit(ShairportSync.Events.START, this);47 }48}49ShairportSync.Events = {50 START: 'start'51}...
PythonProcess.js
Source:PythonProcess.js
...16 this._process = window.reactopya_client.startPythonProcess(this._componentModule, this._componentName, this._handleProcessMessage);17 }18 else if (window.ReactopyaPythonProcess) {19 this._process = new window.ReactopyaPythonProcess(this._componentModule, this._componentName, this._handleProcessMessage);20 this._process.start();21 }22 else {23 console.error('Found no mechanism to start python process.');24 return;25 }26 }27 stop() {28 if (!this._process) return;29 this._process.stop();30 this._process = null;31 }32 onReceiveMessage(handler) {33 this._receiveMessageHandlers.push(handler);34 }...
TaskQueue.js
Source:TaskQueue.js
1// @flow2export type Task<T> = {3 handler: () => T,4 resolve: T => void,5 reject: Error => void,6};7export class TaskQueue {8 _jobs: Array<Task<any>> = [];9 _running: boolean = false;10 addJob<E>(handler: () => E): Promise<E> {11 return new Promise((resolve: E => void, reject) => {12 this._jobs.push({handler, resolve, reject});13 this._process();14 });15 }16 start = () => {17 this._running = true;18 this._process();19 };20 stop = () => {21 this._running = false;22 };23 _process = () => {24 while (this._running && this._jobs.length) {25 const task = this._jobs.shift();26 try {27 const result = task.handler();28 task.resolve(result);29 } catch (e) {30 task.reject(e);31 }32 }33 };34}...
Using AI Code Generation
1const { spawn } = require('child_process');2const { exec } = require('child_process');3const { execFile } = require('child_process');4var path = require('path');5var fs = require('fs');6var log = require('npmlog');7var _ = require('lodash');8var mkdirp = require('mkdirp');9var B = require('bluebird');10var request = require('request-promise');11var unzip = require('unzip');12var rimraf = require('rimraf');13var xcode = require('appium-xcode');14var teen_process = require('teen_process');15var uuid = require('uuid');16var os = require('os');17var net = require('net');18var plist = require('plist');19var appPlist = require('appium-xcuitest-driver').appPlist;20var appInfo = require('appium-xcuitest-driver').appInfo;21var errors = require('appium-xcuitest-driver').errors;22var IDB = require('appium-idb');23var IDB_EXECUTABLE = require('appium-idb').IDB_EXECUTABLE;24var IDB_COMPLETER = require('appium-idb').IDB_COMPLETER;25var IDB_EXECUTABLE_RELATIVE = require('appium-idb').IDB_EXECUTABLE_RELATIVE;26var IDB_COMPLETER_RELATIVE = require('appium-idb').IDB_COMPLETER_RELATIVE;27var IDB_EXECUTABLE_DEFAULT = require('appium-idb').IDB_EXECUTABLE_DEFAULT;28var IDB_COMPLETER_DEFAULT = require('appium-idb').IDB_COMPLETER_DEFAULT;29var IDB_EXECUTABLE_DEFAULT_RELATIVE = require('appium-idb').IDB_EXECUTABLE_DEFAULT_RELATIVE;30var IDB_COMPLETER_DEFAULT_RELATIVE = require('appium-idb').IDB_COMPLETER_DEFAULT_RELATIVE;31var IDB_EXECUTABLE_DEFAULT_MAC = require('appium-idb').IDB_EXECUTABLE_DEFAULT_MAC;32var IDB_COMPLETER_DEFAULT_MAC = require('appium-idb').IDB_COMPLETER_DEFAULT_MAC;33var IDB_EXECUTABLE_DEFAULT_MAC_RELATIVE = require('appium-idb').IDB_EXECUTABLE_DEFAULT_MAC_RELATIVE;34var IDB_COMPLETER_DEFAULT_MAC_RELATIVE = require('appium-idb').IDB_COMPLETER_DEFAULT_MAC
Using AI Code Generation
1 async start (caps, emitStartingState = true) {2 if (emitStartingState) {3 this.emitStartingEvent();4 }5 const startDetector = new SubProcess('node', [startDetectorPath]);6 this._process = startDetector;7 this._process.on('output', (stdout, stderr) => {8 if (stdout) {9 log.debug(`[XCUITest] xcodebuild: ${stdout}`);10 }11 if (stderr) {12 log.debug(`[XCUITest] xcodebuild: ${stderr}`);13 }14 });15 await this._process.start(0);16 await this._process.stop('SIGINT');17 }18 async start (caps, emitStartingState = true) {19 if (emitStartingState) {20 this.emitStartingEvent();21 }22 const startDetector = new SubProcess('node', [startDetectorPath]);23 this._process = startDetector;24 this._process.on('output', (stdout, stderr) => {25 if (stdout) {26 log.debug(`[XCUITest] xcodebuild: ${stdout}`);27 }28 if (stderr) {29 log.debug(`[XCUITest] xcodebuild: ${stderr}`);30 }31 });32 await this._process.start(0);33 await this._process.stop('SIGINT');34 }35 async start (caps, emitStartingState = true) {36 if (emitStartingState) {37 this.emitStartingEvent();38 }39 const startDetector = new SubProcess('node', [startDetectorPath]);40 this._process = startDetector;41 this._process.on('output', (stdout, stderr) => {42 if (stdout) {43 log.debug(`[XCUITest] xcodebuild: ${stdout}`);44 }45 if (stderr) {46 log.debug(`[XCUITest] xcodebuild: ${stderr}`);47 }48 });
Using AI Code Generation
1let driver = new webdriverio.remote(options);2await driver.init();3await driver.createSession();4await driver._process.start('xcrun', ['simctl', 'list']);5let processOutput = await driver._process.getOutput();6console.log(processOutput);7await driver._process.stop();8await driver.deleteSession();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!