How to use parent method in wpt

Best JavaScript code snippet using wpt

core.js

Source:core.js Github

copy

Full Screen

1$(document).ready(function() {2 var theclass;3 $('.fa-expand.normal').click(function() {4 theclass = $(this).parent().parent().parent().attr('class');5 $('.' + theclass).hide();6 $(this).parent().parent().find('.inner').hide();7 $('.inner.mini').show();8 $('.fa-compress').show();9 $('.fa-bar-chart-o').show();10 $('.fa-table').show();11 $(this).parent().find('.fa-table').addClass('selected');12 $(this).parent().find('.fa-bar-chart-o').removeClass('selected');13 $('.fa-expand').hide();14 $(this).parent().parent().parent().show();15 $(this).parent().parent().parent().removeClass('standard-graph');16 $(this).parent().parent().parent().addClass('x-large-graph');17 });18 $('.fa-compress.normal').click(function() {19 $('.' + theclass).show();20 $(this).parent().parent().parent().removeClass('x-large-graph');21 $(this).parent().parent().parent().addClass('standard-graph');22 $('.inner.mini').hide();23 $(this).parent().parent().find('.inner.max').show();24 $('.' + theclass).show();25 $('.fa-compress').hide();26 $('.fa-bar-chart-o').hide();27 $('.fa-table').hide();28 $('.fa-expand').show();29 $(this).parent().parent().find('.mini-graph').empty();30 $(this).parent().parent().find('.mini-graph-2').empty();31 $(this).parent().parent().find('.mini-graph').hide();32 $(this).parent().parent().find('.mini-graph-2').hide();33 });34 $('.fa-expand.full-screen').click(function() {35 theclass = $(this).parent().parent().parent().attr('class');36 $('.' + theclass).hide();37 $(this).parent().parent().find('.inner').hide();38 $('.inner.mini.full-screen').show();39 $('.fa-compress.full-screen').show();40 $('.fa-bar-chart-o').show();41 $('.fa-table').show();42 $(this).parent().find('.fa-table').addClass('selected');43 $(this).parent().find('.fa-bar-chart-o').removeClass('selected');44 $('.fa-expand.full-screen').hide();45 $(this).parent().parent().parent().show();46 $(this).parent().parent().parent().removeClass('standard-graph');47 $(this).parent().parent().parent().addClass('xx-large-graph');48 $(this).parent().find('#limit').text('(All)');49 $('.activities').hide();50 $('.guide').hide();51 //var base_url = '<?php echo base_url(); ?>';52 //var function_url_array = ['guidelines_policy/distribution/region/county/all'];53 //var container_array = ['distribution_county_fullscreen'];54 //loadGraphSection(base_url, function_url_array, container_array);55 });56 $('.fa-compress.full-screen').click(function() {57 $('.' + theclass).show();58 $(this).parent().parent().parent().removeClass('xx-large-graph');59 $(this).parent().parent().parent().addClass('standard-graph');60 $('.inner.mini.full-screen').hide();61 $(this).parent().parent().find('.inner.max').show();62 $('.' + theclass).show();63 $('.fa-compress.full-screen').hide();64 $('.fa-bar-chart-o').hide();65 $('.fa-table').hide();66 $('.fa-expand.full-screen').show();67 $(this).parent().parent().find('.mini-graph').empty();68 $(this).parent().parent().find('.mini-graph-2').empty();69 $(this).parent().parent().find('.mini-graph').hide();70 $(this).parent().parent().find('.mini-graph-2').hide();71 $(this).parent().find('#limit').text('(Top 10)');72 $('.activities').show();73 $('.guide').show();74 });75 $('.fa-bar-chart-o').click(function() {76 $(this).parent().parent().find('.mini-graph').empty();77 $(this).parent().parent().find('.mini-graph-2').empty();78 $(this).parent().find('.fa-bar-chart-o').addClass('selected');79 $(this).parent().find('.fa-table').removeClass('selected');80 $(this).parent().parent().find('.mini').hide();81 $(this).parent().parent().find('.mini-graph').show();82 $(this).parent().parent().find('.mini-graph-2').show();83 });84 $('.fa-table').click(function() {85 $(this).parent().find('.fa-bar-chart-o').removeClass('selected');86 $(this).parent().find('.fa-table').addClass('selected');87 $(this).parent().parent().find('.mini-graph').hide();88 $(this).parent().parent().find('.mini-graph-2').hide();89 $(this).parent().parent().find('.mini').show();90 });91 $('.fa-search').click(function() {92 showSearch();93 });94 $('.search-close').click(function() {95 hideSearch();96 });97 $(document).on('keydown', null, 'ctrl+z', showSearch);98 $(document).on('keydown', null, 'ctrl+x', hideSearch);99});100function getHCWData(base_url, function_url) {101 var facilityTable, hcwTable;102 $.ajax({103 url: base_url + function_url,104 beforeSend: function(xhr) {105 xhr.overrideMimeType("text/plain; charset=x-user-defined");106 },107 success: function(data) {108 $('#hcw_list').empty();109 $('#facility_list').empty();110 var obj = $.parseJSON(data);111 $('#facility_total_existing').text(obj['facility_data']['facility_number_existing']);112 $('#facility_total_trained_hcw').text(obj['facility_data']['facility_number_trained']);113 $('#hcw_total_trained').text(obj['participant_data']['participant_number_trained']);114 $('#facility_total_trained_public_hcw').text(obj['participant_data']['public']);115 $('#facility_total_trained_private_hcw').text(obj['participant_data']['private']);116 facilityTable = '<table class="dataTable"><thead><th>Facility MFL Code<i class="fa"></i></th> <th>Facility Name<i class="fa"></i></th></thead><tbody> ';117 $.each(obj['facility_data']['facility_list'], function(k, v) {118 facilityTable = facilityTable + '<tr><td>' + v['mfl_code'] + '</td><td>' + v['fac_name'] + '</td></tr>';119 });120 facilityTable = facilityTable + '</tbody></table>';121 $('#facility_list').append(facilityTable);122 $('#hcw_total_existing').text(obj['participant_data']['participant_number_existing']);123 $('#hcw_total_trained').text(obj['participant_data']['participant_number_trained']);124 hcwTable = '<table class="dataTable"><thead><th>Participant Name<i class="fa"></i></th> <th>Facility Name<i class="fa"></i></th><th>Cadre<i class="fa"></i></th></thead><tbody> ';125 $.each(obj['participant_data']['participant_list'], function(k, v) {126 hcwTable = hcwTable + '<tr><td>' + v['names_of_participant'] + '</td><td>' + v['fac_name'] + '</td><td>' + v['cadre'] + '</td></tr>';127 });128 hcwTable = hcwTable + '</tbody></table>';129 $('#hcw_list').append(hcwTable);130 $('.dataTable').dataTable({131 "sPaginationType": "full_numbers"132 });133 $('.dataTables_filter label input').addClass('form-control');134 $('.dataTables_length label select').addClass('form-control');135 $('#DataTables_Table_0_paginate a').addClass('btn btn-xs btn-default');136 $('#DataTables_Table_0_paginate span a').addClass('btn btn-xs btn-default');137 }138 });139}140$('th.sorting_asc i').addClass('fa-chevron-up');141$('th.sorting_desc i').addClass('fa-chevron-down');142function getTOTData(base_url, function_url) {143 var facilityTable, hcwTable;144 $.ajax({145 url: base_url + function_url,146 beforeSend: function(xhr) {147 xhr.overrideMimeType("text/plain; charset=x-user-defined");148 },149 success: function(data) {150 var obj = $.parseJSON(data);151 $('#tot_total_trained').text(obj['participant_data']['participant_number_trained']);152 }153 });154}155function showSearch() {156 //$('.fa-search').parent().parent().addClass('active');157 left = $('.main').css('left');158 if (left == '0px') {159 $('.main').animate({160 left: '100%'161 }, 1000);162 $('.search').animate({163 left: '+=100%'164 }, 1000);165 $('.search-close').show();166 $('.fa-search').parent().parent().hide();167 $('.tt-input').focus();168 }169}170function hideSearch() {171 left = $('.search').css('left');172 if (left == '0px') {173 $('.fa-search').parent().parent().show();174 $('.search-close').hide();175 $('.search').animate({176 left: '-=100%'177 }, 1000);178 $('.main').animate({179 left: '-=100%'180 }, 1000);181 $('.tt-input').blur();182 }183}184function loadGraph(base_url, function_url, container) {185 $('#' + container).load(base_url + function_url);186}187/**188 * [loadGraphSection loops through an array of container IDs to plot the graphs]189 * @param {[array]} containerArray [description]190 * @param {[string]} base_url [description]191 * @param {[string]} function_url [description]192 * @param {[string]} container [description]193 * @return {[none]} [description]194 */195function loadGraphSection(base_url, function_url_array, container_array) {196 //alert('Stuff');197 count = 0;198 $.each(container_array, function(index, value) {199 //alert (base_url+function_url_array[count]+' '+ value);200 loadGraph(base_url, function_url_array[count], value);201 count++;202 });203}204function loadGraphs(base_url, function_url) {205 $.ajax({206 url: base_url + function_url,207 beforeSend: function(xhr) {208 xhr.overrideMimeType("text/plain; charset=x-user-defined");209 },210 success: function(data) {211 obj = jQuery.parseJSON(data);212 $("#chart_category").val(obj['cat']);213 $('#graph').empty();214 $('#graph').append('<div style="width:100%" id="' + obj['chart_container'] + '"></div>');215 runGraph(obj['chart_container'], obj['chart_type'], obj['chart_size'], obj['chart_title'], obj['chart_stacking'], obj['chart_categories'], obj['chart_series']);216 }217 });218}219function runGraph(chart_container, chart_type, chart_title, chart_series) {220 $("#" + chart_container).chart_type({221 dataSource: dataSource,222 commonSeriesSettings: {223 label: {224 visible: true,225 connector: {226 visible: true227 },228 customizeText: function(value) {229 return value.argumentText;230 }231 }232 //...233 },234 title: {235 text: chart_title,236 verticalAlignment: 'bottom',237 font: {238 color: '#3276b1',239 family: 'SourceSansPro-Regular',240 opacity: 0.75,241 size: 16,242 weight: 200243 }244 },245 series: chart_series,246 tooltip: {247 enabled: true,248 customizeText: function(value) {249 return value.argumentText + ' : ' + value.percentText;250 }251 },252 legend: {253 visible: false254 }255 });256}257function pageHandler(base_url, activity) {258 var activityID;259 $("." + activity + "_manual_update").click(function() {260 $('#' + activity + '_manual_update').modal('show');261 activityID = $(this).attr('id');262 $('#' + activity + '_manual_update').delay(2000).queue(function(nxt) {263 $('#activity_id_man').val(activityID);264 nxt();265 });266 });267 $('.' + activity + '_activity_source').click(function() {268 $('#source_data').empty();269 $('#source_data').append('<div class="la-anim-1-mini"></div>');270 $('#source_data > .la-anim-1-mini').addClass('la-animate');271 $('#activity_name').empty();272 activityID = $(this).attr('id');273 $('#' + activity + '_files_modal').modal('show');274 $('#' + activity + '_files_modal').delay(2000).queue(function(nxt) {275 $('#source_data').load(base_url + 'imci/load_activity_source/' + activityID);276 $('#activity_name').load(base_url + 'imci/load_activity_name/' + activityID);277 nxt();278 });279 $('#' + activity + '_files_modal').delay(4000).queue(function(nxt) {280 $(".dataTable").dataTable();281 nxt();282 });283 });284 $("." + activity + "_activity_upload").click(function() {285 $('#' + activity + '_upload_activity').modal('show');286 activityID = $(this).attr('id');287 $('#upload_button').delay(2000).queue(function(nxt) {288 $('#activity_id').val(activityID);289 nxt();290 });291 });292 $("#" + activity + "_uploadActivityBtn").click(function() {293 $('#' + activity + '_upload_form').submit();294 });295 $(".add").click(function() {296 // when add is clicked this function297 $('.datepicker').datepicker('remove');298 $table = $('#activity_table');299 var cloned_object = $table.find('tr:last').clone(true);300 var id = cloned_object.attr("id");301 var next_id = parseInt(id) + 1;302 cloned_object.attr("id", next_id);303 cloned_object.find("input").val("");304 cloned_object.find(":input").css('border-color', '#ccc');305 //cat_name;306 // cat_name.attr("text",'');307 //cloned_object.find(".participant").attr("name",'participant['+next_id+']');308 cloned_object.insertAfter('#activity_table tr:last');309 $('.remove').show();310 $('.datepicker').datepicker({311 format: 'dd-m-yyyy',312 autoclose: true313 });314 return false;315 });316 $('.remove').click(function() {317 id = $(this).parent().parent().attr("id");318 if (id !== 0) {319 $(this).parent().parent().remove();320 } else {321 alert('This is the first row');322 }323 });324 //On Change325 $('.datepicker').datepicker({326 format: 'dd-m-yyyy',327 autoclose: true328 });329 $('#export_csv').click(function() {330 link = $(this).attr('data-link');331 window.open(link + activityID);332 });333 $('#export_pdf').click(function() {334 link = $(this).attr('data-link');335 window.open(link + activityID);336 });337 $('.modal-title > a#export_pdf').click(function() {338 link = $(this).attr('data-link');339 });340 $('.facilityoption').change(function() {341 val = $(this).val();342 text = $(this).find('option:selected').text();343 //alert(text);344 row = $(this).parent().parent().attr("id");345 $(this).closest('tr').find('.mfl_code').val(val);346 $(this).closest('tr').find('.facilityname').val(text);347 });348 function validate_combo(combo) {349 tr_id = $(combo).parent().parent().attr('id');350 value = $('tr#' + tr_id + ' td ' + combo).prop("selectedIndex");351 if (value === 0) {352 $(combo).css('border-color', 'red');353 } else {354 $(combo).css('border-color', '#ccc');355 }356 //return value;357 }358 function validate_text(field) {359 tr_id = $(field).parent().parent().attr('id');360 alert('tr#' + tr_id + ' td ' + field);361 value = $('tr#' + tr_id + ' td ' + field).val();362 //message = $(field).attr('data-msg');363 if (value === "") {364 $(field).attr.css('border-color', 'red');365 $(field).tooltip('show');366 } else {367 $(field).css('border-color', '#ccc');368 $(field).tooltip('hide');369 }370 }371 $('.fa-bar-chart-o').click(function() {372 var activity_name = 'Train an expanded pool of HCWs';373 activity_name = encodeURIComponent(activity_name);...

Full Screen

Full Screen

ox.multicheckbox.js

Source:ox.multicheckbox.js Github

copy

Full Screen

...199 if ($target.is(":checkbox")) {200 $checkbox = $target;201 } 202 else if (options.clickElement && ($target.is(options.clickElement) || (ie6 && $target.is("label")))) {203 $checkbox = $target.parent().find(":checkbox");204 if (!$checkbox.get(0)) {205 return;206 }207 $checkbox.get(0).checked = !$checkbox.get(0).checked; 208 } 209 else {210 return;211 }212 213 if ($checkbox.is(options.selectAllSelector)) {214 handleSelectAllChange($checkbox);215 }216 else {217 handleCheckboxStateChange($checkbox, $target, true);...

Full Screen

Full Screen

BarnesHutSolver.js

Source:BarnesHutSolver.js Github

copy

Full Screen

1class BarnesHutSolver {2 constructor(body, physicsBody, options) {3 this.body = body;4 this.physicsBody = physicsBody;5 this.barnesHutTree;6 this.setOptions(options);7 this.randomSeed = 5;8 // debug: show grid9 //this.body.emitter.on("afterDrawing", (ctx) => {this._debug(ctx,'#ff0000')})10 }11 setOptions(options) {12 this.options = options;13 this.thetaInversed = 1 / this.options.theta;14 this.overlapAvoidanceFactor = 1 - Math.max(0, Math.min(1,this.options.avoidOverlap)); // if 1 then min distance = 0.5, if 0.5 then min distance = 0.5 + 0.5*node.shape.radius15 }16 seededRandom() {17 var x = Math.sin(this.randomSeed++) * 10000;18 return x - Math.floor(x);19 }20 /**21 * This function calculates the forces the nodes apply on each other based on a gravitational model.22 * The Barnes Hut method is used to speed up this N-body simulation.23 *24 * @private25 */26 solve() {27 if (this.options.gravitationalConstant !== 0 && this.physicsBody.physicsNodeIndices.length > 0) {28 let node;29 let nodes = this.body.nodes;30 let nodeIndices = this.physicsBody.physicsNodeIndices;31 let nodeCount = nodeIndices.length;32 // create the tree33 let barnesHutTree = this._formBarnesHutTree(nodes, nodeIndices);34 // for debugging35 this.barnesHutTree = barnesHutTree;36 // place the nodes one by one recursively37 for (let i = 0; i < nodeCount; i++) {38 node = nodes[nodeIndices[i]];39 if (node.options.mass > 0) {40 // starting with root is irrelevant, it never passes the BarnesHutSolver condition41 this._getForceContribution(barnesHutTree.root.children.NW, node);42 this._getForceContribution(barnesHutTree.root.children.NE, node);43 this._getForceContribution(barnesHutTree.root.children.SW, node);44 this._getForceContribution(barnesHutTree.root.children.SE, node);45 }46 }47 }48 }49 /**50 * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.51 * If a region contains a single node, we check if it is not itself, then we apply the force.52 *53 * @param parentBranch54 * @param node55 * @private56 */57 _getForceContribution(parentBranch, node) {58 // we get no force contribution from an empty region59 if (parentBranch.childrenCount > 0) {60 let dx, dy, distance;61 // get the distance from the center of mass to the node.62 dx = parentBranch.centerOfMass.x - node.x;63 dy = parentBranch.centerOfMass.y - node.y;64 distance = Math.sqrt(dx * dx + dy * dy);65 // BarnesHutSolver condition66 // original condition : s/d < theta = passed === d/s > 1/theta = passed67 // calcSize = 1/s --> d * 1/s > 1/theta = passed68 if (distance * parentBranch.calcSize > this.thetaInversed) {69 this._calculateForces(distance, dx, dy, node, parentBranch);70 }71 else {72 // Did not pass the condition, go into children if available73 if (parentBranch.childrenCount === 4) {74 this._getForceContribution(parentBranch.children.NW, node);75 this._getForceContribution(parentBranch.children.NE, node);76 this._getForceContribution(parentBranch.children.SW, node);77 this._getForceContribution(parentBranch.children.SE, node);78 }79 else { // parentBranch must have only one node, if it was empty we wouldnt be here80 if (parentBranch.children.data.id != node.id) { // if it is not self81 this._calculateForces(distance, dx, dy, node, parentBranch);82 }83 }84 }85 }86 }87 /**88 * Calculate the forces based on the distance.89 *90 * @param distance91 * @param dx92 * @param dy93 * @param node94 * @param parentBranch95 * @private96 */97 _calculateForces(distance, dx, dy, node, parentBranch) {98 if (distance === 0) {99 distance = 0.1;100 dx = distance;101 }102 if (this.overlapAvoidanceFactor < 1 && node.shape.radius) {103 distance = Math.max(0.1 + (this.overlapAvoidanceFactor * node.shape.radius), distance - node.shape.radius);104 }105 // the dividing by the distance cubed instead of squared allows us to get the fx and fy components without sines and cosines106 // it is shorthand for gravityforce with distance squared and fx = dx/distance * gravityForce107 let gravityForce = this.options.gravitationalConstant * parentBranch.mass * node.options.mass / Math.pow(distance,3);108 let fx = dx * gravityForce;109 let fy = dy * gravityForce;110 this.physicsBody.forces[node.id].x += fx;111 this.physicsBody.forces[node.id].y += fy;112 }113 /**114 * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.115 *116 * @param nodes117 * @param nodeIndices118 * @private119 */120 _formBarnesHutTree(nodes, nodeIndices) {121 let node;122 let nodeCount = nodeIndices.length;123 let minX = nodes[nodeIndices[0]].x;124 let minY = nodes[nodeIndices[0]].y;125 let maxX = nodes[nodeIndices[0]].x;126 let maxY = nodes[nodeIndices[0]].y;127 // get the range of the nodes128 for (let i = 1; i < nodeCount; i++) {129 let x = nodes[nodeIndices[i]].x;130 let y = nodes[nodeIndices[i]].y;131 if (nodes[nodeIndices[i]].options.mass > 0) {132 if (x < minX) {133 minX = x;134 }135 if (x > maxX) {136 maxX = x;137 }138 if (y < minY) {139 minY = y;140 }141 if (y > maxY) {142 maxY = y;143 }144 }145 }146 // make the range a square147 let sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y148 if (sizeDiff > 0) {149 minY -= 0.5 * sizeDiff;150 maxY += 0.5 * sizeDiff;151 } // xSize > ySize152 else {153 minX += 0.5 * sizeDiff;154 maxX -= 0.5 * sizeDiff;155 } // xSize < ySize156 let minimumTreeSize = 1e-5;157 let rootSize = Math.max(minimumTreeSize, Math.abs(maxX - minX));158 let halfRootSize = 0.5 * rootSize;159 let centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);160 // construct the barnesHutTree161 let barnesHutTree = {162 root: {163 centerOfMass: {x: 0, y: 0},164 mass: 0,165 range: {166 minX: centerX - halfRootSize, maxX: centerX + halfRootSize,167 minY: centerY - halfRootSize, maxY: centerY + halfRootSize168 },169 size: rootSize,170 calcSize: 1 / rootSize,171 children: {data: null},172 maxWidth: 0,173 level: 0,174 childrenCount: 4175 }176 };177 this._splitBranch(barnesHutTree.root);178 // place the nodes one by one recursively179 for (let i = 0; i < nodeCount; i++) {180 node = nodes[nodeIndices[i]];181 if (node.options.mass > 0) {182 this._placeInTree(barnesHutTree.root, node);183 }184 }185 // make global186 return barnesHutTree187 }188 /**189 * this updates the mass of a branch. this is increased by adding a node.190 *191 * @param parentBranch192 * @param node193 * @private194 */195 _updateBranchMass(parentBranch, node) {196 let totalMass = parentBranch.mass + node.options.mass;197 let totalMassInv = 1 / totalMass;198 parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.options.mass;199 parentBranch.centerOfMass.x *= totalMassInv;200 parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.options.mass;201 parentBranch.centerOfMass.y *= totalMassInv;202 parentBranch.mass = totalMass;203 let biggestSize = Math.max(Math.max(node.height, node.radius), node.width);204 parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;205 }206 /**207 * determine in which branch the node will be placed.208 *209 * @param parentBranch210 * @param node211 * @param skipMassUpdate212 * @private213 */214 _placeInTree(parentBranch, node, skipMassUpdate) {215 if (skipMassUpdate != true || skipMassUpdate === undefined) {216 // update the mass of the branch.217 this._updateBranchMass(parentBranch, node);218 }219 if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW220 if (parentBranch.children.NW.range.maxY > node.y) { // in NW221 this._placeInRegion(parentBranch, node, "NW");222 }223 else { // in SW224 this._placeInRegion(parentBranch, node, "SW");225 }226 }227 else { // in NE or SE228 if (parentBranch.children.NW.range.maxY > node.y) { // in NE229 this._placeInRegion(parentBranch, node, "NE");230 }231 else { // in SE232 this._placeInRegion(parentBranch, node, "SE");233 }234 }235 }236 /**237 * actually place the node in a region (or branch)238 *239 * @param parentBranch240 * @param node241 * @param region242 * @private243 */244 _placeInRegion(parentBranch, node, region) {245 switch (parentBranch.children[region].childrenCount) {246 case 0: // place node here247 parentBranch.children[region].children.data = node;248 parentBranch.children[region].childrenCount = 1;249 this._updateBranchMass(parentBranch.children[region], node);250 break;251 case 1: // convert into children252 // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)253 // we move one node a little bit and we do not put it in the tree.254 if (parentBranch.children[region].children.data.x === node.x &&255 parentBranch.children[region].children.data.y === node.y) {256 node.x += this.seededRandom();257 node.y += this.seededRandom();258 }259 else {260 this._splitBranch(parentBranch.children[region]);261 this._placeInTree(parentBranch.children[region], node);262 }263 break;264 case 4: // place in branch265 this._placeInTree(parentBranch.children[region], node);266 break;267 }268 }269 /**270 * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch271 * after the split is complete.272 *273 * @param parentBranch274 * @private275 */276 _splitBranch(parentBranch) {277 // if the branch is shaded with a node, replace the node in the new subset.278 let containedNode = null;279 if (parentBranch.childrenCount === 1) {280 containedNode = parentBranch.children.data;281 parentBranch.mass = 0;282 parentBranch.centerOfMass.x = 0;283 parentBranch.centerOfMass.y = 0;284 }285 parentBranch.childrenCount = 4;286 parentBranch.children.data = null;287 this._insertRegion(parentBranch, "NW");288 this._insertRegion(parentBranch, "NE");289 this._insertRegion(parentBranch, "SW");290 this._insertRegion(parentBranch, "SE");291 if (containedNode != null) {292 this._placeInTree(parentBranch, containedNode);293 }294 }295 /**296 * This function subdivides the region into four new segments.297 * Specifically, this inserts a single new segment.298 * It fills the children section of the parentBranch299 *300 * @param parentBranch301 * @param region302 * @param parentRange303 * @private304 */305 _insertRegion(parentBranch, region) {306 let minX, maxX, minY, maxY;307 let childSize = 0.5 * parentBranch.size;308 switch (region) {309 case "NW":310 minX = parentBranch.range.minX;311 maxX = parentBranch.range.minX + childSize;312 minY = parentBranch.range.minY;313 maxY = parentBranch.range.minY + childSize;314 break;315 case "NE":316 minX = parentBranch.range.minX + childSize;317 maxX = parentBranch.range.maxX;318 minY = parentBranch.range.minY;319 maxY = parentBranch.range.minY + childSize;320 break;321 case "SW":322 minX = parentBranch.range.minX;323 maxX = parentBranch.range.minX + childSize;324 minY = parentBranch.range.minY + childSize;325 maxY = parentBranch.range.maxY;326 break;327 case "SE":328 minX = parentBranch.range.minX + childSize;329 maxX = parentBranch.range.maxX;330 minY = parentBranch.range.minY + childSize;331 maxY = parentBranch.range.maxY;332 break;333 }334 parentBranch.children[region] = {335 centerOfMass: {x: 0, y: 0},336 mass: 0,337 range: {minX: minX, maxX: maxX, minY: minY, maxY: maxY},338 size: 0.5 * parentBranch.size,339 calcSize: 2 * parentBranch.calcSize,340 children: {data: null},341 maxWidth: 0,342 level: parentBranch.level + 1,343 childrenCount: 0344 };345 }346 //--------------------------- DEBUGGING BELOW ---------------------------//347 /**348 * This function is for debugging purposed, it draws the tree.349 *350 * @param ctx351 * @param color352 * @private353 */354 _debug(ctx, color) {355 if (this.barnesHutTree !== undefined) {356 ctx.lineWidth = 1;357 this._drawBranch(this.barnesHutTree.root, ctx, color);358 }359 }360 /**361 * This function is for debugging purposes. It draws the branches recursively.362 *363 * @param branch364 * @param ctx365 * @param color366 * @private367 */368 _drawBranch(branch, ctx, color) {369 if (color === undefined) {370 color = "#FF0000";371 }372 if (branch.childrenCount === 4) {373 this._drawBranch(branch.children.NW, ctx);374 this._drawBranch(branch.children.NE, ctx);375 this._drawBranch(branch.children.SE, ctx);376 this._drawBranch(branch.children.SW, ctx);377 }378 ctx.strokeStyle = color;379 ctx.beginPath();380 ctx.moveTo(branch.range.minX, branch.range.minY);381 ctx.lineTo(branch.range.maxX, branch.range.minY);382 ctx.stroke();383 ctx.beginPath();384 ctx.moveTo(branch.range.maxX, branch.range.minY);385 ctx.lineTo(branch.range.maxX, branch.range.maxY);386 ctx.stroke();387 ctx.beginPath();388 ctx.moveTo(branch.range.maxX, branch.range.maxY);389 ctx.lineTo(branch.range.minX, branch.range.maxY);390 ctx.stroke();391 ctx.beginPath();392 ctx.moveTo(branch.range.minX, branch.range.maxY);393 ctx.lineTo(branch.range.minX, branch.range.minY);394 ctx.stroke();395 /*396 if (branch.mass > 0) {397 ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);398 ctx.stroke();399 }400 */401 }402}...

Full Screen

Full Screen

random.js

Source:random.js Github

copy

Full Screen

1/**2 * Text extraction plugin.3 */4Draw.loadPlugin(function(ui)5{6 var defaultDelay = 2000;7 var defaultMax = 50;8 var graph = ui.editor.graph;9 // Adds resource for action10 mxResources.parse('randomLabel=Random Label...');11 12 // Adds action13 ui.actions.addAction('randomLabel', function()14 {15 var cells = graph.getSelectionCells().slice();16 17 if (cells.length > 0)18 {19 var delay = parseInt(prompt('Delay (ms)', defaultDelay));20 var max = parseInt(prompt('Cycles', defaultMax));21 var counter = 0;22 function schedule()23 {24 var jitter = 1 + 0.3 * (Math.random() - 0.5);25 26 window.setTimeout(function()27 {28 for (var i = 0; i < cells.length; i++)29 {30 graph.labelChanged(cells[i], 'Test ' + Math.round(Math.random() * 100));31 }32 33 if (ui.dialog != null)34 {35 console.log('randomLabel halted');36 }37 else38 {39 ui.saveFile(null, function()40 {41 if (counter++ < max && ui.dialog == null)42 {43 console.log('randomLabel', counter);44 schedule();45 }46 else47 {48 console.log('randomLabel halted');49 }50 });51 }52 }, delay * jitter);53 }54 55 schedule();56 }57 else58 {59 ui.alert(mxResources.get('nothingIsSelected'));60 }61 });62 63 // Adds resource for action64 mxResources.parse('swapChildren=Swap children...');65 // Adds action66 ui.actions.addAction('swapChildren', function()67 {68 var cells = graph.getSelectionCells().slice();69 70 if (cells.length > 1)71 {72 var delay = parseInt(prompt('Delay (ms)', defaultDelay));73 var max = parseInt(prompt('Cycles', defaultMax));74 var counter = 0;75 76 function schedule()77 {78 var jitter = 1 + 0.3 * (Math.random() - 0.5);79 80 window.setTimeout(function()81 {82 // assuming parent is the first cell selected83 var parentA = cells[0];84 var parentB = cells[1];85 86 var childrenA = parentA.children;87 var childrenB = parentB.children;88 89 var numberA = childrenA.length;90 var numberB = childrenB.length;91 92 if (childrenA != null && childrenA.length > 1 || childrenB != null && childrenB.length > 1)93 {94 graph.getModel().beginUpdate();95 try96 {97 // permute children98 var passes = Math.floor(Math.random() * numberA) + 1;99 console.log(counter + " - swapping " + passes + " children from parent A to parent B");100 101 for (var i = 0; i < passes; i++)102 {103 // which child to select from parent A104 var k = Math.floor(Math.random() * numberA);105 // where to insert it to parent B106 var l = Math.floor(Math.random() * (numberB + 1));107 graph.model.add(parentB, childrenA[k], l);108 109 numberA -= 1;110 numberB += 1;111 }112 var passes = Math.floor(Math.random() * numberB) + 1;113 console.log(counter + " - swapping " + passes + " children from parent B to parent A");114 115 for (var i = 0; i < passes; i++)116 {117 // which child to select from parent A118 var k = Math.floor(Math.random() * numberB);119 // where to insert it to parent B120 var l = Math.floor(Math.random() * (numberA + 1));121 graph.model.add(parentA, childrenB[k], l);122 numberA += 1;123 numberB -= 1;124 }125 }126 finally127 {128 graph.getModel().endUpdate();129 }130 }131 132 if (ui.dialog != null)133 {134 console.log('swapChildren halted');135 }136 else137 {138 ui.saveFile(null, function()139 {140 if (counter++ < max && ui.dialog == null)141 {142 console.log('swapChildren', counter);143 schedule();144 }145 else146 {147 console.log('swapChildren halted');148 }149 });150 }151 }, delay * jitter);152 }153 154 schedule();155 }156 else157 {158 ui.alert(mxResources.get('nothingIsSelected'));159 }160 });161 162 // Adds resource for action163 mxResources.parse('placeChildren=Place children...');164 // Adds action165 ui.actions.addAction('placeChildren', function()166 {167 var graph = ui.editor.graph;168 var cells = graph.getSelectionCells().slice();169 170 if (cells.length > 1)171 {172 var counter = 0;173 var delay = parseInt(prompt('Delay (ms)', defaultDelay));174 var max = parseInt(prompt('Cycles', defaultMax));175 176 177 function schedule()178 {179 var jitter = 1 + 0.3 * (Math.random() - 0.5);180 181 window.setTimeout(function()182 {183 // assuming parent is the first cell selected184 var parentA = cells[0];185 var parentB = cells[1];186 187 var childrenA = parentA.children;188 var childrenB = parentB.children;189 190 var numberA = (childrenA != null)? childrenA.length: 0;191 var numberB = (childrenB != null)? childrenB.length: 0;192 193 var n = 0;194 195 if (childrenA != null && childrenA.length > 1 || childrenB != null && childrenB.length > 1)196 {197 graph.getModel().beginUpdate();198 try199 {200 // first, remove a few children from each parent201 childrenA = parentA.children;202 childrenB = parentB.children;203 numberA = (childrenA != null)? childrenA.length: 0;204 numberB = (childrenB != null)? childrenB.length: 0;205 206 // 1st parent207 n = Math.floor(Math.random() * 4); // how many to delete? at least 1 should remain208 n = Math.min(n, Math.max(0, numberA - 2));209 console.log(counter + " - removing " + n + " children from parent A");210 for (var i = 0; i < n; i++)211 {212 childrenA = parentA.children;213 numberA = (childrenA != null)? childrenA.length: 0;214 if (numberA > 0)215 {216 var k = Math.floor(Math.random() * numberA);217 parentA.remove(k);218 }219 }220 221 // 2nd parent222 n = Math.floor(Math.random() * 4); // how many to delete? at least 1 should remain223 n = Math.min(n, Math.max(0, numberB - 2));224 console.log(counter + " - removing " + n + " children from parent B");225 for (var i = 0; i < n; i++)226 {227 childrenB = parentB.children;228 numberB = (childrenB != null)? childrenB.length: 0;229 if (numberB > 0)230 {231 var k = Math.floor(Math.random() * numberB);232 parentB.remove(k);233 }234 }235 236 // second, insert a few children to each parent237 childrenA = parentA.children;238 childrenB = parentB.children;239 numberA = (childrenA != null)? childrenA.length: 0;240 numberB = (childrenB != null)? childrenB.length: 0;241 242 // 1st parent243 n = Math.floor(Math.random() * 4); // how many to insert?244 console.log(counter + " - inserting " + n + " children into parent A");245 for (var i = 0; i < n; i++)246 {247 childrenA = parentA.children;248 numberA = (childrenA != null)? childrenA.length: 0;249 if (numberA > 0)250 {251 var k = Math.floor(Math.random() * numberA);252 var x = Math.floor(Math.random() * 200);253 var y = Math.floor(Math.random() * 50);254 var number = Math.floor(Math.random() * 9000 + 1000);255 var child = graph.insertVertex(parentA, null, number.toString(), x, y, 120, 30);256 parentA.insert(child, k);257 }258 }259 260 // 2nd parent261 n = Math.floor(Math.random() * 4); // how many to insert?262 console.log(counter + " - inserting " + n + " children into parent B");263 for (var i = 0; i < n; i++)264 {265 childrenB = parentB.children;266 numberB = (childrenB != null)? childrenB.length: 0;267 if (numberB > 0)268 {269 var k = Math.floor(Math.random() * numberB);270 var x = Math.floor(Math.random() * 200);271 var y = Math.floor(Math.random() * 50);272 var number = Math.floor(Math.random() * 9000 + 1000);273 var child = graph.insertVertex(parentB, null, number.toString(), x, y, 120, 30);274 parentB.insert(child, k);275 }276 }277 278 // third, shuffle children in each parent279 childrenA = parentA.children;280 childrenB = parentB.children;281 numberA = (childrenA != null)? childrenA.length: 0;282 numberB = (childrenB != null)? childrenB.length: 0;283 284 // 1st parent285 n = Math.floor(Math.random() * numberA); // how many to shuffle?286 console.log(counter + " - moving " + n + " children inside parent A");287 for (var i = 0; i < n; i++)288 {289 childrenA = parentA.children;290 numberA = (childrenA != null)? childrenA.length: 0;291 if (numberA > 0)292 {293 var k = Math.floor(Math.random() * numberA); // from index294 var l = Math.floor(Math.random() * numberA); // to index295 var child = parentA.getChildAt(k);296 parentA.insert(child, l);297 }298 }299 300 // 2nd parent301 n = Math.floor(Math.random() * numberB); // how many to shuffle?302 console.log(counter + " - moving " + n + " children inside parent B");303 for (var i = 0; i < n; i++)304 {305 childrenB = parentB.children;306 numberB = (childrenB != null)? childrenB.length: 0;307 if (numberB > 0)308 {309 var k = Math.floor(Math.random() * numberB); // from index310 var l = Math.floor(Math.random() * numberB); // to index311 var child = parentB.getChildAt(k);312 parentB.insert(child, l);313 }314 }315 316 // fourth, exchange a few children between both parents317 childrenA = parentA.children;318 childrenB = parentB.children;319 numberA = (childrenA != null)? childrenA.length: 0;320 numberB = (childrenB != null)? childrenB.length: 0;321 322 // permute children323 var passes = Math.floor(Math.random() * numberA) + 1;324 console.log(counter + " - swapping " + passes + " children from parent A to parent B");325 326 for (var i = 0; i < passes; i++)327 {328 // which child to select from parent A329 var k = Math.floor(Math.random() * numberA);330 // where to insert it to parent B331 var l = Math.floor(Math.random() * (numberB + 1));332 graph.model.add(parentB, childrenA[k], l);333 334 numberA -= 1;335 numberB += 1;336 }337 var passes = Math.floor(Math.random() * numberB) + 1;338 console.log(counter + " - swapping " + passes + " children from parent B to parent A");339 340 for (var i = 0; i < passes; i++)341 {342 // which child to select from parent A343 var k = Math.floor(Math.random() * numberB);344 // where to insert it to parent B345 var l = Math.floor(Math.random() * (numberA + 1));346 graph.model.add(parentA, childrenB[k], l);347 numberA += 1;348 numberB -= 1;349 }350 }351 finally352 {353 graph.getModel().endUpdate();354 }355 }356 if (ui.dialog != null)357 {358 console.log('placeChildren halted');359 }360 else361 {362 ui.saveFile(null, function()363 {364 if (counter++ < max && ui.dialog == null)365 {366 console.log('placeChildren', counter);367 schedule();368 }369 else370 {371 console.log('placeChildren halted');372 }373 });374 }375 }, delay * jitter);376 }377 378 schedule();379 }380 else381 {382 ui.alert(mxResources.get('nothingIsSelected'));383 }384 });385 386 // Adds resource for action387 mxResources.parse('reorderChildren=Reorder children...');388 // Adds action389 ui.actions.addAction('reorderChildren', function()390 {391 var cells = graph.getSelectionCells().slice();392 393 if (cells.length > 0)394 {395 var delay = parseInt(prompt('Delay (ms)', defaultDelay));396 var max = parseInt(prompt('Cycles', defaultMax));397 var counter = 0;398 399 function schedule()400 {401 var jitter = 1 + 0.3 * (Math.random() - 0.5);402 403 window.setTimeout(function()404 {405 // assuming parent is the first cell selected406 var parent = cells[0];407 408 var children = parent.children;409 if (children != null && children.length > 1)410 {411 graph.getModel().beginUpdate();412 try413 {414 // permute children415 var number = children.length;416 var passes = Math.floor(Math.random() * number) + 1;417 console.log(counter + " - reordering in " + passes + " passes");418 419 for (var i = 0; i < passes; i++)420 {421 var k = Math.floor(Math.random() * number);422 graph.orderCells(true, [children[k]]);423 }424 }425 finally426 {427 graph.getModel().endUpdate();428 }429 }430 431 if (ui.dialog != null)432 {433 console.log('reorderChildren halted');434 }435 else436 {437 ui.saveFile(null, function()438 {439 if (counter++ < max && ui.dialog == null)440 {441 console.log('reorderChildren', counter);442 schedule();443 }444 else445 {446 console.log('reorderChildren halted');447 }448 });449 }450 }, delay * jitter);451 }452 453 schedule();454 }455 else456 {457 ui.alert(mxResources.get('nothingIsSelected'));458 }459 });460 461 var menu = ui.menus.get('extras');462 var oldFunct = menu.funct;463 464 menu.funct = function(menu, parent)465 {466 oldFunct.apply(this, arguments);467 468 ui.menus.addMenuItems(menu, ['-', 'randomLabel', 'reorderChildren', 'swapChildren', 'placeChildren'], parent);469 };...

Full Screen

Full Screen

loader.js

Source:loader.js Github

copy

Full Screen

1define([2 "dojo/_base/lang",3 "../_base",4 "dojo/_base/array",5 "dojo/_base/connect"6], function(lang,dd,array,connect){7 lang.getObject("dojox.dtl.tag.loader", true);8 var ddtl = dd.tag.loader;9 ddtl.BlockNode = lang.extend(function(name, nodelist){10 this.name = name;11 this.nodelist = nodelist; // Can be overridden12 },13 {14 "super": function(){15 if(this.parent){16 var html = this.parent.nodelist.dummyRender(this.context, null, true);17 if(typeof html == "string"){18 html = new String(html);19 }20 html.safe = true;21 return html;22 }23 return '';24 },25 render: function(context, buffer){26 var name = this.name;27 var nodelist = this.nodelist;28 var parent;29 if(buffer.blocks){30 var block = buffer.blocks[name];31 if(block){32 parent = block.parent;33 nodelist = block.nodelist;34 block.used = true;35 }36 }37 this.rendered = nodelist;38 context = context.push();39 this.context = context;40 this.parent = null;41 if(nodelist != this.nodelist){42 this.parent = this;43 }44 context.block = this;45 if(buffer.getParent){46 var bufferParent = buffer.getParent();47 var setParent = connect.connect(buffer, "onSetParent", function(node, up, root){48 if(up && root){49 buffer.setParent(bufferParent);50 }51 });52 }53 buffer = nodelist.render(context, buffer, this);54 setParent && connect.disconnect(setParent);55 context = context.pop();56 return buffer;57 },58 unrender: function(context, buffer){59 return this.rendered.unrender(context, buffer);60 },61 clone: function(buffer){62 return new this.constructor(this.name, this.nodelist.clone(buffer));63 },64 toString: function(){ return "dojox.dtl.tag.loader.BlockNode"; }65 });66 ddtl.ExtendsNode = lang.extend(function(getTemplate, nodelist, shared, parent, key){67 this.getTemplate = getTemplate;68 this.nodelist = nodelist;69 this.shared = shared;70 this.parent = parent;71 this.key = key;72 },73 {74 parents: {},75 getParent: function(context){76 var parent = this.parent;77 if(!parent){78 var string;79 parent = this.parent = context.get(this.key, false);80 if(!parent){81 throw new Error("extends tag used a variable that did not resolve");82 }83 if(typeof parent == "object"){84 var url = parent.url || parent.templatePath;85 if(parent.shared){86 this.shared = true;87 }88 if(url){89 parent = this.parent = url.toString();90 }else if(parent.templateString){91 // Allow the builder's string interning to work92 string = parent.templateString;93 parent = this.parent = " ";94 }else{95 parent = this.parent = this.parent.toString();96 }97 }98 if(parent && parent.indexOf("shared:") === 0){99 this.shared = true;100 parent = this.parent = parent.substring(7, parent.length);101 }102 }103 if(!parent){104 throw new Error("Invalid template name in 'extends' tag.");105 }106 if(parent.render){107 return parent;108 }109 if(this.parents[parent]){110 return this.parents[parent];111 }112 this.parent = this.getTemplate(string || dojox.dtl.text.getTemplateString(parent));113 if(this.shared){114 this.parents[parent] = this.parent;115 }116 return this.parent;117 },118 render: function(context, buffer){119 var parent = this.getParent(context);120 parent.blocks = parent.blocks || {};121 buffer.blocks = buffer.blocks || {};122 for(var i = 0, node; node = this.nodelist.contents[i]; i++){123 if(node instanceof dojox.dtl.tag.loader.BlockNode){124 var old = parent.blocks[node.name];125 if(old && old.nodelist != node.nodelist){126 // In a shared template, the individual blocks might change127 buffer = old.nodelist.unrender(context, buffer);128 }129 parent.blocks[node.name] = buffer.blocks[node.name] = {130 shared: this.shared,131 nodelist: node.nodelist,132 used: false133 }134 }135 }136 this.rendered = parent;137 return parent.nodelist.render(context, buffer, this);138 },139 unrender: function(context, buffer){140 return this.rendered.unrender(context, buffer, this);141 },142 toString: function(){ return "dojox.dtl.block.ExtendsNode"; }143 });144 ddtl.IncludeNode = lang.extend(function(path, constant, getTemplate, text, parsed){145 this._path = path;146 this.constant = constant;147 this.path = (constant) ? path : new dd._Filter(path);148 this.getTemplate = getTemplate;149 this.text = text;150 this.parsed = (arguments.length == 5) ? parsed : true;151 },152 {153 _cache: [{}, {}],154 render: function(context, buffer){155 var location = ((this.constant) ? this.path : this.path.resolve(context)).toString();156 var parsed = Number(this.parsed);157 var dirty = false;158 if(location != this.last){159 dirty = true;160 if(this.last){161 buffer = this.unrender(context, buffer);162 }163 this.last = location;164 }165 var cache = this._cache[parsed];166 if(parsed){167 if(!cache[location]){168 cache[location] = dd.text._resolveTemplateArg(location, true);169 }170 if(dirty){171 var template = this.getTemplate(cache[location]);172 this.rendered = template.nodelist;173 }174 return this.rendered.render(context, buffer, this);175 }else{176 if(this.text instanceof dd._TextNode){177 if(dirty){178 this.rendered = this.text;179 this.rendered.set(dd.text._resolveTemplateArg(location, true));180 }181 return this.rendered.render(context, buffer);182 }else{183 if(!cache[location]){184 var nodelist = [];185 var div = document.createElement("div");186 div.innerHTML = dd.text._resolveTemplateArg(location, true);187 var children = div.childNodes;188 while(children.length){189 var removed = div.removeChild(children[0]);190 nodelist.push(removed);191 }192 cache[location] = nodelist;193 }194 if(dirty){195 this.nodelist = [];196 var exists = true;197 for(var i = 0, child; child = cache[location][i]; i++){198 this.nodelist.push(child.cloneNode(true));199 }200 }201 for(var i = 0, node; node = this.nodelist[i]; i++){202 buffer = buffer.concat(node);203 }204 }205 }206 return buffer;207 },208 unrender: function(context, buffer){209 if(this.rendered){210 buffer = this.rendered.unrender(context, buffer);211 }212 if(this.nodelist){213 for(var i = 0, node; node = this.nodelist[i]; i++){214 buffer = buffer.remove(node);215 }216 }217 return buffer;218 },219 clone: function(buffer){220 return new this.constructor(this._path, this.constant, this.getTemplate, this.text.clone(buffer), this.parsed);221 }222 });223 lang.mixin(ddtl, {224 block: function(parser, token){225 var parts = token.contents.split();226 var name = parts[1];227 parser._blocks = parser._blocks || {};228 parser._blocks[name] = parser._blocks[name] || [];229 parser._blocks[name].push(name);230 var nodelist = parser.parse(["endblock", "endblock " + name]).rtrim();231 parser.next_token();232 return new dojox.dtl.tag.loader.BlockNode(name, nodelist);233 },234 extends_: function(parser, token){235 var parts = token.contents.split();236 var shared = false;237 var parent = null;238 var key = null;239 if(parts[1].charAt(0) == '"' || parts[1].charAt(0) == "'"){240 parent = parts[1].substring(1, parts[1].length - 1);241 }else{242 key = parts[1];243 }244 if(parent && parent.indexOf("shared:") == 0){245 shared = true;246 parent = parent.substring(7, parent.length);247 }248 var nodelist = parser.parse();249 return new dojox.dtl.tag.loader.ExtendsNode(parser.getTemplate, nodelist, shared, parent, key);250 },251 include: function(parser, token){252 var parts = token.contents.split();253 if(parts.length != 2){254 throw new Error(parts[0] + " tag takes one argument: the name of the template to be included");255 }256 var path = parts[1];257 var constant = false;258 if((path.charAt(0) == '"' || path.slice(-1) == "'") && path.charAt(0) == path.slice(-1)){259 path = path.slice(1, -1);260 constant = true;261 }262 return new ddtl.IncludeNode(path, constant, parser.getTemplate, parser.create_text_node());263 },264 ssi: function(parser, token){265 // We're going to treat things a little differently here.266 // First of all, this tag is *not* portable, so I'm not267 // concerned about it being a "drop in" replacement.268 // Instead, we'll just replicate the include tag, but with that269 // optional "parsed" parameter.270 var parts = token.contents.split();271 var parsed = false;272 if(parts.length == 3){273 parsed = (parts.pop() == "parsed");274 if(!parsed){275 throw new Error("Second (optional) argument to ssi tag must be 'parsed'");276 }277 }278 var node = ddtl.include(parser, new dd.Token(token.token_type, parts.join(" ")));279 node.parsed = parsed;280 return node;281 }282 });283 return dojox.dtl.tag.loader;...

Full Screen

Full Screen

htmlparser.js

Source:htmlparser.js Github

copy

Full Screen

1/**2 * html字符串转换成uNode节点3 * @file4 * @module UE5 * @since 1.2.6.16 */7/**8 * UEditor公用空间,UEditor所有的功能都挂载在该空间下9 * @unfile10 * @module UE11 */12/**13 * html字符串转换成uNode节点的静态方法14 * @method htmlparser15 * @param { String } htmlstr 要转换的html代码16 * @param { Boolean } ignoreBlank 若设置为true,转换的时候忽略\n\r\t等空白字符17 * @return { uNode } 给定的html片段转换形成的uNode对象18 * @example19 * ```javascript20 * var root = UE.htmlparser('<p><b>htmlparser</b></p>', true);21 * ```22 */23var htmlparser = UE.htmlparser = function (htmlstr,ignoreBlank) {24 //todo 原来的方式 [^"'<>\/] 有\/就不能配对上 <TD vAlign=top background=../AAA.JPG> 这样的标签了25 //先去掉了,加上的原因忘了,这里先记录26 var re_tag = /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/<>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g,27 re_attr = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g;28 //ie下取得的html可能会有\n存在,要去掉,在处理replace(/[\t\r\n]*/g,'');代码高量的\n不能去除29 var allowEmptyTags = {30 b:1,code:1,i:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,span:1,31 sub:1,img:1,sup:1,font:1,big:1,small:1,iframe:1,a:1,br:1,pre:132 };33 htmlstr = htmlstr.replace(new RegExp(domUtils.fillChar, 'g'), '');34 if(!ignoreBlank){35 htmlstr = htmlstr.replace(new RegExp('[\\r\\t\\n'+(ignoreBlank?'':' ')+']*<\/?(\\w+)\\s*(?:[^>]*)>[\\r\\t\\n'+(ignoreBlank?'':' ')+']*','g'), function(a,b){36 //br暂时单独处理37 if(b && allowEmptyTags[b.toLowerCase()]){38 return a.replace(/(^[\n\r]+)|([\n\r]+$)/g,'');39 }40 return a.replace(new RegExp('^[\\r\\n'+(ignoreBlank?'':' ')+']+'),'').replace(new RegExp('[\\r\\n'+(ignoreBlank?'':' ')+']+$'),'');41 });42 }43 var notTransAttrs = {44 'href':1,45 'src':146 };47 var uNode = UE.uNode,48 needParentNode = {49 'td':'tr',50 'tr':['tbody','thead','tfoot'],51 'tbody':'table',52 'th':'tr',53 'thead':'table',54 'tfoot':'table',55 'caption':'table',56 'li':['ul', 'ol'],57 'dt':'dl',58 'dd':'dl',59 'option':'select'60 },61 needChild = {62 'ol':'li',63 'ul':'li'64 };65 function text(parent, data) {66 if(needChild[parent.tagName]){67 var tmpNode = uNode.createElement(needChild[parent.tagName]);68 parent.appendChild(tmpNode);69 tmpNode.appendChild(uNode.createText(data));70 parent = tmpNode;71 }else{72 parent.appendChild(uNode.createText(data));73 }74 }75 function element(parent, tagName, htmlattr) {76 var needParentTag;77 if (needParentTag = needParentNode[tagName]) {78 var tmpParent = parent,hasParent;79 while(tmpParent.type != 'root'){80 if(utils.isArray(needParentTag) ? utils.indexOf(needParentTag, tmpParent.tagName) != -1 : needParentTag == tmpParent.tagName){81 parent = tmpParent;82 hasParent = true;83 break;84 }85 tmpParent = tmpParent.parentNode;86 }87 if(!hasParent){88 parent = element(parent, utils.isArray(needParentTag) ? needParentTag[0] : needParentTag)89 }90 }91 //按dtd处理嵌套92// if(parent.type != 'root' && !dtd[parent.tagName][tagName])93// parent = parent.parentNode;94 var elm = new uNode({95 parentNode:parent,96 type:'element',97 tagName:tagName.toLowerCase(),98 //是自闭合的处理一下99 children:dtd.$empty[tagName] ? null : []100 });101 //如果属性存在,处理属性102 if (htmlattr) {103 var attrs = {}, match;104 while (match = re_attr.exec(htmlattr)) {105 attrs[match[1].toLowerCase()] = notTransAttrs[match[1].toLowerCase()] ? (match[2] || match[3] || match[4]) : utils.unhtml(match[2] || match[3] || match[4])106 }107 elm.attrs = attrs;108 }109 //trace:3970110// //如果parent下不能放elm111// if(dtd.$inline[parent.tagName] && dtd.$block[elm.tagName] && !dtd[parent.tagName][elm.tagName]){112// parent = parent.parentNode;113// elm.parentNode = parent;114// }115 parent.children.push(elm);116 //如果是自闭合节点返回父亲节点117 return dtd.$empty[tagName] ? parent : elm118 }119 function comment(parent, data) {120 parent.children.push(new uNode({121 type:'comment',122 data:data,123 parentNode:parent124 }));125 }126 var match, currentIndex = 0, nextIndex = 0;127 //设置根节点128 var root = new uNode({129 type:'root',130 children:[]131 });132 var currentParent = root;133 while (match = re_tag.exec(htmlstr)) {134 currentIndex = match.index;135 try{136 if (currentIndex > nextIndex) {137 //text node138 text(currentParent, htmlstr.slice(nextIndex, currentIndex));139 }140 if (match[3]) {141 if(dtd.$cdata[currentParent.tagName]){142 text(currentParent, match[0]);143 }else{144 //start tag145 currentParent = element(currentParent, match[3].toLowerCase(), match[4]);146 }147 } else if (match[1]) {148 if(currentParent.type != 'root'){149 if(dtd.$cdata[currentParent.tagName] && !dtd.$cdata[match[1]]){150 text(currentParent, match[0]);151 }else{152 var tmpParent = currentParent;153 while(currentParent.type == 'element' && currentParent.tagName != match[1].toLowerCase()){154 currentParent = currentParent.parentNode;155 if(currentParent.type == 'root'){156 currentParent = tmpParent;157 throw 'break'158 }159 }160 //end tag161 currentParent = currentParent.parentNode;162 }163 }164 } else if (match[2]) {165 //comment166 comment(currentParent, match[2])167 }168 }catch(e){}169 nextIndex = re_tag.lastIndex;170 }171 //如果结束是文本,就有可能丢掉,所以这里手动判断一下172 //例如 <li>sdfsdfsdf<li>sdfsdfsdfsdf173 if (nextIndex < htmlstr.length) {174 text(currentParent, htmlstr.slice(nextIndex));175 }176 return root;...

Full Screen

Full Screen

hook-sync-nested.spec.js

Source:hook-sync-nested.spec.js Github

copy

Full Screen

1'use strict';2describe('serial', function () {3 describe('nested', function () {4 var calls = [];5 beforeEach(function () {6 calls.push('parent before');7 if (this.currentTest) {8 calls.push('parent before test ' + this.currentTest.title);9 }10 });11 afterEach(function () {12 calls.push('parent after');13 if (this.currentTest) {14 calls.push('parent after test ' + this.currentTest.title + ' ' + this.currentTest.state);15 }16 });17 it('foo', function () {18 expect(calls).to.eql([19 'parent before',20 'parent before test foo'21 ]);22 calls.push('foo');23 });24 it('bar', function () {25 expect(calls).to.eql([26 'parent before',27 'parent before test foo',28 'foo',29 'parent after',30 'parent after test foo passed',31 'parent before',32 'parent before test bar'33 ]);34 });35 describe('hooks', function () {36 beforeEach(function () {37 calls.push('before');38 if (this.currentTest) {39 calls.push('before test ' + this.currentTest.title);40 }41 });42 it('one', function () {43 expect(calls).to.eql([44 'parent before',45 'parent before test foo',46 'foo',47 'parent after',48 'parent after test foo passed',49 'parent before',50 'parent before test bar',51 'parent after',52 'parent after test bar passed',53 'parent before',54 'parent before test one',55 'before',56 'before test one'57 ]);58 calls.push('one');59 });60 it('two', function () {61 expect(calls).to.eql([62 'parent before',63 'parent before test foo',64 'foo',65 'parent after',66 'parent after test foo passed',67 'parent before',68 'parent before test bar',69 'parent after',70 'parent after test bar passed',71 'parent before',72 'parent before test one',73 'before',74 'before test one',75 'one',76 'after',77 'after test one passed',78 'parent after',79 'parent after test one passed',80 'parent before',81 'parent before test two',82 'before',83 'before test two'84 ]);85 calls.push('two');86 });87 afterEach(function () {88 calls.push('after');89 if (this.currentTest) {90 calls.push('after test ' + this.currentTest.title + ' ' + this.currentTest.state);91 }92 });93 });94 });...

Full Screen

Full Screen

Traversable.js

Source:Traversable.js Github

copy

Full Screen

1/**2 * A Traversable mixin.3 * @private4 */5Ext.define('Ext.mixin.Traversable', {6 extend: 'Ext.mixin.Mixin',7 mixinConfig: {8 id: 'traversable'9 },10 setParent: function(parent) {11 this.parent = parent;12 return this;13 },14 /**15 * @member Ext.Component16 * Returns `true` if this component has a parent.17 * @return {Boolean} `true` if this component has a parent.18 */19 hasParent: function() {20 return Boolean(this.parent);21 },22 /**23 * @member Ext.Component24 * Returns the parent of this component, if it has one.25 * @return {Ext.Component} The parent of this component.26 */27 getParent: function() {28 return this.parent;29 },30 getAncestors: function() {31 var ancestors = [],32 parent = this.getParent();33 while (parent) {34 ancestors.push(parent);35 parent = parent.getParent();36 }37 return ancestors;38 },39 getAncestorIds: function() {40 var ancestorIds = [],41 parent = this.getParent();42 while (parent) {43 ancestorIds.push(parent.getId());44 parent = parent.getParent();45 }46 return ancestorIds;47 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) return console.error(err);4 console.log('Test submitted to WebPageTest for %s', data.data.testUrl);5 console.log('Test ID: %s', data.data.testId);6});

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 wpt 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