How to use child method in lambdium

Best JavaScript code snippet using lambdium

widget-parent-debug.js

Source:widget-parent-debug.js Github

copy

Full Screen

1/*2YUI 3.16.0 (build 76f0e08)3Copyright 2014 Yahoo! Inc. All rights reserved.4Licensed under the BSD License.5http://yuilibrary.com/license/6*/7YUI.add('widget-parent', function (Y, NAME) {8/**9 * Extension enabling a Widget to be a parent of another Widget.10 *11 * @module widget-parent12 */13var Lang = Y.Lang,14 RENDERED = "rendered",15 BOUNDING_BOX = "boundingBox";16/**17 * Widget extension providing functionality enabling a Widget to be a 18 * parent of another Widget.19 *20 * <p>In addition to the set of attributes supported by WidgetParent, the constructor21 * configuration object can also contain a <code>children</code> which can be used22 * to add child widgets to the parent during construction. The <code>children</code>23 * property is an array of either child widget instances or child widget configuration 24 * objects, and is sugar for the <a href="#method_add">add</a> method. See the 25 * <a href="#method_add">add</a> for details on the structure of the child widget 26 * configuration object.27 * @class WidgetParent28 * @constructor29 * @uses ArrayList30 * @param {Object} config User configuration object.31 */32function Parent(config) {33 /**34 * Fires when a Widget is add as a child. The event object will have a 35 * 'child' property that returns a reference to the child Widget, as well 36 * as an 'index' property that returns a reference to the index specified 37 * when the add() method was called.38 * <p>39 * Subscribers to the "on" moment of this event, will be notified 40 * before a child is added.41 * </p>42 * <p>43 * Subscribers to the "after" moment of this event, will be notified44 * after a child is added.45 * </p>46 *47 * @event addChild48 * @preventable _defAddChildFn49 * @param {EventFacade} e The Event Facade50 */51 this.publish("addChild", { 52 defaultTargetOnly: true,53 defaultFn: this._defAddChildFn 54 });55 /**56 * Fires when a child Widget is removed. The event object will have a 57 * 'child' property that returns a reference to the child Widget, as well 58 * as an 'index' property that returns a reference child's ordinal position.59 * <p>60 * Subscribers to the "on" moment of this event, will be notified 61 * before a child is removed.62 * </p>63 * <p>64 * Subscribers to the "after" moment of this event, will be notified65 * after a child is removed.66 * </p>67 *68 * @event removeChild69 * @preventable _defRemoveChildFn70 * @param {EventFacade} e The Event Facade71 */72 this.publish("removeChild", { 73 defaultTargetOnly: true,74 defaultFn: this._defRemoveChildFn 75 });76 this._items = [];77 var children,78 handle;79 if (config && config.children) {80 children = config.children;81 82 handle = this.after("initializedChange", function (e) {83 this._add(children);84 handle.detach();85 });86 }87 // Widget method overlap88 Y.after(this._renderChildren, this, "renderUI");89 Y.after(this._bindUIParent, this, "bindUI");90 this.after("selectionChange", this._afterSelectionChange);91 this.after("selectedChange", this._afterParentSelectedChange);92 this.after("activeDescendantChange", this._afterActiveDescendantChange);93 this._hDestroyChild = this.after("*:destroy", this._afterDestroyChild);94 this.after("*:focusedChange", this._updateActiveDescendant);95}96Parent.ATTRS = {97 /**98 * @attribute defaultChildType99 * @type {String|Object}100 *101 * @description String representing the default type of the children 102 * managed by this Widget. Can also supply default type as a constructor103 * reference.104 */105 defaultChildType: {106 setter: function (val) {107 108 var returnVal = Y.Attribute.INVALID_VALUE,109 FnConstructor = Lang.isString(val) ? Y[val] : val;110 111 if (Lang.isFunction(FnConstructor)) {112 returnVal = FnConstructor;113 }114 115 return returnVal;116 }117 },118 /**119 * @attribute activeDescendant120 * @type Widget121 * @readOnly122 *123 * @description Returns the Widget's currently focused descendant Widget.124 */125 activeDescendant: { 126 readOnly: true127 },128 /**129 * @attribute multiple130 * @type Boolean131 * @default false132 * @writeOnce 133 *134 * @description Boolean indicating if multiple children can be selected at 135 * once. Whether or not multiple selection is enabled is always delegated136 * to the value of the <code>multiple</code> attribute of the root widget137 * in the object hierarchy.138 */139 multiple: {140 value: false,141 validator: Lang.isBoolean,142 writeOnce: true,143 getter: function (value) {144 var root = this.get("root");145 return (root && root != this) ? root.get("multiple") : value;146 }147 },148 /**149 * @attribute selection150 * @type {ArrayList|Widget}151 * @readOnly 152 *153 * @description Returns the currently selected child Widget. If the 154 * <code>mulitple</code> attribte is set to <code>true</code> will 155 * return an Y.ArrayList instance containing the currently selected 156 * children. If no children are selected, will return null.157 */158 selection: {159 readOnly: true,160 setter: "_setSelection",161 getter: function (value) {162 var selection = Lang.isArray(value) ? 163 (new Y.ArrayList(value)) : value;164 return selection;165 }166 },167 selected: {168 setter: function (value) {169 // Enforces selection behavior on for parent Widgets. Parent's 170 // selected attribute can be set to the following:171 // 0 - Not selected172 // 1 - Fully selected (all children are selected). In order for 173 // all children to be selected, multiple selection must be 174 // enabled. Therefore, you cannot set the "selected" attribute 175 // on a parent Widget to 1 unless multiple selection is enabled.176 // 2 - Partially selected, meaning one ore more (but not all) 177 // children are selected.178 var returnVal = value;179 if (value === 1 && !this.get("multiple")) {180 Y.log('The selected attribute can only be set to 1 if the "multiple" attribute is set to true.', "error", "widget");181 returnVal = Y.Attribute.INVALID_VALUE;182 }183 184 return returnVal;185 }186 }187};188Parent.prototype = {189 /**190 * The destructor implementation for Parent widgets. Destroys all children.191 * @method destructor192 */193 destructor: function() {194 this._destroyChildren();195 },196 /**197 * Destroy event listener for each child Widget, responsible for removing 198 * the destroyed child Widget from the parent's internal array of children199 * (_items property).200 *201 * @method _afterDestroyChild202 * @protected203 * @param {EventFacade} event The event facade for the attribute change.204 */205 _afterDestroyChild: function (event) {206 var child = event.target;207 if (child.get("parent") == this) {208 child.remove();209 } 210 },211 /**212 * Attribute change listener for the <code>selection</code> 213 * attribute, responsible for setting the value of the 214 * parent's <code>selected</code> attribute.215 *216 * @method _afterSelectionChange217 * @protected218 * @param {EventFacade} event The event facade for the attribute change.219 */220 _afterSelectionChange: function (event) {221 if (event.target == this && event.src != this) {222 var selection = event.newVal,223 selectedVal = 0; // Not selected224 if (selection) {225 selectedVal = 2; // Assume partially selected, confirm otherwise226 if (Y.instanceOf(selection, Y.ArrayList) && 227 (selection.size() === this.size())) {228 selectedVal = 1; // Fully selected229 }230 231 }232 this.set("selected", selectedVal, { src: this });233 234 }235 },236 /**237 * Attribute change listener for the <code>activeDescendant</code> 238 * attribute, responsible for setting the value of the 239 * parent's <code>activeDescendant</code> attribute.240 *241 * @method _afterActiveDescendantChange242 * @protected243 * @param {EventFacade} event The event facade for the attribute change.244 */245 _afterActiveDescendantChange: function (event) {246 var parent = this.get("parent");247 if (parent) {248 parent._set("activeDescendant", event.newVal);249 }250 },251 /**252 * Attribute change listener for the <code>selected</code> 253 * attribute, responsible for syncing the selected state of all children to 254 * match that of their parent Widget.255 * 256 *257 * @method _afterParentSelectedChange258 * @protected259 * @param {EventFacade} event The event facade for the attribute change.260 */261 _afterParentSelectedChange: function (event) {262 var value = event.newVal;263 if (this == event.target && event.src != this && 264 (value === 0 || value === 1)) {265 this.each(function (child) {266 // Specify the source of this change as the parent so that 267 // value of the parent's "selection" attribute isn't 268 // recalculated269 child.set("selected", value, { src: this });270 }, this);271 272 }273 274 },275 /**276 * Default setter for <code>selection</code> attribute changes.277 *278 * @method _setSelection279 * @protected280 * @param child {Widget|Array} Widget or Array of Widget instances. 281 * @return {Widget|Array} Widget or Array of Widget instances.282 */283 _setSelection: function (child) {284 var selection = null,285 selected;286 if (this.get("multiple") && !this.isEmpty()) {287 selected = [];288 289 this.each(function (v) {290 if (v.get("selected") > 0) {291 selected.push(v);292 }293 });294 if (selected.length > 0) {295 selection = selected;296 }297 }298 else {299 if (child.get("selected") > 0) {300 selection = child;301 }302 }303 304 return selection;305 306 },307 /**308 * Attribute change listener for the <code>selected</code> 309 * attribute of child Widgets, responsible for setting the value of the 310 * parent's <code>selection</code> attribute.311 *312 * @method _updateSelection313 * @protected314 * @param {EventFacade} event The event facade for the attribute change.315 */316 _updateSelection: function (event) {317 var child = event.target,318 selection;319 if (child.get("parent") == this) {320 if (event.src != "_updateSelection") {321 selection = this.get("selection");322 if (!this.get("multiple") && selection && event.newVal > 0) {323 // Deselect the previously selected child.324 // Set src equal to the current context to prevent325 // unnecessary re-calculation of the selection.326 selection.set("selected", 0, { src: "_updateSelection" });327 }328 this._set("selection", child);329 }330 if (event.src == this) {331 this._set("selection", child, { src: this });332 }333 334 }335 },336 /**337 * Attribute change listener for the <code>focused</code> 338 * attribute of child Widgets, responsible for setting the value of the 339 * parent's <code>activeDescendant</code> attribute.340 *341 * @method _updateActiveDescendant342 * @protected343 * @param {EventFacade} event The event facade for the attribute change.344 */345 _updateActiveDescendant: function (event) {346 var activeDescendant = (event.newVal === true) ? event.target : null;347 this._set("activeDescendant", activeDescendant);348 },349 /**350 * Creates an instance of a child Widget using the specified configuration.351 * By default Widget instances will be created of the type specified 352 * by the <code>defaultChildType</code> attribute. Types can be explicitly353 * defined via the <code>childType</code> property of the configuration object354 * literal. The use of the <code>type</code> property has been deprecated, but 355 * will still be used as a fallback, if <code>childType</code> is not defined,356 * for backwards compatibility. 357 *358 * @method _createChild359 * @protected360 * @param config {Object} Object literal representing the configuration 361 * used to create an instance of a Widget.362 */363 _createChild: function (config) {364 var defaultType = this.get("defaultChildType"),365 altType = config.childType || config.type,366 child,367 Fn,368 FnConstructor;369 if (altType) {370 Fn = Lang.isString(altType) ? Y[altType] : altType;371 }372 if (Lang.isFunction(Fn)) {373 FnConstructor = Fn;374 } else if (defaultType) {375 // defaultType is normalized to a function in it's setter 376 FnConstructor = defaultType;377 }378 if (FnConstructor) {379 child = new FnConstructor(config);380 } else {381 Y.error("Could not create a child instance because its constructor is either undefined or invalid.");382 }383 return child;384 385 },386 /**387 * Default addChild handler388 *389 * @method _defAddChildFn390 * @protected391 * @param event {EventFacade} The Event object392 * @param child {Widget} The Widget instance, or configuration 393 * object for the Widget to be added as a child.394 * @param index {Number} Number representing the position at 395 * which the child will be inserted.396 */397 _defAddChildFn: function (event) {398 var child = event.child,399 index = event.index,400 children = this._items;401 if (child.get("parent")) {402 child.remove();403 }404 if (Lang.isNumber(index)) {405 children.splice(index, 0, child);406 }407 else {408 children.push(child);409 }410 child._set("parent", this);411 child.addTarget(this);412 // Update index in case it got normalized after addition413 // (e.g. user passed in 10, and there are only 3 items, the actual index would be 3. We don't want to pass 10 around in the event facade).414 event.index = child.get("index");415 // TO DO: Remove in favor of using event bubbling416 child.after("selectedChange", Y.bind(this._updateSelection, this));417 },418 /**419 * Default removeChild handler420 *421 * @method _defRemoveChildFn422 * @protected423 * @param event {EventFacade} The Event object424 * @param child {Widget} The Widget instance to be removed.425 * @param index {Number} Number representing the index of the Widget to 426 * be removed.427 */ 428 _defRemoveChildFn: function (event) {429 var child = event.child,430 index = event.index,431 children = this._items;432 if (child.get("focused")) {433 child.blur(); // focused is readOnly, so use the public i/f to unset it434 }435 if (child.get("selected")) {436 child.set("selected", 0);437 }438 children.splice(index, 1);439 child.removeTarget(this);440 child._oldParent = child.get("parent");441 child._set("parent", null);442 },443 /**444 * @method _add445 * @protected446 * @param child {Widget|Object} The Widget instance, or configuration 447 * object for the Widget to be added as a child.448 * @param child {Array} Array of Widget instances, or configuration 449 * objects for the Widgets to be added as a children.450 * @param index {Number} (Optional.) Number representing the position at 451 * which the child should be inserted.452 * @description Adds a Widget as a child. If the specified Widget already453 * has a parent it will be removed from its current parent before454 * being added as a child.455 * @return {Widget|Array} Successfully added Widget or Array containing the 456 * successfully added Widget instance(s). If no children where added, will 457 * will return undefined.458 */459 _add: function (child, index) { 460 var children,461 oChild,462 returnVal;463 if (Lang.isArray(child)) {464 children = [];465 Y.each(child, function (v, k) {466 oChild = this._add(v, (index + k));467 if (oChild) {468 children.push(oChild);469 }470 471 }, this);472 473 if (children.length > 0) {474 returnVal = children;475 }476 }477 else {478 if (Y.instanceOf(child, Y.Widget)) {479 oChild = child;480 }481 else {482 oChild = this._createChild(child);483 }484 if (oChild && this.fire("addChild", { child: oChild, index: index })) {485 returnVal = oChild;486 }487 }488 return returnVal;489 },490 /**491 * @method add492 * @param child {Widget|Object} The Widget instance, or configuration 493 * object for the Widget to be added as a child. The configuration object494 * for the child can include a <code>childType</code> property, which is either495 * a constructor function or a string which names a constructor function on the 496 * Y instance (e.g. "Tab" would refer to Y.Tab) (<code>childType</code> used to be 497 * named <code>type</code>, support for which has been deprecated, but is still498 * maintained for backward compatibility. <code>childType</code> takes precedence499 * over <code>type</code> if both are defined.500 * @param child {Array} Array of Widget instances, or configuration 501 * objects for the Widgets to be added as a children.502 * @param index {Number} (Optional.) Number representing the position at 503 * which the child should be inserted.504 * @description Adds a Widget as a child. If the specified Widget already505 * has a parent it will be removed from its current parent before506 * being added as a child.507 * @return {ArrayList} Y.ArrayList containing the successfully added 508 * Widget instance(s). If no children where added, will return an empty 509 * Y.ArrayList instance.510 */511 add: function () {512 var added = this._add.apply(this, arguments),513 children = added ? (Lang.isArray(added) ? added : [added]) : [];514 return (new Y.ArrayList(children));515 },516 /**517 * @method remove518 * @param index {Number} (Optional.) Number representing the index of the 519 * child to be removed.520 * @description Removes the Widget from its parent. Optionally, can remove521 * a child by specifying its index.522 * @return {Widget} Widget instance that was successfully removed, otherwise523 * undefined.524 */525 remove: function (index) {526 var child = this._items[index],527 returnVal;528 if (child && this.fire("removeChild", { child: child, index: index })) {529 returnVal = child;530 }531 532 return returnVal;533 },534 /**535 * @method removeAll536 * @description Removes all of the children from the Widget.537 * @return {ArrayList} Y.ArrayList instance containing Widgets that were 538 * successfully removed. If no children where removed, will return an empty 539 * Y.ArrayList instance.540 */541 removeAll: function () {542 var removed = [],543 child;544 Y.each(this._items.concat(), function () {545 child = this.remove(0);546 if (child) {547 removed.push(child);548 }549 }, this);550 return (new Y.ArrayList(removed));551 },552 553 /**554 * Selects the child at the given index (zero-based).555 *556 * @method selectChild557 * @param {Number} i the index of the child to be selected558 */559 selectChild: function(i) {560 this.item(i).set('selected', 1);561 },562 /**563 * Selects all children.564 *565 * @method selectAll566 */567 selectAll: function () {568 this.set("selected", 1);569 },570 /**571 * Deselects all children.572 *573 * @method deselectAll574 */575 deselectAll: function () {576 this.set("selected", 0);577 },578 /**579 * Updates the UI in response to a child being added.580 *581 * @method _uiAddChild582 * @protected583 * @param child {Widget} The child Widget instance to render.584 * @param parentNode {Object} The Node under which the 585 * child Widget is to be rendered.586 */ 587 _uiAddChild: function (child, parentNode) {588 child.render(parentNode);589 // TODO: Ideally this should be in Child's render UI. 590 var childBB = child.get("boundingBox"),591 siblingBB,592 nextSibling = child.next(false),593 prevSibling;594 // Insert or Append to last child.595 // Avoiding index, and using the current sibling 596 // state (which should be accurate), means we don't have 597 // to worry about decorator elements which may be added 598 // to the _childContainer node.599 600 if (nextSibling && nextSibling.get(RENDERED)) {601 siblingBB = nextSibling.get(BOUNDING_BOX);602 siblingBB.insert(childBB, "before");603 } else {604 prevSibling = child.previous(false);605 if (prevSibling && prevSibling.get(RENDERED)) {606 siblingBB = prevSibling.get(BOUNDING_BOX);607 siblingBB.insert(childBB, "after");608 } else if (!parentNode.contains(childBB)) {609 // Based on pull request from andreas-karlsson610 // https://github.com/yui/yui3/pull/25#issuecomment-2103536611 // Account for case where a child was rendered independently of the 612 // parent-child framework, to a node outside of the parentNode,613 // and there are no siblings.614 parentNode.appendChild(childBB);615 }616 }617 },618 /**619 * Updates the UI in response to a child being removed.620 *621 * @method _uiRemoveChild622 * @protected623 * @param child {Widget} The child Widget instance to render.624 */ 625 _uiRemoveChild: function (child) {626 child.get("boundingBox").remove();627 },628 _afterAddChild: function (event) {629 var child = event.child;630 if (child.get("parent") == this) {631 this._uiAddChild(child, this._childrenContainer);632 }633 },634 _afterRemoveChild: function (event) {635 var child = event.child;636 if (child._oldParent == this) {637 this._uiRemoveChild(child);638 }639 },640 /**641 * Sets up DOM and CustomEvent listeners for the parent widget.642 * <p>643 * This method in invoked after bindUI is invoked for the Widget class644 * using YUI's aop infrastructure.645 * </p>646 *647 * @method _bindUIParent648 * @protected649 */650 _bindUIParent: function () {651 this.after("addChild", this._afterAddChild);652 this.after("removeChild", this._afterRemoveChild);653 },654 /**655 * Renders all child Widgets for the parent.656 * <p>657 * This method in invoked after renderUI is invoked for the Widget class658 * using YUI's aop infrastructure.659 * </p>660 * @method _renderChildren661 * @protected662 */663 _renderChildren: function () {664 /**665 * <p>By default WidgetParent will render it's children to the parent's content box.</p>666 *667 * <p>If the children need to be rendered somewhere else, the _childrenContainer property668 * can be set to the Node which the children should be rendered to. This property should be669 * set before the _renderChildren method is invoked, ideally in your renderUI method, 670 * as soon as you create the element to be rendered to.</p>671 *672 * @protected673 * @property _childrenContainer674 * @value The content box675 * @type Node676 */677 var renderTo = this._childrenContainer || this.get("contentBox");678 this._childrenContainer = renderTo;679 this.each(function (child) {680 child.render(renderTo);681 });682 },683 /**684 * Destroys all child Widgets for the parent.685 * <p>686 * This method is invoked before the destructor is invoked for the Widget 687 * class using YUI's aop infrastructure.688 * </p>689 * @method _destroyChildren690 * @protected691 */692 _destroyChildren: function () {693 // Detach the handler responsible for removing children in 694 // response to destroying them since:695 // 1) It is unnecessary/inefficient at this point since we are doing 696 // a batch destroy of all children.697 // 2) Removing each child will affect our ability to iterate the 698 // children since the size of _items will be changing as we 699 // iterate.700 this._hDestroyChild.detach();701 // Need to clone the _items array since 702 this.each(function (child) {703 child.destroy();704 });705 }706 707};708Y.augment(Parent, Y.ArrayList);709Y.WidgetParent = Parent;...

Full Screen

Full Screen

widget-parent.js

Source:widget-parent.js Github

copy

Full Screen

1/*2YUI 3.17.2 (build 9c3c78e)3Copyright 2014 Yahoo! Inc. All rights reserved.4Licensed under the BSD License.5http://yuilibrary.com/license/6*/7YUI.add('widget-parent', function (Y, NAME) {8/**9 * Extension enabling a Widget to be a parent of another Widget.10 *11 * @module widget-parent12 */13var Lang = Y.Lang,14 RENDERED = "rendered",15 BOUNDING_BOX = "boundingBox";16/**17 * Widget extension providing functionality enabling a Widget to be a18 * parent of another Widget.19 *20 * <p>In addition to the set of attributes supported by WidgetParent, the constructor21 * configuration object can also contain a <code>children</code> which can be used22 * to add child widgets to the parent during construction. The <code>children</code>23 * property is an array of either child widget instances or child widget configuration24 * objects, and is sugar for the <a href="#method_add">add</a> method. See the25 * <a href="#method_add">add</a> for details on the structure of the child widget26 * configuration object.27 * @class WidgetParent28 * @constructor29 * @uses ArrayList30 * @param {Object} config User configuration object.31 */32function Parent(config) {33 /**34 * Fires when a Widget is add as a child. The event object will have a35 * 'child' property that returns a reference to the child Widget, as well36 * as an 'index' property that returns a reference to the index specified37 * when the add() method was called.38 * <p>39 * Subscribers to the "on" moment of this event, will be notified40 * before a child is added.41 * </p>42 * <p>43 * Subscribers to the "after" moment of this event, will be notified44 * after a child is added.45 * </p>46 *47 * @event addChild48 * @preventable _defAddChildFn49 * @param {EventFacade} e The Event Facade50 */51 this.publish("addChild", {52 defaultTargetOnly: true,53 defaultFn: this._defAddChildFn54 });55 /**56 * Fires when a child Widget is removed. The event object will have a57 * 'child' property that returns a reference to the child Widget, as well58 * as an 'index' property that returns a reference child's ordinal position.59 * <p>60 * Subscribers to the "on" moment of this event, will be notified61 * before a child is removed.62 * </p>63 * <p>64 * Subscribers to the "after" moment of this event, will be notified65 * after a child is removed.66 * </p>67 *68 * @event removeChild69 * @preventable _defRemoveChildFn70 * @param {EventFacade} e The Event Facade71 */72 this.publish("removeChild", {73 defaultTargetOnly: true,74 defaultFn: this._defRemoveChildFn75 });76 this._items = [];77 var children,78 handle;79 if (config && config.children) {80 children = config.children;81 handle = this.after("initializedChange", function (e) {82 this._add(children);83 handle.detach();84 });85 }86 // Widget method overlap87 Y.after(this._renderChildren, this, "renderUI");88 Y.after(this._bindUIParent, this, "bindUI");89 this.after("selectionChange", this._afterSelectionChange);90 this.after("selectedChange", this._afterParentSelectedChange);91 this.after("activeDescendantChange", this._afterActiveDescendantChange);92 this._hDestroyChild = this.after("*:destroy", this._afterDestroyChild);93 this.after("*:focusedChange", this._updateActiveDescendant);94}95Parent.ATTRS = {96 /**97 * @attribute defaultChildType98 * @type {String|Object}99 *100 * @description String representing the default type of the children101 * managed by this Widget. Can also supply default type as a constructor102 * reference.103 */104 defaultChildType: {105 setter: function (val) {106 var returnVal = Y.Attribute.INVALID_VALUE,107 FnConstructor = Lang.isString(val) ? Y[val] : val;108 if (Lang.isFunction(FnConstructor)) {109 returnVal = FnConstructor;110 }111 return returnVal;112 }113 },114 /**115 * @attribute activeDescendant116 * @type Widget117 * @readOnly118 *119 * @description Returns the Widget's currently focused descendant Widget.120 */121 activeDescendant: {122 readOnly: true123 },124 /**125 * @attribute multiple126 * @type Boolean127 * @default false128 * @writeOnce129 *130 * @description Boolean indicating if multiple children can be selected at131 * once. Whether or not multiple selection is enabled is always delegated132 * to the value of the <code>multiple</code> attribute of the root widget133 * in the object hierarchy.134 */135 multiple: {136 value: false,137 validator: Lang.isBoolean,138 writeOnce: true,139 getter: function (value) {140 var root = this.get("root");141 return (root && root != this) ? root.get("multiple") : value;142 }143 },144 /**145 * @attribute selection146 * @type {ArrayList|Widget}147 * @readOnly148 *149 * @description Returns the currently selected child Widget. If the150 * <code>mulitple</code> attribte is set to <code>true</code> will151 * return an Y.ArrayList instance containing the currently selected152 * children. If no children are selected, will return null.153 */154 selection: {155 readOnly: true,156 setter: "_setSelection",157 getter: function (value) {158 var selection = Lang.isArray(value) ?159 (new Y.ArrayList(value)) : value;160 return selection;161 }162 },163 selected: {164 setter: function (value) {165 // Enforces selection behavior on for parent Widgets. Parent's166 // selected attribute can be set to the following:167 // 0 - Not selected168 // 1 - Fully selected (all children are selected). In order for169 // all children to be selected, multiple selection must be170 // enabled. Therefore, you cannot set the "selected" attribute171 // on a parent Widget to 1 unless multiple selection is enabled.172 // 2 - Partially selected, meaning one ore more (but not all)173 // children are selected.174 var returnVal = value;175 if (value === 1 && !this.get("multiple")) {176 returnVal = Y.Attribute.INVALID_VALUE;177 }178 return returnVal;179 }180 }181};182Parent.prototype = {183 /**184 * The destructor implementation for Parent widgets. Destroys all children.185 * @method destructor186 */187 destructor: function() {188 this._destroyChildren();189 },190 /**191 * Destroy event listener for each child Widget, responsible for removing192 * the destroyed child Widget from the parent's internal array of children193 * (_items property).194 *195 * @method _afterDestroyChild196 * @protected197 * @param {EventFacade} event The event facade for the attribute change.198 */199 _afterDestroyChild: function (event) {200 var child = event.target;201 if (child.get("parent") == this) {202 child.remove();203 }204 },205 /**206 * Attribute change listener for the <code>selection</code>207 * attribute, responsible for setting the value of the208 * parent's <code>selected</code> attribute.209 *210 * @method _afterSelectionChange211 * @protected212 * @param {EventFacade} event The event facade for the attribute change.213 */214 _afterSelectionChange: function (event) {215 if (event.target == this && event.src != this) {216 var selection = event.newVal,217 selectedVal = 0; // Not selected218 if (selection) {219 selectedVal = 2; // Assume partially selected, confirm otherwise220 if (Y.instanceOf(selection, Y.ArrayList) &&221 (selection.size() === this.size())) {222 selectedVal = 1; // Fully selected223 }224 }225 this.set("selected", selectedVal, { src: this });226 }227 },228 /**229 * Attribute change listener for the <code>activeDescendant</code>230 * attribute, responsible for setting the value of the231 * parent's <code>activeDescendant</code> attribute.232 *233 * @method _afterActiveDescendantChange234 * @protected235 * @param {EventFacade} event The event facade for the attribute change.236 */237 _afterActiveDescendantChange: function (event) {238 var parent = this.get("parent");239 if (parent) {240 parent._set("activeDescendant", event.newVal);241 }242 },243 /**244 * Attribute change listener for the <code>selected</code>245 * attribute, responsible for syncing the selected state of all children to246 * match that of their parent Widget.247 *248 *249 * @method _afterParentSelectedChange250 * @protected251 * @param {EventFacade} event The event facade for the attribute change.252 */253 _afterParentSelectedChange: function (event) {254 var value = event.newVal;255 if (this == event.target && event.src != this &&256 (value === 0 || value === 1)) {257 this.each(function (child) {258 // Specify the source of this change as the parent so that259 // value of the parent's "selection" attribute isn't260 // recalculated261 child.set("selected", value, { src: this });262 }, this);263 }264 },265 /**266 * Default setter for <code>selection</code> attribute changes.267 *268 * @method _setSelection269 * @protected270 * @param child {Widget|Array} Widget or Array of Widget instances.271 * @return {Widget|Array} Widget or Array of Widget instances.272 */273 _setSelection: function (child) {274 var selection = null,275 selected;276 if (this.get("multiple") && !this.isEmpty()) {277 selected = [];278 this.each(function (v) {279 if (v.get("selected") > 0) {280 selected.push(v);281 }282 });283 if (selected.length > 0) {284 selection = selected;285 }286 }287 else {288 if (child.get("selected") > 0) {289 selection = child;290 }291 }292 return selection;293 },294 /**295 * Attribute change listener for the <code>selected</code>296 * attribute of child Widgets, responsible for setting the value of the297 * parent's <code>selection</code> attribute.298 *299 * @method _updateSelection300 * @protected301 * @param {EventFacade} event The event facade for the attribute change.302 */303 _updateSelection: function (event) {304 var child = event.target,305 selection;306 if (child.get("parent") == this) {307 if (event.src != "_updateSelection") {308 selection = this.get("selection");309 if (!this.get("multiple") && selection && event.newVal > 0) {310 // Deselect the previously selected child.311 // Set src equal to the current context to prevent312 // unnecessary re-calculation of the selection.313 selection.set("selected", 0, { src: "_updateSelection" });314 }315 this._set("selection", child);316 }317 if (event.src == this) {318 this._set("selection", child, { src: this });319 }320 }321 },322 /**323 * Attribute change listener for the <code>focused</code>324 * attribute of child Widgets, responsible for setting the value of the325 * parent's <code>activeDescendant</code> attribute.326 *327 * @method _updateActiveDescendant328 * @protected329 * @param {EventFacade} event The event facade for the attribute change.330 */331 _updateActiveDescendant: function (event) {332 var activeDescendant = (event.newVal === true) ? event.target : null;333 this._set("activeDescendant", activeDescendant);334 },335 /**336 * Creates an instance of a child Widget using the specified configuration.337 * By default Widget instances will be created of the type specified338 * by the <code>defaultChildType</code> attribute. Types can be explicitly339 * defined via the <code>childType</code> property of the configuration object340 * literal. The use of the <code>type</code> property has been deprecated, but341 * will still be used as a fallback, if <code>childType</code> is not defined,342 * for backwards compatibility.343 *344 * @method _createChild345 * @protected346 * @param config {Object} Object literal representing the configuration347 * used to create an instance of a Widget.348 */349 _createChild: function (config) {350 var defaultType = this.get("defaultChildType"),351 altType = config.childType || config.type,352 child,353 Fn,354 FnConstructor;355 if (altType) {356 Fn = Lang.isString(altType) ? Y[altType] : altType;357 }358 if (Lang.isFunction(Fn)) {359 FnConstructor = Fn;360 } else if (defaultType) {361 // defaultType is normalized to a function in it's setter362 FnConstructor = defaultType;363 }364 if (FnConstructor) {365 child = new FnConstructor(config);366 } else {367 Y.error("Could not create a child instance because its constructor is either undefined or invalid.");368 }369 return child;370 },371 /**372 * Default addChild handler373 *374 * @method _defAddChildFn375 * @protected376 * @param event {EventFacade} The Event object377 * @param child {Widget} The Widget instance, or configuration378 * object for the Widget to be added as a child.379 * @param index {Number} Number representing the position at380 * which the child will be inserted.381 */382 _defAddChildFn: function (event) {383 var child = event.child,384 index = event.index,385 children = this._items;386 if (child.get("parent")) {387 child.remove();388 }389 if (Lang.isNumber(index)) {390 children.splice(index, 0, child);391 }392 else {393 children.push(child);394 }395 child._set("parent", this);396 child.addTarget(this);397 // Update index in case it got normalized after addition398 // (e.g. user passed in 10, and there are only 3 items, the actual index would be 3. We don't want to pass 10 around in the event facade).399 event.index = child.get("index");400 // TO DO: Remove in favor of using event bubbling401 child.after("selectedChange", Y.bind(this._updateSelection, this));402 },403 /**404 * Default removeChild handler405 *406 * @method _defRemoveChildFn407 * @protected408 * @param event {EventFacade} The Event object409 * @param child {Widget} The Widget instance to be removed.410 * @param index {Number} Number representing the index of the Widget to411 * be removed.412 */413 _defRemoveChildFn: function (event) {414 var child = event.child,415 index = event.index,416 children = this._items;417 if (child.get("focused")) {418 child.blur(); // focused is readOnly, so use the public i/f to unset it419 }420 if (child.get("selected")) {421 child.set("selected", 0);422 }423 children.splice(index, 1);424 child.removeTarget(this);425 child._oldParent = child.get("parent");426 child._set("parent", null);427 },428 /**429 * @method _add430 * @protected431 * @param child {Widget|Object} The Widget instance, or configuration432 * object for the Widget to be added as a child.433 * @param child {Array} Array of Widget instances, or configuration434 * objects for the Widgets to be added as a children.435 * @param index {Number} (Optional.) Number representing the position at436 * which the child should be inserted.437 * @description Adds a Widget as a child. If the specified Widget already438 * has a parent it will be removed from its current parent before439 * being added as a child.440 * @return {Widget|Array} Successfully added Widget or Array containing the441 * successfully added Widget instance(s). If no children where added, will442 * will return undefined.443 */444 _add: function (child, index) {445 var children,446 oChild,447 returnVal;448 if (Lang.isArray(child)) {449 children = [];450 Y.each(child, function (v, k) {451 oChild = this._add(v, (index + k));452 if (oChild) {453 children.push(oChild);454 }455 }, this);456 if (children.length > 0) {457 returnVal = children;458 }459 }460 else {461 if (Y.instanceOf(child, Y.Widget)) {462 oChild = child;463 }464 else {465 oChild = this._createChild(child);466 }467 if (oChild && this.fire("addChild", { child: oChild, index: index })) {468 returnVal = oChild;469 }470 }471 return returnVal;472 },473 /**474 * @method add475 * @param child {Widget|Object} The Widget instance, or configuration476 * object for the Widget to be added as a child. The configuration object477 * for the child can include a <code>childType</code> property, which is either478 * a constructor function or a string which names a constructor function on the479 * Y instance (e.g. "Tab" would refer to Y.Tab) (<code>childType</code> used to be480 * named <code>type</code>, support for which has been deprecated, but is still481 * maintained for backward compatibility. <code>childType</code> takes precedence482 * over <code>type</code> if both are defined.483 * @param child {Array} Array of Widget instances, or configuration484 * objects for the Widgets to be added as a children.485 * @param index {Number} (Optional.) Number representing the position at486 * which the child should be inserted.487 * @description Adds a Widget as a child. If the specified Widget already488 * has a parent it will be removed from its current parent before489 * being added as a child.490 * @return {ArrayList} Y.ArrayList containing the successfully added491 * Widget instance(s). If no children where added, will return an empty492 * Y.ArrayList instance.493 */494 add: function () {495 var added = this._add.apply(this, arguments),496 children = added ? (Lang.isArray(added) ? added : [added]) : [];497 return (new Y.ArrayList(children));498 },499 /**500 * @method remove501 * @param index {Number} (Optional.) Number representing the index of the502 * child to be removed.503 * @description Removes the Widget from its parent. Optionally, can remove504 * a child by specifying its index.505 * @return {Widget} Widget instance that was successfully removed, otherwise506 * undefined.507 */508 remove: function (index) {509 var child = this._items[index],510 returnVal;511 if (child && this.fire("removeChild", { child: child, index: index })) {512 returnVal = child;513 }514 return returnVal;515 },516 /**517 * @method removeAll518 * @description Removes all of the children from the Widget.519 * @return {ArrayList} Y.ArrayList instance containing Widgets that were520 * successfully removed. If no children where removed, will return an empty521 * Y.ArrayList instance.522 */523 removeAll: function () {524 var removed = [],525 child;526 Y.each(this._items.concat(), function () {527 child = this.remove(0);528 if (child) {529 removed.push(child);530 }531 }, this);532 return (new Y.ArrayList(removed));533 },534 /**535 * Selects the child at the given index (zero-based).536 *537 * @method selectChild538 * @param {Number} i the index of the child to be selected539 */540 selectChild: function(i) {541 this.item(i).set('selected', 1);542 },543 /**544 * Selects all children.545 *546 * @method selectAll547 */548 selectAll: function () {549 this.set("selected", 1);550 },551 /**552 * Deselects all children.553 *554 * @method deselectAll555 */556 deselectAll: function () {557 this.set("selected", 0);558 },559 /**560 * Updates the UI in response to a child being added.561 *562 * @method _uiAddChild563 * @protected564 * @param child {Widget} The child Widget instance to render.565 * @param parentNode {Object} The Node under which the566 * child Widget is to be rendered.567 */568 _uiAddChild: function (child, parentNode) {569 child.render(parentNode);570 // TODO: Ideally this should be in Child's render UI.571 var childBB = child.get("boundingBox"),572 siblingBB,573 nextSibling = child.next(false),574 prevSibling;575 // Insert or Append to last child.576 // Avoiding index, and using the current sibling577 // state (which should be accurate), means we don't have578 // to worry about decorator elements which may be added579 // to the _childContainer node.580 if (nextSibling && nextSibling.get(RENDERED)) {581 siblingBB = nextSibling.get(BOUNDING_BOX);582 siblingBB.insert(childBB, "before");583 } else {584 prevSibling = child.previous(false);585 if (prevSibling && prevSibling.get(RENDERED)) {586 siblingBB = prevSibling.get(BOUNDING_BOX);587 siblingBB.insert(childBB, "after");588 } else if (!parentNode.contains(childBB)) {589 // Based on pull request from andreas-karlsson590 // https://github.com/yui/yui3/pull/25#issuecomment-2103536591 // Account for case where a child was rendered independently of the592 // parent-child framework, to a node outside of the parentNode,593 // and there are no siblings.594 parentNode.appendChild(childBB);595 }596 }597 },598 /**599 * Updates the UI in response to a child being removed.600 *601 * @method _uiRemoveChild602 * @protected603 * @param child {Widget} The child Widget instance to render.604 */605 _uiRemoveChild: function (child) {606 child.get("boundingBox").remove();607 },608 _afterAddChild: function (event) {609 var child = event.child;610 if (child.get("parent") == this) {611 this._uiAddChild(child, this._childrenContainer);612 }613 },614 _afterRemoveChild: function (event) {615 var child = event.child;616 if (child._oldParent == this) {617 this._uiRemoveChild(child);618 }619 },620 /**621 * Sets up DOM and CustomEvent listeners for the parent widget.622 * <p>623 * This method in invoked after bindUI is invoked for the Widget class624 * using YUI's aop infrastructure.625 * </p>626 *627 * @method _bindUIParent628 * @protected629 */630 _bindUIParent: function () {631 this.after("addChild", this._afterAddChild);632 this.after("removeChild", this._afterRemoveChild);633 },634 /**635 * Renders all child Widgets for the parent.636 * <p>637 * This method in invoked after renderUI is invoked for the Widget class638 * using YUI's aop infrastructure.639 * </p>640 * @method _renderChildren641 * @protected642 */643 _renderChildren: function () {644 /**645 * <p>By default WidgetParent will render it's children to the parent's content box.</p>646 *647 * <p>If the children need to be rendered somewhere else, the _childrenContainer property648 * can be set to the Node which the children should be rendered to. This property should be649 * set before the _renderChildren method is invoked, ideally in your renderUI method,650 * as soon as you create the element to be rendered to.</p>651 *652 * @protected653 * @property _childrenContainer654 * @value The content box655 * @type Node656 */657 var renderTo = this._childrenContainer || this.get("contentBox");658 this._childrenContainer = renderTo;659 this.each(function (child) {660 child.render(renderTo);661 });662 },663 /**664 * Destroys all child Widgets for the parent.665 * <p>666 * This method is invoked before the destructor is invoked for the Widget667 * class using YUI's aop infrastructure.668 * </p>669 * @method _destroyChildren670 * @protected671 */672 _destroyChildren: function () {673 // Detach the handler responsible for removing children in674 // response to destroying them since:675 // 1) It is unnecessary/inefficient at this point since we are doing676 // a batch destroy of all children.677 // 2) Removing each child will affect our ability to iterate the678 // children since the size of _items will be changing as we679 // iterate.680 this._hDestroyChild.detach();681 // Need to clone the _items array since682 this.each(function (child) {683 child.destroy();684 });685 }686};687Y.augment(Parent, Y.ArrayList);688Y.WidgetParent = Parent;...

Full Screen

Full Screen

DTxml_Parser.py

Source:DTxml_Parser.py Github

copy

Full Screen

1import xml.etree.ElementTree as ET 2from xml.dom.minidom import Document 3import os 4import cv2 5import time 6 7def ConvertVOCXml(file_path="",file_name=""): 8 tree = ET.parse(file_name) 9 root = tree.getroot() 10 # print(root.tag) 11 12 num=0 #计数 13 #读xml操作 14 15 frame_lists=[] 16 output_file_name="" 17 for child in root: 18 19 if(child.tag=="frame"): 20 # 创建dom文档 21 doc = Document() 22 # 创建根节点 23 annotation = doc.createElement('annotation') 24 # 根节点插入dom树 25 doc.appendChild(annotation) 26 27 #print(child.tag, child.attrib["num"]) 28 pic_id= child.attrib["num"].zfill(5) 29 #print(pic_id) 30 output_file_name=root.attrib["name"]+"__img"+pic_id+".xml" 31 # print(output_file_name) 32 33 folder = doc.createElement("folder") 34 folder.appendChild(doc.createTextNode("VOC2007")) 35 annotation.appendChild(folder) 36 37 filename = doc.createElement("filename") 38 pic_name="img"+pic_id+".jpg" 39 filename.appendChild(doc.createTextNode(pic_name)) 40 annotation.appendChild(filename) 41 42 sizeimage = doc.createElement("size") 43 imagewidth = doc.createElement("width") 44 imageheight = doc.createElement("height") 45 imagedepth = doc.createElement("depth") 46 47 imagewidth.appendChild(doc.createTextNode("960")) 48 imageheight.appendChild(doc.createTextNode("540")) 49 imagedepth.appendChild(doc.createTextNode("3")) 50 51 sizeimage.appendChild(imagedepth) 52 sizeimage.appendChild(imagewidth) 53 sizeimage.appendChild(imageheight) 54 annotation.appendChild(sizeimage) 55 56 target_list=child.getchildren()[0] #获取target_list 57 #print(target_list.tag) 58 object=None 59 for target in target_list: 60 if(target.tag=="target"): 61 #print(target.tag) 62 object = doc.createElement('object') 63 bndbox = doc.createElement("bndbox") 64 65 for target_child in target: 66 if(target_child.tag=="box"): 67 xmin = doc.createElement("xmin") 68 ymin = doc.createElement("ymin") 69 xmax = doc.createElement("xmax") 70 ymax = doc.createElement("ymax") 71 xmin_value=int(float(target_child.attrib["left"])) 72 ymin_value=int(float(target_child.attrib["top"])) 73 box_width_value=int(float(target_child.attrib["width"])) 74 box_height_value=int(float(target_child.attrib["height"])) 75 xmin.appendChild(doc.createTextNode(str(xmin_value))) 76 ymin.appendChild(doc.createTextNode(str(ymin_value))) 77 if(xmin_value+box_width_value>960): 78 xmax.appendChild(doc.createTextNode(str(960))) 79 else: 80 xmax.appendChild(doc.createTextNode(str(xmin_value+box_width_value))) 81 if(ymin_value+box_height_value>540): 82 ymax.appendChild(doc.createTextNode(str(540))) 83 else: 84 ymax.appendChild(doc.createTextNode(str(ymin_value+box_height_value))) 85 86 if(target_child.tag=="attribute"): 87 name = doc.createElement('name') 88 pose=doc.createElement('pose') 89 truncated=doc.createElement('truncated') 90 difficult=doc.createElement('difficult') 91 92 TYPE= target_child.attrib['vehicle_type']93 name.appendChild(doc.createTextNode(TYPE)) 94 pose.appendChild(doc.createTextNode("Left")) #随意指定 95 truncated.appendChild(doc.createTextNode("0")) #随意指定 96 difficult.appendChild(doc.createTextNode("0")) #随意指定 97 98 99 object.appendChild(name) 100 object.appendChild(pose) 101 object.appendChild(truncated) 102 object.appendChild(difficult) 103 104 bndbox.appendChild(xmin) 105 bndbox.appendChild(ymin) 106 bndbox.appendChild(xmax) 107 bndbox.appendChild(ymax) 108 object.appendChild(bndbox) 109 annotation.appendChild(object) 110 111 112 file_path_out=os.path.join(file_path,output_file_name) 113 f = open(file_path_out, 'w') 114 f.write(doc.toprettyxml(indent=' ' * 4)) 115 f.close() 116 num=num+1 117 return num 118 119 120 121 122''''' 123画方框 124''' 125def bboxes_draw_on_img(img, bbox, color=[255, 0, 0], thickness=2): 126 127 # Draw bounding box... 128 print(bbox) 129 p1 = (int(float(bbox["xmin"])), int(float(bbox["ymin"]))) 130 p2 = (int(float(bbox["xmax"])), int(float(bbox["ymax"]))) 131 cv2.rectangle(img, p1, p2, color, thickness) 132 133 134def visualization_image(image_name,xml_file_name): 135 tree = ET.parse(xml_file_name) 136 root = tree.getroot() 137 138 object_lists=[] 139 for child in root: 140 if(child.tag=="folder"): 141 print(child.tag, child.text) 142 elif (child.tag == "filename"): 143 print(child.tag, child.text) 144 elif (child.tag == "size"): #解析size 145 for size_child in child: 146 if(size_child.tag=="width"): 147 print(size_child.tag,size_child.text) 148 elif (size_child.tag == "height"): 149 print(size_child.tag, size_child.text) 150 elif (size_child.tag == "depth"): 151 print(size_child.tag, size_child.text) 152 elif (child.tag == "object"): #解析object 153 singleObject={} 154 for object_child in child: 155 if (object_child.tag == "name"): 156 # print(object_child.tag,object_child.text) 157 singleObject["name"] = object_child.text 158 elif (object_child.tag == "bndbox"): 159 for bndbox_child in object_child: 160 if (bndbox_child.tag == "xmin"): 161 singleObject["xmin"] = bndbox_child.text 162 # print(bndbox_child.tag, bndbox_child.text) 163 elif (bndbox_child.tag == "ymin"): 164 # print(bndbox_child.tag, bndbox_child.text) 165 singleObject["ymin"] = bndbox_child.text 166 elif (bndbox_child.tag == "xmax"): 167 singleObject["xmax"] = bndbox_child.text 168 elif (bndbox_child.tag == "ymax"): 169 singleObject["ymax"] = bndbox_child.text 170 object_length=len(singleObject) 171 if(object_length>0): 172 object_lists.append(singleObject) 173 img = cv2.imread(image_name) 174 for object_coordinate in object_lists: 175 bboxes_draw_on_img(img,object_coordinate) 176 cv2.imshow("capture", img) 177 cv2.waitKey (0) 178 cv2.destroyAllWindows() 179 180 181if ( __name__ == "__main__"): 182 #print("main") 183 basePath="DETRAC-Train-Annotations-XML" 184 totalxml=os.listdir(basePath) 185 total_num=0 186 flag=False 187 print("正在转换") 188 saveBasePath="xml_test" 189 if os.path.exists(saveBasePath)==False: #判断文件夹是否存在 190 os.makedirs(saveBasePath) 191 192 #ConvertVOCXml(file_path="samplexml",file_name="000009.xml") 193 # Start time 194 start = time.time() 195 log=open("xml_statistical.txt","w") #分析日志,进行排错 196 for xml in totalxml: 197 file_name=os.path.join(basePath,xml) 198 print(file_name) 199 num=ConvertVOCXml(file_path=saveBasePath,file_name=file_name) 200 print(num) 201 total_num=total_num+num 202 log.write(file_name+" "+str(num)+"\n") 203 # End time 204 end = time.time() 205 seconds=end-start 206 print( "Time taken : {0} seconds".format(seconds)) 207 print(total_num) 208 log.write(str(total_num)+"\n") ...

Full Screen

Full Screen

child_process.js

Source:child_process.js Github

copy

Full Screen

1/**2 * Node provides a tri-directional popen(3) facility through the3 * child_process module.4 */5var child_process = {};6/**7 * Launches a new process with the given command, with command line8 * arguments in args.9 * @param command {String}10 * @param args {Array}11 * @param options {Object}12 * @returns {child_process.ChildProcess}13 */14child_process.spawn = function(command, args, options) {}15/**16 * ChildProcess is an [EventEmitter][].17 * @constructor18 */19child_process.ChildProcess = function() {}20child_process.ChildProcess.prototype = new events.EventEmitter();21/**22 * Send a signal to the child process. If no argument is given, the process23 * will be sent 'SIGTERM'. See signal(7) for a list of available signals.24 * @param signal='SIGTERM' {String}25 */26child_process.ChildProcess.prototype.kill = function(signal) {}27/**28 * A Writable Stream that represents the child process's stdin.29 * @type {stream.WritableStream}30 */31child_process.ChildProcess.prototype.stdin = 0;32/**33 * The PID of the child process.34 */35child_process.ChildProcess.prototype.pid = 0;36/**37 * A Readable Stream that represents the child process's stderr.38 * @type {stream.ReadableStream}39 */40child_process.ChildProcess.prototype.stderr = 0;41/**42 * A Readable Stream that represents the child process's stdout.43 * @type {stream.ReadableStream}44 */45child_process.ChildProcess.prototype.stdout = 0;46/**47 * To close the IPC connection between parent and child use the48 * child.disconnect() method. This allows the child to exit gracefully49 * since there is no IPC channel keeping it alive. When calling this method50 * the disconnect event will be emitted in both parent and child, and the51 * connected flag will be set to false. Please note that you can also call52 * process.disconnect() in the child process.53 */54child_process.ChildProcess.prototype.disconnect = function() {}55/**56 * When using child_process.fork() you can write to the child using57 * child.send(message, [sendHandle]) and messages are received by a58 * 'message' event on the child.59 * @param message {Object}60 * @param sendHandle {Handle}61 */62child_process.ChildProcess.prototype.send = function(message, sendHandle) {}63/** @__local__ */ child_process.ChildProcess.__events__ = {};64/**65 * This event is emitted after the child process ends. If the process66 * terminated normally, code is the final exit code of the process,67 * otherwise null. If the process terminated due to receipt of a signal,68 * signal is the string name of the signal, otherwise null. Note that the69 * child process stdio streams might still be open. See waitpid(2).70 * @param code=null {Number}71 * @param signal=null {String}72 */73child_process.ChildProcess.__events__.exit = function(code, signal) {};74/**75 * This event is emitted when the stdio streams of a child process have all76 * terminated. This is distinct from 'exit', since multiple processes might77 * share the same stdio streams.78 */79child_process.ChildProcess.__events__.close = function() {};80/**81 * This event is emitted after using the .disconnect() method in the parent82 * or in the child. After disconnecting it is no longer possible to send83 * messages. An alternative way to check if you can send messages is to see84 * if the child.connected property is true.85 */86child_process.ChildProcess.__events__.disconnect = function() {};87/**88 * Messages send by .send(message, [sendHandle]) are obtained using the89 * message event.90 */91child_process.ChildProcess.__events__.message = function() {};92/**93 * Runs a command in a shell and buffers the output.94 * @param command {String}95 * @param options {Object}96 * @param callback {Function}97 * @returns {child_process.ChildProcess} ChildProcess object98 */99child_process.exec = function(command, options, callback) {}100/**101 * This is similar to child_process.exec() except it does not execute a102 * subshell but rather the specified file directly. This makes it slightly103 * leaner than child_process.exec. It has the same options.104 * @param file {String}105 * @param args {Array}106 * @param options {Object}107 * @param callback {Function}108 * @returns {child_process.ChildProcess} ChildProcess object109 */110child_process.execFile = function(file, args, options, callback) {}111/**112 * This is a special case of the spawn() functionality for spawning Node113 * processes. In addition to having all the methods in a normal114 * ChildProcess instance, the returned object has a communication channel115 * built-in. See child.send(message, [sendHandle]) for details.116 * @param modulePath {String}117 * @param args {Array}118 * @param options {Object}119 * @returns {child_process.ChildProcess} ChildProcess object120 */121child_process.fork = function(modulePath, args, options) {}122/* used for giving types to ChildProcess.std* */123var stream = require('stream');124var events = require('events');...

Full Screen

Full Screen

test_embed.py

Source:test_embed.py Github

copy

Full Screen

1"""Test embedding of IPython"""2#-----------------------------------------------------------------------------3# Copyright (C) 2013 The IPython Development Team4#5# Distributed under the terms of the BSD License. The full license is in6# the file COPYING, distributed as part of this software.7#-----------------------------------------------------------------------------8#-----------------------------------------------------------------------------9# Imports10#-----------------------------------------------------------------------------11import os12import subprocess13import sys14import nose.tools as nt15from IPython.utils.tempdir import NamedFileInTemporaryDirectory16from IPython.testing.decorators import skip_win3217#-----------------------------------------------------------------------------18# Tests19#-----------------------------------------------------------------------------20_sample_embed = b"""21import IPython22a = 323b = 1424print(a, '.', b)25IPython.embed()26print('bye!')27"""28_exit = b"exit\r"29def test_ipython_embed():30 """test that `IPython.embed()` works"""31 with NamedFileInTemporaryDirectory('file_with_embed.py') as f:32 f.write(_sample_embed)33 f.flush()34 f.close() # otherwise msft won't be able to read the file35 # run `python file_with_embed.py`36 cmd = [sys.executable, f.name]37 env = os.environ.copy()38 env['IPY_TEST_SIMPLE_PROMPT'] = '1'39 p = subprocess.Popen(cmd, env=env, stdin=subprocess.PIPE,40 stdout=subprocess.PIPE, stderr=subprocess.PIPE)41 out, err = p.communicate(_exit)42 std = out.decode('UTF-8')43 nt.assert_equal(p.returncode, 0)44 nt.assert_in('3 . 14', std)45 if os.name != 'nt':46 # TODO: Fix up our different stdout references, see issue gh-1447 nt.assert_in('IPython', std)48 nt.assert_in('bye!', std)49@skip_win3250def test_nest_embed():51 """test that `IPython.embed()` is nestable"""52 import pexpect53 ipy_prompt = r']:' #ansi color codes give problems matching beyond this54 env = os.environ.copy()55 env['IPY_TEST_SIMPLE_PROMPT'] = '1'56 child = pexpect.spawn(sys.executable, ['-m', 'IPython', '--colors=nocolor'],57 env=env)58 child.expect(ipy_prompt)59 child.sendline("import IPython")60 child.expect(ipy_prompt)61 child.sendline("ip0 = get_ipython()")62 #enter first nested embed63 child.sendline("IPython.embed()")64 #skip the banner until we get to a prompt65 try:66 prompted = -167 while prompted != 0:68 prompted = child.expect([ipy_prompt, '\r\n'])69 except pexpect.TIMEOUT as e:70 print(e)71 #child.interact()72 child.sendline("embed1 = get_ipython()"); child.expect(ipy_prompt)73 child.sendline("print('true' if embed1 is not ip0 else 'false')")74 assert(child.expect(['true\r\n', 'false\r\n']) == 0)75 child.expect(ipy_prompt)76 child.sendline("print('true' if IPython.get_ipython() is embed1 else 'false')")77 assert(child.expect(['true\r\n', 'false\r\n']) == 0)78 child.expect(ipy_prompt)79 #enter second nested embed80 child.sendline("IPython.embed()")81 #skip the banner until we get to a prompt82 try:83 prompted = -184 while prompted != 0:85 prompted = child.expect([ipy_prompt, '\r\n'])86 except pexpect.TIMEOUT as e:87 print(e)88 #child.interact()89 child.sendline("embed2 = get_ipython()"); child.expect(ipy_prompt)90 child.sendline("print('true' if embed2 is not embed1 else 'false')")91 assert(child.expect(['true\r\n', 'false\r\n']) == 0)92 child.expect(ipy_prompt)93 child.sendline("print('true' if embed2 is IPython.get_ipython() else 'false')")94 assert(child.expect(['true\r\n', 'false\r\n']) == 0)95 child.expect(ipy_prompt)96 child.sendline('exit')97 #back at first embed98 child.expect(ipy_prompt)99 child.sendline("print('true' if get_ipython() is embed1 else 'false')")100 assert(child.expect(['true\r\n', 'false\r\n']) == 0)101 child.expect(ipy_prompt)102 child.sendline("print('true' if IPython.get_ipython() is embed1 else 'false')")103 assert(child.expect(['true\r\n', 'false\r\n']) == 0)104 child.expect(ipy_prompt)105 child.sendline('exit')106 #back at launching scope107 child.expect(ipy_prompt)108 child.sendline("print('true' if get_ipython() is ip0 else 'false')")109 assert(child.expect(['true\r\n', 'false\r\n']) == 0)110 child.expect(ipy_prompt)111 child.sendline("print('true' if IPython.get_ipython() is ip0 else 'false')")112 assert(child.expect(['true\r\n', 'false\r\n']) == 0)113 child.expect(ipy_prompt)114 child.sendline('exit')...

Full Screen

Full Screen

binary_search_tree.py

Source:binary_search_tree.py Github

copy

Full Screen

1class Node (object):2 def __init__ (self, data):3 self.data = data4 self.rightChild = None5 self.leftChild = None6class BinaryTree (object):7 def __init__ (self):8 self.root = None9 def insert (self, newData):10 leaf = Node(newData)11 if self.root is None:12 self.root = leaf13 else:14 current = self.root15 parent = self.root16 while current is not None:17 parent = current18 if newData < current.data:19 current = current.leftChild20 else:21 current = current.rightChild22 if newData < parent.data:23 parent.leftChild = leaf24 else:25 parent.rightChild = leaf26 # returns false if the item to be deleted is not on the tree27 def delete (self, data):28 current = self.root29 parent = self.root30 isLeft = False31 if current is None:32 return False33 while current is not None and current.data is not data:34 parent = current35 if data < current.data:36 current = current.leftChild37 isLeft = True 38 else:39 current = current.rightChild40 isLeft = False41 if current is None:42 return False43 if current.leftChild is None and current.rightChild is None:44 if current is self.root:45 self.root = None46 elif isLeft:47 parent.leftChild = None48 else:49 parent.rightChild = None50 elif current.rightChild is None:51 if current is self.root:52 self.root = current.leftChild53 elif isLeft:54 parent.leftChild = current.leftChild55 else:56 parent.rightChild = current.leftChild57 elif current.rightChild is None:58 if current is self.root:59 self.root = current.rightChild60 elif isLeft:61 parent.lChild = current.rightChild62 else:63 parent.rightChild = current.rightChild64 else:65 succesor = current.rightChild66 succesorParent = current67 while succesor.leftChild is not None:68 succesorParent = succesor69 succesor = succesor.leftChild70 if current is self.root:71 self.root = succesor72 elif isLeft:73 parent.leftChild = succesor74 else:75 parent.rightChild = succesor76 succesor.leftChild = current.leftChild77 if succesor is not current.rightChild:78 succesorParent.leftChild = succesor.rightChild79 succesor.rightChild = current.rightChild80 return True 81 def minNode (self):82 current = self.root83 while current.leftChild is not None:84 current = current.leftChild85 return current.data86 def maxNode (self):87 current = self.root88 while current.rightChild is not None:89 current = current.rightChild90 return current.data91 def printPostOrder (self):92 global postOrder93 postOrder = []94 def PostOrder(node):95 if node is not None:96 PostOrder(node.leftChild)97 PostOrder(node.rightChild)98 postOrder.append(node.data)99 PostOrder(self.root)100 return postOrder101 def printInOrder (self):102 global inOrder 103 inOrder = []104 def InOrder (node):105 if node is not None:106 InOrder(node.leftChild)107 inOrder.append(node.data)108 InOrder(node.rightChild)109 InOrder(self.root)110 return inOrder111 def printPreOrder (self):112 global preOrder113 preOrder = []114 def PreOrder (node):115 if node is not None:116 preOrder.append(node.data)117 PreOrder(node.leftChild)118 PreOrder(node.rightChild)119 PreOrder(self.root)120 return preOrder121 def treeIsEmpty (self):...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var child = require('lambdium').child;2var lambda = require('lambdium').lambda;3var AWS = require('aws-sdk');4var fs = require('fs');5var util = require('util');6var path = require('path');7var child_process = require('child_process');8var events = require('events');9var crypto = require('crypto');10var zlib = require('zlib');11var stream = require('stream');12var http = require('http');13var https = require('https');14var url = require('url');15var querystring = require('querystring');16var assert = require('assert');17var string_decoder = require('string_decoder');18var buffer = require('buffer');19var timers = require('timers');20var console = require('console');21var domain = require('domain');22var process = require('process');23var os = require('os');24var events = require('events');25var util = require('util');26var net = require('net');27var tls = require('tls');28var dgram = require('dgram');

Full Screen

Using AI Code Generation

copy

Full Screen

1var child = require('lambdium').child;2child('test2.js', function (err, result) {3 if (err) {4 console.log(err);5 } else {6 console.log(result);7 }8});9var child = require('lambdium').child;10child('test.js', function (err, result) {11 if (err) {12 console.log(err);13 } else {14 console.log(result);15 }16});17var child = require('lambdium').child;18child('test2.js', function (err, result) {19 if (err) {20 console.log(err);21 } else {22 console.log(result);23 }24});25var child = require('lambdium').child;26child('test.js', function (err, result) {27 if (err) {28 console.log(err);29 } else {30 console.log(result);31 }32});33var child = require('lambdium').child;34child('test2.js', function (err, result) {35 if (err) {36 console.log(err);37 } else {38 console.log(result);39 }40});41var child = require('lambdium').child;42child('test.js', function (err, result) {43 if (err) {44 console.log(err);45 } else {46 console.log(result);47 }48});49var child = require('lambdium').child;50child('test2.js', function (err, result) {51 if (err) {52 console.log(err);53 } else {54 console.log(result);55 }56});57var child = require('lambdium').child;58child('test.js', function (err, result) {59 if (err) {60 console.log(err);61 } else {62 console.log(result

Full Screen

Using AI Code Generation

copy

Full Screen

1const child = require('lambdium').child;2const fs = require('fs');3const path = require('path');4const child_process = require('child_process');5const util = require('util');6const exec = util.promisify(child_process.exec);7const writeFile = util.promisify(fs.writeFile);8const readFile = util.promisify(fs.readFile);9const copyFile = util.promisify(fs.copyFile);10const mkdir = util.promisify(fs.mkdir);11const unlink = util.promisify(fs.unlink);12const readdir = util.promisify(fs.readdir);13const stat = util.promisify(fs.stat);14const rmdir = util.promisify(fs.rmdir);15const removeDir = util.promisify(child.removeDir);16const removeFile = util.promisify(child.removeFile);17const remove = util.promisify(child.remove);18const getDir = util.promisify(child.getDir);19const getFile = util.promisify(child.getFile);20const get = util.promisify(child.get);21const putDir = util.promisify(child.putDir);22const putFile = util.promisify(child.putFile);23const put = util.promisify(child.put);24const list = util.promisify(child.list);

Full Screen

Using AI Code Generation

copy

Full Screen

1var lambda = require('lambdium').child();2var lambda = require('lambdium').child();3lambda.handler = function(event, context) {4 console.log('Hello world');5 context.done();6};7var lambda = require('lambdium').child();8lambda.handler = function(event, context) {9 console.log('Hello world 2');10 context.done();11};12var lambda = require('lambdium').child();13lambda.handler = function(event, context) {14 console.log('Hello world 3');15 context.done();16};17var lambda = require('lambdium').child();18lambda.handler = function(event, context) {19 console.log('Hello world 4');20 context.done();21};22var lambda = require('lambdium').child();23lambda.handler = function(event, context) {24 console.log('Hello world 5');25 context.done();26};27var lambda = require('lambdium').child();28lambda.handler = function(event, context) {29 console.log('Hello world 6');30 context.done();31};32var lambda = require('lambdium').child();33lambda.handler = function(event, context) {34 console.log('Hello world 7');35 context.done();36};37var lambda = require('lambdium').child();38lambda.handler = function(event, context) {39 console.log('Hello world 8');40 context.done();41};42var lambda = require('lambdium').child();43lambda.handler = function(event, context) {44 console.log('Hello world 9');45 context.done();46};

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = function (lambdium) {2 return lambdium.child(function (lambdium) {3 return {4 handler: function (event, context) {5 }6 }7 })8}9var lambdium = require('lambdium')10var test = require('./test')11var handler = test(lambdium)12module.exports = function (lambdium) {13 return lambdium.child(function (lambdium) {14 return {15 handler: function (event, context) {16 }17 }18 })19}20var lambdium = require('lambdium')21var test = require('./test')22var handler = test(lambdium)23module.exports = function (lambdium) {24 return lambdium.child(function (lambdium) {25 return {26 handler: function (event, context) {27 }28 }29 })30}31var lambdium = require('lambdium')32var test = require('./test')33var handler = test(lambdium)34module.exports = function (lambdium) {35 return lambdium.child(function (lambdium) {36 return {37 handler: function (event, context) {38 }39 }40 })41}42var lambdium = require('lambdium')43var test = require('./test')44var handler = test(lambdium)45module.exports = function (lambdium) {46 return lambdium.child(function (lambdium) {47 return {

Full Screen

Using AI Code Generation

copy

Full Screen

1var child = require('lambdium').child;2child('child.js', function(err, child) {3 if (err) {4 console.error(err);5 return;6 }7 child.send('hello child');8 child.on('message', function(msg) {9 console.log(msg);10 });11});12var child = require('lambdium').child;13child.on('message', function(msg) {14 console.log(msg);15 child.send('hello parent');16});17child.send('hello child', [1, 2, 3], {a: 1, b: 2});18child.on('message', function(msg, arr, obj) {19 console.log(msg, arr, obj);20});21child.send('hello child', function() {22 return 'hello parent';23});24child.on('message', function(msg, fn) {25});26child.send('hello child', function() {27 return 'hello parent';28});29child.on('message', function(msg, fn) {30});31child.send('hello child', function() {32 var child = require('lambdium').child;33 child.send('hello parent');34});35child.on('message', function(msg) {36});37child.send('hello child', function() {38 var child = require('lambdium').child;39 child.send('hello parent');40});41child.on('message', function(msg) {42});43child.send('hello child', function() {44 var child = require('lambdium').child;45 child.send('hello parent');46});

Full Screen

Using AI Code Generation

copy

Full Screen

1var child = require('lambdium').child;2var myFunction = function(event, context, callback) {3 callback(null, 'Hello World');4}5exports.handler = child(myFunction);6var child = require('lambdium').child;7var myFunction = function(event, context, callback) {8 callback(null, 'Hello World');9}10exports.handler = child(myFunction);11var child = require('lambdium').child;12var myFunction = function(event, context, callback) {13 callback(null, 'Hello World');14}15exports.handler = child(myFunction);16var child = require('lambdium').child;17var myFunction = function(event, context, callback) {18 callback(null, 'Hello World');19}20exports.handler = child(myFunction);21var child = require('lambdium').child;22var myFunction = function(event, context, callback) {23 callback(null, 'Hello World');24}25exports.handler = child(myFunction);26var child = require('lambdium').child;27var myFunction = function(event, context, callback) {28 callback(null, 'Hello World');29}30exports.handler = child(myFunction);31var child = require('lambdium').child;32var myFunction = function(event, context, callback) {33 callback(null, 'Hello World');34}35exports.handler = child(myFunction);

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run lambdium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful