language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
function isCollapsedBlockProp(node) { if (isCollapsedLineBreak(node) && !isExtraneousLineBreak(node)) { return true; } if (!isInlineNode(node) || node.nodeType != $_.Node.ELEMENT_NODE) { return false; } var hasCollapsedBlockPropChild = false; for (var i = 0; i < node.childNodes.length; i++) { if (!isInvisible(node.childNodes[i]) && !isCollapsedBlockProp(node.childNodes[i])) { return false; } if (isCollapsedBlockProp(node.childNodes[i])) { hasCollapsedBlockPropChild = true; } } return hasCollapsedBlockPropChild; }
function isCollapsedBlockProp(node) { if (isCollapsedLineBreak(node) && !isExtraneousLineBreak(node)) { return true; } if (!isInlineNode(node) || node.nodeType != $_.Node.ELEMENT_NODE) { return false; } var hasCollapsedBlockPropChild = false; for (var i = 0; i < node.childNodes.length; i++) { if (!isInvisible(node.childNodes[i]) && !isCollapsedBlockProp(node.childNodes[i])) { return false; } if (isCollapsedBlockProp(node.childNodes[i])) { hasCollapsedBlockPropChild = true; } } return hasCollapsedBlockPropChild; }
JavaScript
function isEffectivelyContained(node, range) { if (range.collapsed) { return false; } // "node is contained in range." if (isContained(node, range)) { return true; } // "node is range's start node, it is a Text node, and its length is // different from range's start offset." if (node == range.startContainer && node.nodeType == $_.Node.TEXT_NODE && getNodeLength(node) != range.startOffset) { return true; } // "node is range's end node, it is a Text node, and range's end offset is // not 0." if (node == range.endContainer && node.nodeType == $_.Node.TEXT_NODE && range.endOffset != 0) { return true; } // "node has at least one child; and all its children are effectively // contained in range; and either range's start node is not a descendant of // node or is not a Text node or range's start offset is zero; and either // range's end node is not a descendant of node or is not a Text node or // range's end offset is its end node's length." if (node.hasChildNodes() && $_(node.childNodes).every(function(child) { return isEffectivelyContained(child, range) }) && (!isDescendant(range.startContainer, node) || range.startContainer.nodeType != $_.Node.TEXT_NODE || range.startOffset == 0) && (!isDescendant(range.endContainer, node) || range.endContainer.nodeType != $_.Node.TEXT_NODE || range.endOffset == getNodeLength(range.endContainer))) { return true; } return false; }
function isEffectivelyContained(node, range) { if (range.collapsed) { return false; } // "node is contained in range." if (isContained(node, range)) { return true; } // "node is range's start node, it is a Text node, and its length is // different from range's start offset." if (node == range.startContainer && node.nodeType == $_.Node.TEXT_NODE && getNodeLength(node) != range.startOffset) { return true; } // "node is range's end node, it is a Text node, and range's end offset is // not 0." if (node == range.endContainer && node.nodeType == $_.Node.TEXT_NODE && range.endOffset != 0) { return true; } // "node has at least one child; and all its children are effectively // contained in range; and either range's start node is not a descendant of // node or is not a Text node or range's start offset is zero; and either // range's end node is not a descendant of node or is not a Text node or // range's end offset is its end node's length." if (node.hasChildNodes() && $_(node.childNodes).every(function(child) { return isEffectivelyContained(child, range) }) && (!isDescendant(range.startContainer, node) || range.startContainer.nodeType != $_.Node.TEXT_NODE || range.startOffset == 0) && (!isDescendant(range.endContainer, node) || range.endContainer.nodeType != $_.Node.TEXT_NODE || range.endOffset == getNodeLength(range.endContainer))) { return true; } return false; }
JavaScript
function isModifiableElement(node) { if (!isHtmlElement(node)) { return false; } if ($_( ["B", "EM", "I", "S", "SPAN", "STRIKE", "STRONG", "SUB", "SUP", "U"] ).indexOf(node.tagName) != -1) { if (node.attributes.length == 0) { return true; } if (node.attributes.length == 1 && $_( node ).hasAttribute("style")) { return true; } } if (node.tagName == "FONT" || node.tagName == "A") { var numAttrs = node.attributes.length; if ($_( node ).hasAttribute("style")) { numAttrs--; } if (node.tagName == "FONT") { if ($_( node ).hasAttribute("color")) { numAttrs--; } if ($_( node ).hasAttribute("face")) { numAttrs--; } if ($_( node ).hasAttribute("size")) { numAttrs--; } } if (node.tagName == "A" && $_( node ).hasAttribute("href")) { numAttrs--; } if (numAttrs == 0) { return true; } } return false; }
function isModifiableElement(node) { if (!isHtmlElement(node)) { return false; } if ($_( ["B", "EM", "I", "S", "SPAN", "STRIKE", "STRONG", "SUB", "SUP", "U"] ).indexOf(node.tagName) != -1) { if (node.attributes.length == 0) { return true; } if (node.attributes.length == 1 && $_( node ).hasAttribute("style")) { return true; } } if (node.tagName == "FONT" || node.tagName == "A") { var numAttrs = node.attributes.length; if ($_( node ).hasAttribute("style")) { numAttrs--; } if (node.tagName == "FONT") { if ($_( node ).hasAttribute("color")) { numAttrs--; } if ($_( node ).hasAttribute("face")) { numAttrs--; } if ($_( node ).hasAttribute("size")) { numAttrs--; } } if (node.tagName == "A" && $_( node ).hasAttribute("href")) { numAttrs--; } if (numAttrs == 0) { return true; } } return false; }
JavaScript
function areEquivalentValues(command, val1, val2) { if (val1 === null && val2 === null) { return true; } if (typeof val1 == "string" && typeof val2 == "string" && val1 == val2 && !("equivalentValues" in commands[command])) { return true; } if (typeof val1 == "string" && typeof val2 == "string" && "equivalentValues" in commands[command] && commands[command].equivalentValues(val1, val2)) { return true; } return false; }
function areEquivalentValues(command, val1, val2) { if (val1 === null && val2 === null) { return true; } if (typeof val1 == "string" && typeof val2 == "string" && val1 == val2 && !("equivalentValues" in commands[command])) { return true; } if (typeof val1 == "string" && typeof val2 == "string" && "equivalentValues" in commands[command] && commands[command].equivalentValues(val1, val2)) { return true; } return false; }
JavaScript
function normalizeFontSize(value) { // "Strip leading and trailing whitespace from value." // // Cheap hack, not following the actual algorithm. value = $_(value).trim(); // "If value is a valid floating point number, or would be a valid // floating point number if a single leading "+" character were // stripped:" if (/^[-+]?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?$/.test(value)) { var mode; // "If the first character of value is "+", delete the character // and let mode be "relative-plus"." if (value[0] == "+") { value = value.slice(1); mode = "relative-plus"; // "Otherwise, if the first character of value is "-", delete the // character and let mode be "relative-minus"." } else if (value[0] == "-") { value = value.slice(1); mode = "relative-minus"; // "Otherwise, let mode be "absolute"." } else { mode = "absolute"; } // "Apply the rules for parsing non-negative integers to value, and // let number be the result." // // Another cheap hack. var num = parseInt(value); // "If mode is "relative-plus", add three to number." if (mode == "relative-plus") { num += 3; } // "If mode is "relative-minus", negate number, then add three to // it." if (mode == "relative-minus") { num = 3 - num; } // "If number is less than one, let number equal 1." if (num < 1) { num = 1; } // "If number is greater than seven, let number equal 7." if (num > 7) { num = 7; } // "Set value to the string here corresponding to number:" [table // omitted] value = { 1: "xx-small", 2: "small", 3: "medium", 4: "large", 5: "x-large", 6: "xx-large", 7: "xxx-large" }[num]; } return value; }
function normalizeFontSize(value) { // "Strip leading and trailing whitespace from value." // // Cheap hack, not following the actual algorithm. value = $_(value).trim(); // "If value is a valid floating point number, or would be a valid // floating point number if a single leading "+" character were // stripped:" if (/^[-+]?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?$/.test(value)) { var mode; // "If the first character of value is "+", delete the character // and let mode be "relative-plus"." if (value[0] == "+") { value = value.slice(1); mode = "relative-plus"; // "Otherwise, if the first character of value is "-", delete the // character and let mode be "relative-minus"." } else if (value[0] == "-") { value = value.slice(1); mode = "relative-minus"; // "Otherwise, let mode be "absolute"." } else { mode = "absolute"; } // "Apply the rules for parsing non-negative integers to value, and // let number be the result." // // Another cheap hack. var num = parseInt(value); // "If mode is "relative-plus", add three to number." if (mode == "relative-plus") { num += 3; } // "If mode is "relative-minus", negate number, then add three to // it." if (mode == "relative-minus") { num = 3 - num; } // "If number is less than one, let number equal 1." if (num < 1) { num = 1; } // "If number is greater than seven, let number equal 7." if (num > 7) { num = 7; } // "Set value to the string here corresponding to number:" [table // omitted] value = { 1: "xx-small", 2: "small", 3: "medium", 4: "large", 5: "x-large", 6: "xx-large", 7: "xxx-large" }[num]; } return value; }
JavaScript
function isIndentationElement(node) { if (!isHtmlElement(node)) { return false; } if (node.tagName == "BLOCKQUOTE") { return true; } if (node.tagName != "DIV") { return false; } if (typeof node.style.length !== 'undefined') { for (var i = 0; i < node.style.length; i++) { // Approximate check if (/^(-[a-z]+-)?margin/.test(node.style[i])) { return true; } } } else { for (var s in node.style) { if (/^(-[a-z]+-)?margin/.test(s) && node.style[s] && node.style[s] !== 0) { return true; } } } return false; }
function isIndentationElement(node) { if (!isHtmlElement(node)) { return false; } if (node.tagName == "BLOCKQUOTE") { return true; } if (node.tagName != "DIV") { return false; } if (typeof node.style.length !== 'undefined') { for (var i = 0; i < node.style.length; i++) { // Approximate check if (/^(-[a-z]+-)?margin/.test(node.style[i])) { return true; } } } else { for (var s in node.style) { if (/^(-[a-z]+-)?margin/.test(s) && node.style[s] && node.style[s] !== 0) { return true; } } } return false; }
JavaScript
function normalizeSublists(item, range) { // "If item is not an li or it is not editable or its parent is not // editable, abort these steps." if (!isHtmlElement(item, "LI") || !isEditable(item) || !isEditable(item.parentNode)) { return; } // "Let new item be null." var newItem = null; // "While item has an ol or ul child:" while ($_(item.childNodes).some( function (node) { return isHtmlElement(node, ["OL", "UL"]) })) { // "Let child be the last child of item." var child = item.lastChild; // "If child is an ol or ul, or new item is null and child is a Text // node whose data consists of zero of more space characters:" if (isHtmlElement(child, ["OL", "UL"]) || (!newItem && child.nodeType == $_.Node.TEXT_NODE && /^[ \t\n\f\r]*$/.test(child.data))) { // "Set new item to null." newItem = null; // "Insert child into the parent of item immediately following // item, preserving ranges." movePreservingRanges(child, item.parentNode, 1 + getNodeIndex(item), range); // "Otherwise:" } else { // "If new item is null, let new item be the result of calling // createElement("li") on the ownerDocument of item, then insert // new item into the parent of item immediately after item." if (!newItem) { newItem = item.ownerDocument.createElement("li"); item.parentNode.insertBefore(newItem, item.nextSibling); } // "Insert child into new item as its first child, preserving // ranges." movePreservingRanges(child, newItem, 0, range); } } }
function normalizeSublists(item, range) { // "If item is not an li or it is not editable or its parent is not // editable, abort these steps." if (!isHtmlElement(item, "LI") || !isEditable(item) || !isEditable(item.parentNode)) { return; } // "Let new item be null." var newItem = null; // "While item has an ol or ul child:" while ($_(item.childNodes).some( function (node) { return isHtmlElement(node, ["OL", "UL"]) })) { // "Let child be the last child of item." var child = item.lastChild; // "If child is an ol or ul, or new item is null and child is a Text // node whose data consists of zero of more space characters:" if (isHtmlElement(child, ["OL", "UL"]) || (!newItem && child.nodeType == $_.Node.TEXT_NODE && /^[ \t\n\f\r]*$/.test(child.data))) { // "Set new item to null." newItem = null; // "Insert child into the parent of item immediately following // item, preserving ranges." movePreservingRanges(child, item.parentNode, 1 + getNodeIndex(item), range); // "Otherwise:" } else { // "If new item is null, let new item be the result of calling // createElement("li") on the ownerDocument of item, then insert // new item into the parent of item immediately after item." if (!newItem) { newItem = item.ownerDocument.createElement("li"); item.parentNode.insertBefore(newItem, item.nextSibling); } // "Insert child into new item as its first child, preserving // ranges." movePreservingRanges(child, newItem, 0, range); } } }
JavaScript
function unNormalizeSublists(item, range) { // "If item is not an ol or ol or it is not editable or its parent is not // editable, abort these steps." if (!isHtmlElement(item, ["OL", "UL"]) || !isEditable(item)) { return; } var $list = jQuery(item); $list.children("ol,ul").each(function(index, sublist) { if (isHtmlElement(sublist.previousSibling, "LI")) { // move the sublist into the LI movePreservingRanges(sublist, sublist.previousSibling, sublist.previousSibling.childNodes.length, range); } }); }
function unNormalizeSublists(item, range) { // "If item is not an ol or ol or it is not editable or its parent is not // editable, abort these steps." if (!isHtmlElement(item, ["OL", "UL"]) || !isEditable(item)) { return; } var $list = jQuery(item); $list.children("ol,ul").each(function(index, sublist) { if (isHtmlElement(sublist.previousSibling, "LI")) { // move the sublist into the LI movePreservingRanges(sublist, sublist.previousSibling, sublist.previousSibling.childNodes.length, range); } }); }
JavaScript
function isBlockStartPoint(node, offset) { return (!node.parentNode && offset == 0) || (0 <= offset - 1 && offset - 1 < node.childNodes.length && isVisible(node.childNodes[offset - 1]) && (isBlockNode(node.childNodes[offset - 1]) || isHtmlElement(node.childNodes[offset - 1], "br"))); }
function isBlockStartPoint(node, offset) { return (!node.parentNode && offset == 0) || (0 <= offset - 1 && offset - 1 < node.childNodes.length && isVisible(node.childNodes[offset - 1]) && (isBlockNode(node.childNodes[offset - 1]) || isHtmlElement(node.childNodes[offset - 1], "br"))); }
JavaScript
function isBlockEndPoint(node, offset) { return (!node.parentNode && offset == getNodeLength(node)) || (offset < node.childNodes.length && isVisible(node.childNodes[offset]) && isBlockNode(node.childNodes[offset])); }
function isBlockEndPoint(node, offset) { return (!node.parentNode && offset == getNodeLength(node)) || (offset < node.childNodes.length && isVisible(node.childNodes[offset]) && isBlockNode(node.childNodes[offset])); }
JavaScript
function supplant ( str, obj ) { return str.replace( /\{([a-z0-9\-\_]+)\}/ig, function ( str, p1, offset, s ) { var replacement = obj[ p1 ] || str; return ( typeof replacement == 'function' ) ? replacement() : replacement; } ); }
function supplant ( str, obj ) { return str.replace( /\{([a-z0-9\-\_]+)\}/ig, function ( str, p1, offset, s ) { var replacement = obj[ p1 ] || str; return ( typeof replacement == 'function' ) ? replacement() : replacement; } ); }
JavaScript
function nsSel () { var strBldr = [], prx = ns; jQuery.each( arguments, function () { strBldr.push( '.' + ( this == '' ? prx : prx + '-' + this ) ); } ); return jQuery.trim( strBldr.join( ' ' ) ); }
function nsSel () { var strBldr = [], prx = ns; jQuery.each( arguments, function () { strBldr.push( '.' + ( this == '' ? prx : prx + '-' + this ) ); } ); return jQuery.trim( strBldr.join( ' ' ) ); }
JavaScript
function walkTree(elem, cbFn){ if (elem && elem.nodeType == 1) { cbFn(elem); var i = elem.childNodes.length; while (i--) { walkTree(elem.childNodes.item(i), cbFn); } } }
function walkTree(elem, cbFn){ if (elem && elem.nodeType == 1) { cbFn(elem); var i = elem.childNodes.length; while (i--) { walkTree(elem.childNodes.item(i), cbFn); } } }
JavaScript
function walkTreePost(elem, cbFn) { if (elem && elem.nodeType == 1) { var i = elem.childNodes.length; while (i--) { walkTree(elem.childNodes.item(i), cbFn); } cbFn(elem); } }
function walkTreePost(elem, cbFn) { if (elem && elem.nodeType == 1) { var i = elem.childNodes.length; while (i--) { walkTree(elem.childNodes.item(i), cbFn); } cbFn(elem); } }
JavaScript
function ptObjToArr(type, seg_item) { var arr = segData[type], len = arr.length; var out = Array(len); for(var i=0; i<len; i++) { out[i] = seg_item[arr[i]]; } return out; }
function ptObjToArr(type, seg_item) { var arr = segData[type], len = arr.length; var out = Array(len); for(var i=0; i<len; i++) { out[i] = seg_item[arr[i]]; } return out; }
JavaScript
function pasteElement(object) { var $object = jQuery(object), contents; // try to insert the element into the DOM with limit the editable host // this fails when an element is not allowed to be inserted if (!dom.insertIntoDOM($object, range, $editable, false)) { // if that is not possible, we unwrap the content and insert every child element contents = $object.contents(); // when a block level element was unwrapped, we at least insert a break if (dom.isBlockLevelElement(object) || dom.isListElement(object)) { pasteElement(jQuery('<br/>').get(0)); } // and now all children (starting from the back) for ( i = contents.length - 1; i >= 0; --i) { pasteElement(contents[i]); } } }
function pasteElement(object) { var $object = jQuery(object), contents; // try to insert the element into the DOM with limit the editable host // this fails when an element is not allowed to be inserted if (!dom.insertIntoDOM($object, range, $editable, false)) { // if that is not possible, we unwrap the content and insert every child element contents = $object.contents(); // when a block level element was unwrapped, we at least insert a break if (dom.isBlockLevelElement(object) || dom.isListElement(object)) { pasteElement(jQuery('<br/>').get(0)); } // and now all children (starting from the back) for ( i = contents.length - 1; i >= 0; --i) { pasteElement(contents[i]); } } }
JavaScript
function enableInslides(){ $.each($('.inslide'),function(index,value){ $(value).addClass('slide'); $(value).removeClass('inslide'); }); }
function enableInslides(){ $.each($('.inslide'),function(index,value){ $(value).addClass('slide'); $(value).removeClass('inslide'); }); }
JavaScript
function detectmob() { if( navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i) ){ return true; } else { return false; } }
function detectmob() { if( navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i) ){ return true; } else { return false; } }
JavaScript
function updateModeAddress(selected_id,mode,changeHash){ var main=$("#deck_title_span").text().trim(); var current=$('#'+selected_id).text().trim(); var title=''; if(main==current) title=main; else title=main+': '+current; //$.address.value(selected_id+'-'+mode); //$.address.title(selected_id+'-'+mode); //console.log(window.location); //window.location.hash=selected_id+'-'+mode; var qs=window.location.search; var tmp=qs.split("\/"); //console.log(tmp[0]); if(tmp[0]=='?url=main'){ //console.log(window.location); var n=qs.match(/\?url\=main\/deck\&deck\=([0-9]+)([a-z]*)/); //console.log(n[1]); window.location=window.location.pathname+'deck/'+n[1]+'_'+n[2]; }else{ if(changeHash) window.location=window.location.pathname+'#'+selected_id+'-'+mode; } //document.title=selected_id+'-'+mode; document.title=title; }
function updateModeAddress(selected_id,mode,changeHash){ var main=$("#deck_title_span").text().trim(); var current=$('#'+selected_id).text().trim(); var title=''; if(main==current) title=main; else title=main+': '+current; //$.address.value(selected_id+'-'+mode); //$.address.title(selected_id+'-'+mode); //console.log(window.location); //window.location.hash=selected_id+'-'+mode; var qs=window.location.search; var tmp=qs.split("\/"); //console.log(tmp[0]); if(tmp[0]=='?url=main'){ //console.log(window.location); var n=qs.match(/\?url\=main\/deck\&deck\=([0-9]+)([a-z]*)/); //console.log(n[1]); window.location=window.location.pathname+'deck/'+n[1]+'_'+n[2]; }else{ if(changeHash) window.location=window.location.pathname+'#'+selected_id+'-'+mode; } //document.title=selected_id+'-'+mode; document.title=title; }
JavaScript
function updateTabURLs(selected_id, type){ var tmp,absolute_pos=0; var selected_properties=getPropertiesFromId(selected_id); if (type=="slide"){ $('#slideview').css('min-height','780px'); $('#editlink').attr('onclick','show_deck_brand();editSlide('+selected_properties['deckId']+','+selected_properties['itemId']+','+selected_properties['pos']+');updateModeAddress("'+selected_id+'","edit",1)'); $('#discussionlink').attr('onclick','hide_deck_brand();showDiscussion(\'slide\','+selected_properties['itemId']+');updateModeAddress("'+selected_id+'","discussion",1)'); $('#usagelink').attr('onclick','hide_deck_brand();showSlideUsage('+selected_properties['itemId']+');updateModeAddress("'+selected_id+'","use",1)'); $('#questionslink').attr('onclick','hide_deck_brand();showSlideQuestions('+selected_properties['itemId']+');updateModeAddress("'+selected_id+'","quest",1)'); $('#historylink').attr('onclick','hide_deck_brand();showSlideRevisions('+selected_properties['itemId']+');updateModeAddress("'+selected_id+'","history",1)'); if($.trim($("#"+selected_id+"-hasNewRevision").text())=="1") $('#historylink').html("History<img title='New revision is available!' src='static/img/exclamation.gif'>"); else $('#historylink').html('History'); //get absolute_pos for the selected slide if (!$("#tree").jstree("get_selected")[0]) { tmp=$('.jstree-clicked')[0]?$('.jstree-clicked')[0].title:''; } else { tmp=$("#tree").jstree("get_selected")[0].children[1].title; } if (!tmp){ var hash=window.location.hash; var parameters=hash.split('#')[1]; var parts=getPropertiesFromHash(parameters); tmp=$('#'+parts['nodeId']).attr('title'); } tmp=tmp.split('|')[2]; absolute_pos=tmp.split(':')[1]; $('#playSlide').attr('href','playSync/style/'+style+'/transition/'+transition+'/deck/'+deck+'#'+selected_id+'-'+(parseInt(absolute_pos)-1)+'-view'); $('#shareLink').attr('onclick','showShareLink("slide","'+selected_properties['itemId']+'");'); $("#downloadDeck").css("display",'none'); $("#printDeck").css("display",'none'); $("#current_slide_number").text(absolute_pos); //$("#total_slides_number").text(); }else{ $('#shareLink').attr('onclick','showShareLink("deck","'+selected_properties['itemId']+'");'); $('#editlink').attr('onclick','hide_deck_brand();editDeck('+selected_properties['itemId']+');updateModeAddress("'+selected_id+'","edit",1)'); $('#discussionlink').attr('onclick','hide_deck_brand();showDiscussion(\'deck\','+selected_properties['itemId']+');updateModeAddress("'+selected_id+'","discussion",1)'); $('#usagelink').attr('onclick','hide_deck_brand();showDeckUsage('+selected_properties['itemId']+');updateModeAddress("'+selected_id+'","use",1)'); $('#questionslink').attr('onclick','hide_deck_brand();showDeckQuestions('+selected_properties['itemId']+');updateModeAddress("'+selected_id+'","quest",1)'); $('#historylink').attr('onclick','hide_deck_brand();showDeckRevisions('+selected_properties['itemId']+');updateModeAddress("'+selected_id+'","history",1)'); $('#historylink').html('History'); } $('#viewlink').attr('onclick','show_deck_brand();selectNode("'+selected_id+'");updateModeAddress("'+selected_id+'","view",1)'); }
function updateTabURLs(selected_id, type){ var tmp,absolute_pos=0; var selected_properties=getPropertiesFromId(selected_id); if (type=="slide"){ $('#slideview').css('min-height','780px'); $('#editlink').attr('onclick','show_deck_brand();editSlide('+selected_properties['deckId']+','+selected_properties['itemId']+','+selected_properties['pos']+');updateModeAddress("'+selected_id+'","edit",1)'); $('#discussionlink').attr('onclick','hide_deck_brand();showDiscussion(\'slide\','+selected_properties['itemId']+');updateModeAddress("'+selected_id+'","discussion",1)'); $('#usagelink').attr('onclick','hide_deck_brand();showSlideUsage('+selected_properties['itemId']+');updateModeAddress("'+selected_id+'","use",1)'); $('#questionslink').attr('onclick','hide_deck_brand();showSlideQuestions('+selected_properties['itemId']+');updateModeAddress("'+selected_id+'","quest",1)'); $('#historylink').attr('onclick','hide_deck_brand();showSlideRevisions('+selected_properties['itemId']+');updateModeAddress("'+selected_id+'","history",1)'); if($.trim($("#"+selected_id+"-hasNewRevision").text())=="1") $('#historylink').html("History<img title='New revision is available!' src='static/img/exclamation.gif'>"); else $('#historylink').html('History'); //get absolute_pos for the selected slide if (!$("#tree").jstree("get_selected")[0]) { tmp=$('.jstree-clicked')[0]?$('.jstree-clicked')[0].title:''; } else { tmp=$("#tree").jstree("get_selected")[0].children[1].title; } if (!tmp){ var hash=window.location.hash; var parameters=hash.split('#')[1]; var parts=getPropertiesFromHash(parameters); tmp=$('#'+parts['nodeId']).attr('title'); } tmp=tmp.split('|')[2]; absolute_pos=tmp.split(':')[1]; $('#playSlide').attr('href','playSync/style/'+style+'/transition/'+transition+'/deck/'+deck+'#'+selected_id+'-'+(parseInt(absolute_pos)-1)+'-view'); $('#shareLink').attr('onclick','showShareLink("slide","'+selected_properties['itemId']+'");'); $("#downloadDeck").css("display",'none'); $("#printDeck").css("display",'none'); $("#current_slide_number").text(absolute_pos); //$("#total_slides_number").text(); }else{ $('#shareLink').attr('onclick','showShareLink("deck","'+selected_properties['itemId']+'");'); $('#editlink').attr('onclick','hide_deck_brand();editDeck('+selected_properties['itemId']+');updateModeAddress("'+selected_id+'","edit",1)'); $('#discussionlink').attr('onclick','hide_deck_brand();showDiscussion(\'deck\','+selected_properties['itemId']+');updateModeAddress("'+selected_id+'","discussion",1)'); $('#usagelink').attr('onclick','hide_deck_brand();showDeckUsage('+selected_properties['itemId']+');updateModeAddress("'+selected_id+'","use",1)'); $('#questionslink').attr('onclick','hide_deck_brand();showDeckQuestions('+selected_properties['itemId']+');updateModeAddress("'+selected_id+'","quest",1)'); $('#historylink').attr('onclick','hide_deck_brand();showDeckRevisions('+selected_properties['itemId']+');updateModeAddress("'+selected_id+'","history",1)'); $('#historylink').html('History'); } $('#viewlink').attr('onclick','show_deck_brand();selectNode("'+selected_id+'");updateModeAddress("'+selected_id+'","view",1)'); }
JavaScript
function deleteWorkaroundHandler(event) { if (8/*backspace*/ != event.keyCode && 46/*del*/ != event.keyCode) { return false; } var rangeObj = Aloha.getSelection().getRangeAt(0); var startContainer = rangeObj.startContainer; //the hack is only relevant if after the deletion has been //performed we are inside a li of a nested list var $nestedList = jQuery(startContainer).closest('ul, ol'); if ( ! $nestedList.length ) { return false; } var $parentList = $nestedList.parent().closest('ul, ol'); if ( ! $parentList.length ) { return false; } var ranges = Aloha.getSelection().getAllRanges(); var actionPerformed = false; $parentList.each(function(){ actionPerformed = actionPerformed || fixListNesting(jQuery(this)); }); if (actionPerformed) { Aloha.getSelection().setRanges(ranges); for (var i = 0; i < ranges.length; i++) { ranges[i].detach(); } } return actionPerformed; }
function deleteWorkaroundHandler(event) { if (8/*backspace*/ != event.keyCode && 46/*del*/ != event.keyCode) { return false; } var rangeObj = Aloha.getSelection().getRangeAt(0); var startContainer = rangeObj.startContainer; //the hack is only relevant if after the deletion has been //performed we are inside a li of a nested list var $nestedList = jQuery(startContainer).closest('ul, ol'); if ( ! $nestedList.length ) { return false; } var $parentList = $nestedList.parent().closest('ul, ol'); if ( ! $parentList.length ) { return false; } var ranges = Aloha.getSelection().getAllRanges(); var actionPerformed = false; $parentList.each(function(){ actionPerformed = actionPerformed || fixListNesting(jQuery(this)); }); if (actionPerformed) { Aloha.getSelection().setRanges(ranges); for (var i = 0; i < ranges.length; i++) { ranges[i].detach(); } } return actionPerformed; }
JavaScript
function fixListNesting($list) { var actionPerformed = false; $list.children('ul, ol').each(function(){ Aloha.Log.debug("performing list-nesting cleanup"); if ( ! jQuery(this).prev('li').append(this).length ) { //if there is no preceding li, create a new one and append to that jQuery(this).parent().prepend(document.createElement('li')).append(this); } actionPerformed = true; }); return actionPerformed; }
function fixListNesting($list) { var actionPerformed = false; $list.children('ul, ol').each(function(){ Aloha.Log.debug("performing list-nesting cleanup"); if ( ! jQuery(this).prev('li').append(this).length ) { //if there is no preceding li, create a new one and append to that jQuery(this).parent().prepend(document.createElement('li')).append(this); } actionPerformed = true; }); return actionPerformed; }
JavaScript
function updateCommandState() { if (!options.markup) return; $controls.find('.btn').removeClass('active'); _.each(commands, function(command, name) { if (command.isActive && command.isActive()) { $controls.find('.btn.'+name).addClass('active'); } }); }
function updateCommandState() { if (!options.markup) return; $controls.find('.btn').removeClass('active'); _.each(commands, function(command, name) { if (command.isActive && command.isActive()) { $controls.find('.btn.'+name).addClass('active'); } }); }
JavaScript
function saveSelection() { if (window.getSelection) { var sel = window.getSelection(); if (sel.rangeCount > 0) { return sel.getRangeAt(0); } } else if (document.selection && document.selection.createRange) { // IE return document.selection.createRange(); } return null; }
function saveSelection() { if (window.getSelection) { var sel = window.getSelection(); if (sel.rangeCount > 0) { return sel.getRangeAt(0); } } else if (document.selection && document.selection.createRange) { // IE return document.selection.createRange(); } return null; }
JavaScript
function restoreSelection(range) { if (range) { if (window.getSelection) { var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } else if (document.selection && range.select) { // IE range.select(); } } }
function restoreSelection(range) { if (range) { if (window.getSelection) { var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } else if (document.selection && range.select) { // IE range.select(); } } }
JavaScript
function selectAll() { var range = document.createRange(); range.selectNodeContents($(activeElement)[0]); restoreSelection(range); }
function selectAll() { var range = document.createRange(); range.selectNodeContents($(activeElement)[0]); restoreSelection(range); }
JavaScript
function activate (el, opts) { options = {}; _.extend(options, defaultOptions, opts); // Deactivate previously active element deactivate(); // Make editable $(el).attr('contenteditable', true); activeElement = el; bindEvents(el); // Setup controls if (options.markup) { $controls = $(controlsTpl); $controls.appendTo($(options.controlsTarget)); } // Keyboard bindings if (options.markup) { function execLater(cmd) { return function(e) { e.preventDefault(); exec(cmd); }; } $(activeElement) .keydown('ctrl+s', execLater('save')) .keydown('ctrl+shift+e', execLater('em')) .keydown('ctrl+shift+5', execLater('h5')) .keydown('ctrl+shift+4', execLater('h4')) .keydown('ctrl+shift+3', execLater('h3')) .keydown('ctrl+shift+s', execLater('strong')) .keydown('ctrl+shift+c', execLater('code')) .keydown('ctrl+shift+q', execLater('quote')) .keydown('ctrl+shift+l', execLater('link')) .keydown('ctrl+shift+i', execLater('image')) .keydown('ctrl+shift+b', execLater('ul')) .keydown('ctrl+shift+n', execLater('ol')) .keydown('tab', execLater('indent')) .keydown('ctrl+shift+f', execLater('fullscreen')) .keydown('ctrl+shift+h', execLater('htmlCode')) .keydown('ctrl+shift+r', execLater('removeFormat')) .keydown('shift+tab', execLater('outdent')); } $(activeElement).focus(); updateCommandState(); desemantifyContents($(activeElement)); // Use <b>, <i> and <font face="monospace"> instead of style attributes. // This is convenient because these inline element can easily be replaced // by their more semantic counterparts (<strong>, <em> and <code>). document.execCommand('styleWithCSS', false, false); $('.proper-commands a').click(function(e) { if(!$(this).hasClass('button_inactive')){ e.preventDefault(); $(activeElement).focus(); exec($(e.currentTarget).attr('command')); updateCommandState(); setTimeout(function() { events.trigger('changed'); }, 10); } }); //enable color picker $('#color-picker').colorPicker(); }
function activate (el, opts) { options = {}; _.extend(options, defaultOptions, opts); // Deactivate previously active element deactivate(); // Make editable $(el).attr('contenteditable', true); activeElement = el; bindEvents(el); // Setup controls if (options.markup) { $controls = $(controlsTpl); $controls.appendTo($(options.controlsTarget)); } // Keyboard bindings if (options.markup) { function execLater(cmd) { return function(e) { e.preventDefault(); exec(cmd); }; } $(activeElement) .keydown('ctrl+s', execLater('save')) .keydown('ctrl+shift+e', execLater('em')) .keydown('ctrl+shift+5', execLater('h5')) .keydown('ctrl+shift+4', execLater('h4')) .keydown('ctrl+shift+3', execLater('h3')) .keydown('ctrl+shift+s', execLater('strong')) .keydown('ctrl+shift+c', execLater('code')) .keydown('ctrl+shift+q', execLater('quote')) .keydown('ctrl+shift+l', execLater('link')) .keydown('ctrl+shift+i', execLater('image')) .keydown('ctrl+shift+b', execLater('ul')) .keydown('ctrl+shift+n', execLater('ol')) .keydown('tab', execLater('indent')) .keydown('ctrl+shift+f', execLater('fullscreen')) .keydown('ctrl+shift+h', execLater('htmlCode')) .keydown('ctrl+shift+r', execLater('removeFormat')) .keydown('shift+tab', execLater('outdent')); } $(activeElement).focus(); updateCommandState(); desemantifyContents($(activeElement)); // Use <b>, <i> and <font face="monospace"> instead of style attributes. // This is convenient because these inline element can easily be replaced // by their more semantic counterparts (<strong>, <em> and <code>). document.execCommand('styleWithCSS', false, false); $('.proper-commands a').click(function(e) { if(!$(this).hasClass('button_inactive')){ e.preventDefault(); $(activeElement).focus(); exec($(e.currentTarget).attr('command')); updateCommandState(); setTimeout(function() { events.trigger('changed'); }, 10); } }); //enable color picker $('#color-picker').colorPicker(); }
JavaScript
async _onRequestEnd(response) { if (response && response.clone) { response = await response.clone(); } const adapter = this.getAdapter(); response = await adapter.unserialize(response, this); if (response && response.data) { this.getModel(response.data); } return this.$model || response; }
async _onRequestEnd(response) { if (response && response.clone) { response = await response.clone(); } const adapter = this.getAdapter(); response = await adapter.unserialize(response, this); if (response && response.data) { this.getModel(response.data); } return this.$model || response; }
JavaScript
_getModel(method = 'GET') { let model; switch (method) { case 'GET': default: model = null; break; } return model; }
_getModel(method = 'GET') { let model; switch (method) { case 'GET': default: model = null; break; } return model; }
JavaScript
_buildURL(config) { config.url = this.$url = AmjsDataTypesBase.create('URL', { domain : this.host, path : this.path, params : this.params }); }
_buildURL(config) { config.url = this.$url = AmjsDataTypesBase.create('URL', { domain : this.host, path : this.path, params : this.params }); }
JavaScript
_buildRequestConfig(config = {}) { config.headers = this.headers; config.method = this.method; config.params = this.params; this._buildURL(config); if (['POST', 'PUT', 'PATCH'].includes(this.method)) { const model = this.getModel(this.body); config.body = AmjsDataTypesBase.is('Object', model) ? model.toJSON() : model || this.body; this.$model = null; } }
_buildRequestConfig(config = {}) { config.headers = this.headers; config.method = this.method; config.params = this.params; this._buildURL(config); if (['POST', 'PUT', 'PATCH'].includes(this.method)) { const model = this.getModel(this.body); config.body = AmjsDataTypesBase.is('Object', model) ? model.toJSON() : model || this.body; this.$model = null; } }
JavaScript
json() { return new Promise(resolve => { resolve(JSON.parse(this.$value)); }); }
json() { return new Promise(resolve => { resolve(JSON.parse(this.$value)); }); }
JavaScript
function markdownTable(table, options) { const settings = options || {} const align = (settings.align || []).concat() const stringLength = settings.stringLength || defaultStringLength /** @type {number[]} Character codes as symbols for alignment per column. */ const alignments = [] let rowIndex = -1 /** @type {string[][]} Cells per row. */ const cellMatrix = [] /** @type {number[][]} Sizes of each cell per row. */ const sizeMatrix = [] /** @type {number[]} */ const longestCellByColumn = [] let mostCellsPerRow = 0 /** @type {number} */ let columnIndex /** @type {string[]} Cells of current row */ let row /** @type {number[]} Sizes of current row */ let sizes /** @type {number} Sizes of current cell */ let size /** @type {string} Current cell */ let cell /** @type {string[]} Chunks of current line. */ let line /** @type {string} */ let before /** @type {string} */ let after /** @type {number} */ let code // This is a superfluous loop if we don’t align delimiters, but otherwise we’d // do superfluous work when aligning, so optimize for aligning. while (++rowIndex < table.length) { columnIndex = -1 row = [] sizes = [] if (table[rowIndex].length > mostCellsPerRow) { mostCellsPerRow = table[rowIndex].length } while (++columnIndex < table[rowIndex].length) { cell = serialize(table[rowIndex][columnIndex]) if (settings.alignDelimiters !== false) { size = stringLength(cell) sizes[columnIndex] = size if ( longestCellByColumn[columnIndex] === undefined || size > longestCellByColumn[columnIndex] ) { longestCellByColumn[columnIndex] = size } } row.push(cell) } cellMatrix[rowIndex] = row sizeMatrix[rowIndex] = sizes } // Figure out which alignments to use. columnIndex = -1 if (typeof align === 'object' && 'length' in align) { while (++columnIndex < mostCellsPerRow) { alignments[columnIndex] = toAlignment(align[columnIndex]) } } else { code = toAlignment(align) while (++columnIndex < mostCellsPerRow) { alignments[columnIndex] = code } } // Inject the alignment row. columnIndex = -1 row = [] sizes = [] while (++columnIndex < mostCellsPerRow) { code = alignments[columnIndex] before = '' after = '' if (code === 99 /* `c` */ ) { before = ':' after = ':' } else if (code === 108 /* `l` */ ) { before = ':' } else if (code === 114 /* `r` */ ) { after = ':' } // There *must* be at least one hyphen-minus in each alignment cell. size = settings.alignDelimiters === false ? 1 : Math.max( 1, longestCellByColumn[columnIndex] - before.length - after.length ) cell = before + '-'.repeat(size) + after if (settings.alignDelimiters !== false) { size = before.length + size + after.length if (size > longestCellByColumn[columnIndex]) { longestCellByColumn[columnIndex] = size } sizes[columnIndex] = size } row[columnIndex] = cell } // Inject the alignment row. cellMatrix.splice(1, 0, row) sizeMatrix.splice(1, 0, sizes) rowIndex = -1 /** @type {string[]} */ const lines = [] while (++rowIndex < cellMatrix.length) { row = cellMatrix[rowIndex] sizes = sizeMatrix[rowIndex] columnIndex = -1 line = [] while (++columnIndex < mostCellsPerRow) { cell = row[columnIndex] || '' before = '' after = '' if (settings.alignDelimiters !== false) { size = longestCellByColumn[columnIndex] - (sizes[columnIndex] || 0) code = alignments[columnIndex] if (code === 114 /* `r` */ ) { before = ' '.repeat(size) } else if (code === 99 /* `c` */ ) { if (size % 2) { before = ' '.repeat(size / 2 + 0.5) after = ' '.repeat(size / 2 - 0.5) } else { before = ' '.repeat(size / 2) after = before } } else { after = ' '.repeat(size) } } if (settings.delimiterStart !== false && !columnIndex) { line.push('|') } if ( settings.padding !== false && // Don’t add the opening space if we’re not aligning and the cell is // empty: there will be a closing space. !(settings.alignDelimiters === false && cell === '') && (settings.delimiterStart !== false || columnIndex) ) { line.push(' ') } if (settings.alignDelimiters !== false) { line.push(before) } line.push(cell) if (settings.alignDelimiters !== false) { line.push(after) } if (settings.padding !== false) { line.push(' ') } if ( settings.delimiterEnd !== false || columnIndex !== mostCellsPerRow - 1 ) { line.push('|') } } lines.push( settings.delimiterEnd === false ? line.join('').replace(/ +$/, '') : line.join('') ) } return lines.join('\n') }
function markdownTable(table, options) { const settings = options || {} const align = (settings.align || []).concat() const stringLength = settings.stringLength || defaultStringLength /** @type {number[]} Character codes as symbols for alignment per column. */ const alignments = [] let rowIndex = -1 /** @type {string[][]} Cells per row. */ const cellMatrix = [] /** @type {number[][]} Sizes of each cell per row. */ const sizeMatrix = [] /** @type {number[]} */ const longestCellByColumn = [] let mostCellsPerRow = 0 /** @type {number} */ let columnIndex /** @type {string[]} Cells of current row */ let row /** @type {number[]} Sizes of current row */ let sizes /** @type {number} Sizes of current cell */ let size /** @type {string} Current cell */ let cell /** @type {string[]} Chunks of current line. */ let line /** @type {string} */ let before /** @type {string} */ let after /** @type {number} */ let code // This is a superfluous loop if we don’t align delimiters, but otherwise we’d // do superfluous work when aligning, so optimize for aligning. while (++rowIndex < table.length) { columnIndex = -1 row = [] sizes = [] if (table[rowIndex].length > mostCellsPerRow) { mostCellsPerRow = table[rowIndex].length } while (++columnIndex < table[rowIndex].length) { cell = serialize(table[rowIndex][columnIndex]) if (settings.alignDelimiters !== false) { size = stringLength(cell) sizes[columnIndex] = size if ( longestCellByColumn[columnIndex] === undefined || size > longestCellByColumn[columnIndex] ) { longestCellByColumn[columnIndex] = size } } row.push(cell) } cellMatrix[rowIndex] = row sizeMatrix[rowIndex] = sizes } // Figure out which alignments to use. columnIndex = -1 if (typeof align === 'object' && 'length' in align) { while (++columnIndex < mostCellsPerRow) { alignments[columnIndex] = toAlignment(align[columnIndex]) } } else { code = toAlignment(align) while (++columnIndex < mostCellsPerRow) { alignments[columnIndex] = code } } // Inject the alignment row. columnIndex = -1 row = [] sizes = [] while (++columnIndex < mostCellsPerRow) { code = alignments[columnIndex] before = '' after = '' if (code === 99 /* `c` */ ) { before = ':' after = ':' } else if (code === 108 /* `l` */ ) { before = ':' } else if (code === 114 /* `r` */ ) { after = ':' } // There *must* be at least one hyphen-minus in each alignment cell. size = settings.alignDelimiters === false ? 1 : Math.max( 1, longestCellByColumn[columnIndex] - before.length - after.length ) cell = before + '-'.repeat(size) + after if (settings.alignDelimiters !== false) { size = before.length + size + after.length if (size > longestCellByColumn[columnIndex]) { longestCellByColumn[columnIndex] = size } sizes[columnIndex] = size } row[columnIndex] = cell } // Inject the alignment row. cellMatrix.splice(1, 0, row) sizeMatrix.splice(1, 0, sizes) rowIndex = -1 /** @type {string[]} */ const lines = [] while (++rowIndex < cellMatrix.length) { row = cellMatrix[rowIndex] sizes = sizeMatrix[rowIndex] columnIndex = -1 line = [] while (++columnIndex < mostCellsPerRow) { cell = row[columnIndex] || '' before = '' after = '' if (settings.alignDelimiters !== false) { size = longestCellByColumn[columnIndex] - (sizes[columnIndex] || 0) code = alignments[columnIndex] if (code === 114 /* `r` */ ) { before = ' '.repeat(size) } else if (code === 99 /* `c` */ ) { if (size % 2) { before = ' '.repeat(size / 2 + 0.5) after = ' '.repeat(size / 2 - 0.5) } else { before = ' '.repeat(size / 2) after = before } } else { after = ' '.repeat(size) } } if (settings.delimiterStart !== false && !columnIndex) { line.push('|') } if ( settings.padding !== false && // Don’t add the opening space if we’re not aligning and the cell is // empty: there will be a closing space. !(settings.alignDelimiters === false && cell === '') && (settings.delimiterStart !== false || columnIndex) ) { line.push(' ') } if (settings.alignDelimiters !== false) { line.push(before) } line.push(cell) if (settings.alignDelimiters !== false) { line.push(after) } if (settings.padding !== false) { line.push(' ') } if ( settings.delimiterEnd !== false || columnIndex !== mostCellsPerRow - 1 ) { line.push('|') } } lines.push( settings.delimiterEnd === false ? line.join('').replace(/ +$/, '') : line.join('') ) } return lines.join('\n') }
JavaScript
function Firestormstarter ( config, barrel, object, blower, logger ) { this.config = config || {} this.division = object.division || config.division || '' this.auditor = object.auditor this.concealed = object.concealed this.systemEntity = !!object.systemEntity this.name = object.name || 'Unknown flames' this.distinguishedName = this.name + distinguishPostfix( object.distinguish ) this.active = true this.context = object.context || '' this.path = this.context.split( SEPARATOR ) this.pathLength = this.path.length this.barrel = barrel this.object = object this.logger = logger this.blower = blower this.cronjobRefs = {} this.timeoutRefs = [] this.intervalRefs = [] this.object = require('../util/Extender').extend( this, this.object, path.join( __dirname, 'ext' ) ) this._events = functions( object ) this._serviceInfo = [] for (let i = 0; i < this._events.length; ++i) { let service = this._events[i] let params = _.parameterNames( object[ service ] ) this._serviceInfo[ service ] = { vargs: isLast(params, '...args'), params: params } } this.object.harconlog = logger.harconlog this.terms = object.terms || {} }
function Firestormstarter ( config, barrel, object, blower, logger ) { this.config = config || {} this.division = object.division || config.division || '' this.auditor = object.auditor this.concealed = object.concealed this.systemEntity = !!object.systemEntity this.name = object.name || 'Unknown flames' this.distinguishedName = this.name + distinguishPostfix( object.distinguish ) this.active = true this.context = object.context || '' this.path = this.context.split( SEPARATOR ) this.pathLength = this.path.length this.barrel = barrel this.object = object this.logger = logger this.blower = blower this.cronjobRefs = {} this.timeoutRefs = [] this.intervalRefs = [] this.object = require('../util/Extender').extend( this, this.object, path.join( __dirname, 'ext' ) ) this._events = functions( object ) this._serviceInfo = [] for (let i = 0; i < this._events.length; ++i) { let service = this._events[i] let params = _.parameterNames( object[ service ] ) this._serviceInfo[ service ] = { vargs: isLast(params, '...args'), params: params } } this.object.harconlog = logger.harconlog this.terms = object.terms || {} }
JavaScript
renderField(field){ // double destructuring const { meta: {touched, error } } = field; const className = `form-group ${touched && error ? 'has-danger': ''}`; return ( <div className={className}> <label>{field.label}</label> <input className='form-control' type='text' {...field.input} /> <div className='text-help'> {touched ? error : ''} </div> </div> ); }
renderField(field){ // double destructuring const { meta: {touched, error } } = field; const className = `form-group ${touched && error ? 'has-danger': ''}`; return ( <div className={className}> <label>{field.label}</label> <input className='form-control' type='text' {...field.input} /> <div className='text-help'> {touched ? error : ''} </div> </div> ); }
JavaScript
render () { const { handleSubmit } = this.props; return ( <form onSubmit={handleSubmit(this.onSubmit.bind(this))}> <Field name="title" label='Title for Post' component={this.renderField} /> <Field name="categories" label='Categories' component={this.renderField} /> <Field name="content" label='Post Content' component={this.renderField} /> <button type='submit' className='btn btn-primary'>Submit</button> <Link to='/' className='btn btn-danger'>Cancel</Link> </form> ); }
render () { const { handleSubmit } = this.props; return ( <form onSubmit={handleSubmit(this.onSubmit.bind(this))}> <Field name="title" label='Title for Post' component={this.renderField} /> <Field name="categories" label='Categories' component={this.renderField} /> <Field name="content" label='Post Content' component={this.renderField} /> <button type='submit' className='btn btn-primary'>Submit</button> <Link to='/' className='btn btn-danger'>Cancel</Link> </form> ); }
JavaScript
function handleErrors () { const args = Array.prototype.slice.call( arguments ); $.notify.onError( { 'title': 'Task Failed <%= error.message %>', 'message': 'See console.', 'sound': 'Sosumi' // See: https://github.com/mikaelbr/node-notifier#all-notification-options-with-their-defaults } ).apply( this, args ); $.util.beep(); // Beep 'sosumi' again. // Prevent the 'watch' task from stopping. this.emit( 'end' ); }
function handleErrors () { const args = Array.prototype.slice.call( arguments ); $.notify.onError( { 'title': 'Task Failed <%= error.message %>', 'message': 'See console.', 'sound': 'Sosumi' // See: https://github.com/mikaelbr/node-notifier#all-notification-options-with-their-defaults } ).apply( this, args ); $.util.beep(); // Beep 'sosumi' again. // Prevent the 'watch' task from stopping. this.emit( 'end' ); }
JavaScript
get checkoutPayloadDefaults() { /* prettier-ignore */ return { billingCity: '', billingCountry: '', billingPostCode: '', billingStateProvince: '', billingStreet: '', currency: OnePay.CURRENCY_VND, deliveryAddress: '', deliveryCity: '', deliveryCountry: '', customerEmail: null, // do not use '' since it will be validated with Email RegExp customerPhone: '', deliveryProvince: '', locale: OnePay.LOCALE_VN, title: 'VPC 3-Party', customerId: '', vpcAccessCode: '', vpcCommand: OnePay.COMMAND, vpcMerchant: '', vpcVersion: OnePay.VERSION, }; }
get checkoutPayloadDefaults() { /* prettier-ignore */ return { billingCity: '', billingCountry: '', billingPostCode: '', billingStateProvince: '', billingStreet: '', currency: OnePay.CURRENCY_VND, deliveryAddress: '', deliveryCity: '', deliveryCountry: '', customerEmail: null, // do not use '' since it will be validated with Email RegExp customerPhone: '', deliveryProvince: '', locale: OnePay.LOCALE_VN, title: 'VPC 3-Party', customerId: '', vpcAccessCode: '', vpcCommand: OnePay.COMMAND, vpcMerchant: '', vpcVersion: OnePay.VERSION, }; }
JavaScript
buildCheckoutUrl(payload) { return new Promise((resolve, reject) => { // Mảng các tham số chuyển tới Onepay Payment const data = Object.assign({}, this.checkoutPayloadDefaults, payload); const config = this.config; data.siteCode = config.merchantCode; data.paymentType = ''; // Input type checking try { this.validateCheckoutPayload(data); } catch (error) { reject(error.message); } /* prettier-ignore */ const arrParam = { language : data.language, order_code : data.orderId, order_email : data.customerEmail, order_mobile : data.customerPhone, payment_type : data.paymentType, price : data.amount.toString(), return_url : data.returnUrl, site_code : data.siteCode, transaction_info : data.transactionInfo, version : data.version, }; // Step 2. Create the target redirect URL at SohaPay server const redirectUrl = new URL(config.paymentGateway); const secureCode = []; Object.keys(arrParam) .sort() .forEach(key => { const value = arrParam[key]; if (value == null || value.length === 0) { // skip empty params (but they must be optional) return; } redirectUrl.searchParams.append(key, value); // no need to encode URI with URLSearchParams object if (value.length > 0) { // secureCode is digested from vnp_* params but they should not be URI encoded secureCode.push(`${key}=${value}`); } }); if (secureCode.length > 0) { redirectUrl.searchParams.append( 'secure_hash', toUpperCase(hashHmac('SHA256', secureCode.join('&'), pack(config.secureSecret))) ); } resolve(redirectUrl); }); }
buildCheckoutUrl(payload) { return new Promise((resolve, reject) => { // Mảng các tham số chuyển tới Onepay Payment const data = Object.assign({}, this.checkoutPayloadDefaults, payload); const config = this.config; data.siteCode = config.merchantCode; data.paymentType = ''; // Input type checking try { this.validateCheckoutPayload(data); } catch (error) { reject(error.message); } /* prettier-ignore */ const arrParam = { language : data.language, order_code : data.orderId, order_email : data.customerEmail, order_mobile : data.customerPhone, payment_type : data.paymentType, price : data.amount.toString(), return_url : data.returnUrl, site_code : data.siteCode, transaction_info : data.transactionInfo, version : data.version, }; // Step 2. Create the target redirect URL at SohaPay server const redirectUrl = new URL(config.paymentGateway); const secureCode = []; Object.keys(arrParam) .sort() .forEach(key => { const value = arrParam[key]; if (value == null || value.length === 0) { // skip empty params (but they must be optional) return; } redirectUrl.searchParams.append(key, value); // no need to encode URI with URLSearchParams object if (value.length > 0) { // secureCode is digested from vnp_* params but they should not be URI encoded secureCode.push(`${key}=${value}`); } }); if (secureCode.length > 0) { redirectUrl.searchParams.append( 'secure_hash', toUpperCase(hashHmac('SHA256', secureCode.join('&'), pack(config.secureSecret))) ); } resolve(redirectUrl); }); }
JavaScript
async listen(message, context=null) { return new Promise(resolve => { console.log(message) // Add basic flow if (message.includes('hey')) { const random = Math.floor(Math.random() * 10) var replyMessage = '' if (random % 2 == 0) { replyMessage = 'Hello' } else { replyMessage = 'Jarvis is listening!' } return resolve(replyMessage) } }) }
async listen(message, context=null) { return new Promise(resolve => { console.log(message) // Add basic flow if (message.includes('hey')) { const random = Math.floor(Math.random() * 10) var replyMessage = '' if (random % 2 == 0) { replyMessage = 'Hello' } else { replyMessage = 'Jarvis is listening!' } return resolve(replyMessage) } }) }
JavaScript
function useReducerWithHistory(reducer, state) { // Use a reference for persistent history const history = useRef([state]) // Set some state for the current index const [index, setIndex] = useState(0) // Function to determin if undo is possible function canUndo() { return (index > 0) } // Function to rewind index by 1 function undo() { setIndex(canUndo() ? index - 1 : index) } // Function to determine if redo is possible function canRedo() { return (index < history.current.length - 1) } // Function to increase index by 1 function redo() { setIndex(canRedo() ? index + 1 : index) } // Dispatcher that preserves history when calling the reducer function dispatch(action) { const newState = reducer(history.current[index], action) history.current = history.current.slice(0, index + 1) history.current.push(newState) setIndex(history.current.length - 1) } // Function to reset the history to the start function reset() { history.current = history.current.slice(0, 1) setIndex(0) } // Return the current state, and the new functions return [history.current[index], dispatch, canUndo, undo, canRedo, redo, reset] }
function useReducerWithHistory(reducer, state) { // Use a reference for persistent history const history = useRef([state]) // Set some state for the current index const [index, setIndex] = useState(0) // Function to determin if undo is possible function canUndo() { return (index > 0) } // Function to rewind index by 1 function undo() { setIndex(canUndo() ? index - 1 : index) } // Function to determine if redo is possible function canRedo() { return (index < history.current.length - 1) } // Function to increase index by 1 function redo() { setIndex(canRedo() ? index + 1 : index) } // Dispatcher that preserves history when calling the reducer function dispatch(action) { const newState = reducer(history.current[index], action) history.current = history.current.slice(0, index + 1) history.current.push(newState) setIndex(history.current.length - 1) } // Function to reset the history to the start function reset() { history.current = history.current.slice(0, 1) setIndex(0) } // Return the current state, and the new functions return [history.current[index], dispatch, canUndo, undo, canRedo, redo, reset] }
JavaScript
function dispatch(action) { const newState = reducer(history.current[index], action) history.current = history.current.slice(0, index + 1) history.current.push(newState) setIndex(history.current.length - 1) }
function dispatch(action) { const newState = reducer(history.current[index], action) history.current = history.current.slice(0, index + 1) history.current.push(newState) setIndex(history.current.length - 1) }
JavaScript
function isTie(squares) { // Convert the squares to an array if it is an object if (squares instanceof Object) { squares = Object.values(squares) } // If squares is an array, check if it is full if (Array.isArray(squares)) { return !squares.includes(null) } // Unknown type return false }
function isTie(squares) { // Convert the squares to an array if it is an object if (squares instanceof Object) { squares = Object.values(squares) } // If squares is an array, check if it is full if (Array.isArray(squares)) { return !squares.includes(null) } // Unknown type return false }
JavaScript
function core_sha1(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (24 - len % 32); x[((len + 64 >> 9) << 4) + 15] = len; var w = Array(80); var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; var e = -1009589776; for (var i = 0; i < x.length; i += 16) { var olda = a; var oldb = b; var oldc = c; var oldd = d; var olde = e; for (var j = 0; j < 80; j++) { if (j < 16) w[j] = x[i + j]; else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1); var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j))); e = d; d = c; c = rol(b, 30); b = a; a = t; } a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); e = safe_add(e, olde); } return Array(a, b, c, d, e); }
function core_sha1(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (24 - len % 32); x[((len + 64 >> 9) << 4) + 15] = len; var w = Array(80); var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; var e = -1009589776; for (var i = 0; i < x.length; i += 16) { var olda = a; var oldb = b; var oldc = c; var oldd = d; var olde = e; for (var j = 0; j < 80; j++) { if (j < 16) w[j] = x[i + j]; else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1); var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j))); e = d; d = c; c = rol(b, 30); b = a; a = t; } a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); e = safe_add(e, olde); } return Array(a, b, c, d, e); }
JavaScript
function sha1_ft(t, b, c, d) { if (t < 20) return (b & c) | ((~b) & d); if (t < 40) return b ^ c ^ d; if (t < 60) return (b & c) | (b & d) | (c & d); return b ^ c ^ d; }
function sha1_ft(t, b, c, d) { if (t < 20) return (b & c) | ((~b) & d); if (t < 40) return b ^ c ^ d; if (t < 60) return (b & c) | (b & d) | (c & d); return b ^ c ^ d; }
JavaScript
function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); }
function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); }
JavaScript
function binb2hex(binarray) { var hex_tab = "0123456789abcdef"; var str = ""; for (var i = 0; i < binarray.length * 4; i++) { str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF); } return str; }
function binb2hex(binarray) { var hex_tab = "0123456789abcdef"; var str = ""; for (var i = 0; i < binarray.length * 4; i++) { str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF); } return str; }
JavaScript
function addAttributesToHoverItems(itemsList) { if (itemsList.length === 0) { // nothing to do return; } const { getItemAttributes, addAttributesToElement } = shared.offers.identifiers; // cache for classinfo data const attributeCache = (function() { // the key to set/get values from const CACHE_INDEX = VERSION + '.getTradeOffers.cache'; // this will hold our cached values let values = {}; function save() { let value = JSON.stringify(values); if (value.length >= 50000) { // clear cache when it becomes too big values = {}; value = '{}'; } setStored(CACHE_INDEX, value); } // value is a hash of attributes // at the MOST, this will appear as: // { // spelled: true, // uncraft: true, // strange: true, // effect: 9 // } function store(key, attributes) { values[key] = attributes; } function get() { values = JSON.parse(getStored(CACHE_INDEX) || '{}'); } function key(itemEl) { const classinfo = itemEl.getAttribute('data-economy-item'); const [ , , classid, instanceid] = classinfo.split('/'); return [classid, instanceid].join(':'); } function getValue(key) { return values[key]; } return { save, get, store, key, getValue }; }()); let itemsChecked = 0; let cacheSaveTimer; // first load from cache attributeCache.get(); Array.from(itemsList) // process unusual items first .sort((a, b) => { const getValue = (itemEl) => { const unusualBorderColor = 'rgb(134, 80, 172)'; if (itemEl.style.borderColor === unusualBorderColor) { return 1; } return -1; }; return getValue(b) - getValue(a); }) .forEach((itemEl) => { // get hover for item to get item information // this requires an ajax request // classinfo format - "classinfo/440/192234515/3041550843" const classinfo = itemEl.getAttribute('data-economy-item'); const [ , appid, classid, instanceid] = classinfo.split('/'); // only check tf2 items if (appid !== '440') { // continue return; } const cacheKey = attributeCache.key(itemEl); const cachedValue = attributeCache.getValue(cacheKey); if (cachedValue) { // use cached attributes addAttributesToElement(itemEl, cachedValue); } else { const itemStr = [appid, classid, instanceid].join('/'); const uri = `economy/itemclasshover/${itemStr}?content_only=1&l=english`; const req = new WINDOW.CDelayedAJAXData(uri, 0); // this will space requests const delay = 5000 * Math.floor(itemsChecked / 50); itemsChecked++; setTimeout(() => { // we use this to get class info (names, descriptions) for each item // it would be much more efficient to use GetAssetClassInfo/v0001 but it requires an API key // this may be considered later req.RunWhenAJAXReady(() => { // 3rd element is a script tag containing item data const html = req.m_$Data[2].innerHTML; // extract the json for item with pattern... const match = html.match(/BuildHover\(\s*?\'economy_item_[A-z0-9]+\',\s*?(.*)\s\);/); try { // then parse it const item = JSON.parse(match[1]); const attributes = getItemAttributes(item); // then add the attributes to the element addAttributesToElement(itemEl, attributes); // store the attributes in cache attributeCache.store(cacheKey, attributes); // then save it n ms after the last completed request clearTimeout(cacheSaveTimer); cacheSaveTimer = setTimeout(attributeCache.save, 1000); } catch (e) { } }); }, delay); } }); }
function addAttributesToHoverItems(itemsList) { if (itemsList.length === 0) { // nothing to do return; } const { getItemAttributes, addAttributesToElement } = shared.offers.identifiers; // cache for classinfo data const attributeCache = (function() { // the key to set/get values from const CACHE_INDEX = VERSION + '.getTradeOffers.cache'; // this will hold our cached values let values = {}; function save() { let value = JSON.stringify(values); if (value.length >= 50000) { // clear cache when it becomes too big values = {}; value = '{}'; } setStored(CACHE_INDEX, value); } // value is a hash of attributes // at the MOST, this will appear as: // { // spelled: true, // uncraft: true, // strange: true, // effect: 9 // } function store(key, attributes) { values[key] = attributes; } function get() { values = JSON.parse(getStored(CACHE_INDEX) || '{}'); } function key(itemEl) { const classinfo = itemEl.getAttribute('data-economy-item'); const [ , , classid, instanceid] = classinfo.split('/'); return [classid, instanceid].join(':'); } function getValue(key) { return values[key]; } return { save, get, store, key, getValue }; }()); let itemsChecked = 0; let cacheSaveTimer; // first load from cache attributeCache.get(); Array.from(itemsList) // process unusual items first .sort((a, b) => { const getValue = (itemEl) => { const unusualBorderColor = 'rgb(134, 80, 172)'; if (itemEl.style.borderColor === unusualBorderColor) { return 1; } return -1; }; return getValue(b) - getValue(a); }) .forEach((itemEl) => { // get hover for item to get item information // this requires an ajax request // classinfo format - "classinfo/440/192234515/3041550843" const classinfo = itemEl.getAttribute('data-economy-item'); const [ , appid, classid, instanceid] = classinfo.split('/'); // only check tf2 items if (appid !== '440') { // continue return; } const cacheKey = attributeCache.key(itemEl); const cachedValue = attributeCache.getValue(cacheKey); if (cachedValue) { // use cached attributes addAttributesToElement(itemEl, cachedValue); } else { const itemStr = [appid, classid, instanceid].join('/'); const uri = `economy/itemclasshover/${itemStr}?content_only=1&l=english`; const req = new WINDOW.CDelayedAJAXData(uri, 0); // this will space requests const delay = 5000 * Math.floor(itemsChecked / 50); itemsChecked++; setTimeout(() => { // we use this to get class info (names, descriptions) for each item // it would be much more efficient to use GetAssetClassInfo/v0001 but it requires an API key // this may be considered later req.RunWhenAJAXReady(() => { // 3rd element is a script tag containing item data const html = req.m_$Data[2].innerHTML; // extract the json for item with pattern... const match = html.match(/BuildHover\(\s*?\'economy_item_[A-z0-9]+\',\s*?(.*)\s\);/); try { // then parse it const item = JSON.parse(match[1]); const attributes = getItemAttributes(item); // then add the attributes to the element addAttributesToElement(itemEl, attributes); // store the attributes in cache attributeCache.store(cacheKey, attributes); // then save it n ms after the last completed request clearTimeout(cacheSaveTimer); cacheSaveTimer = setTimeout(attributeCache.save, 1000); } catch (e) { } }); }, delay); } }); }
JavaScript
function show() { if (!$(dropdown).hasClass('open')) { $('>[data-toggle="dropdown"]', dropdown).trigger('click.bs.dropdown'); } }
function show() { if (!$(dropdown).hasClass('open')) { $('>[data-toggle="dropdown"]', dropdown).trigger('click.bs.dropdown'); } }
JavaScript
function hide() { if ($(dropdown).hasClass('open')) { $('>[data-toggle="dropdown"]', dropdown).trigger('click.bs.dropdown'); } }
function hide() { if ($(dropdown).hasClass('open')) { $('>[data-toggle="dropdown"]', dropdown).trigger('click.bs.dropdown'); } }
JavaScript
function locationOf(element, array, compare, start, end) { if (array.length === 0) return -1; start = start || 0; end = end || array.length; var pivot = (start + end) >> 1; var c = compare(element, array[pivot]); if (end - start <= 1) return c == -1 ? pivot - 1 : pivot; switch (c) { case -1: return locationOf(element, array, compare, start, pivot); case 0: return pivot; case 1: return locationOf(element, array, compare, pivot, end); }; }
function locationOf(element, array, compare, start, end) { if (array.length === 0) return -1; start = start || 0; end = end || array.length; var pivot = (start + end) >> 1; var c = compare(element, array[pivot]); if (end - start <= 1) return c == -1 ? pivot - 1 : pivot; switch (c) { case -1: return locationOf(element, array, compare, start, pivot); case 0: return pivot; case 1: return locationOf(element, array, compare, pivot, end); }; }
JavaScript
function parseXml(xml) { var dom = null; if (window.DOMParser) { try { dom = (new DOMParser()).parseFromString(xml, "text/xml"); } catch (e) { dom = null; } } else if (window.ActiveXObject) { try { dom = new ActiveXObject('Microsoft.XMLDOM'); dom.async = false; if (!dom.loadXML(xml)) // parse error .. window.alert(dom.parseError.reason + dom.parseError.srcText); } catch (e) { dom = null; } } else alert("oops"); return dom; }
function parseXml(xml) { var dom = null; if (window.DOMParser) { try { dom = (new DOMParser()).parseFromString(xml, "text/xml"); } catch (e) { dom = null; } } else if (window.ActiveXObject) { try { dom = new ActiveXObject('Microsoft.XMLDOM'); dom.async = false; if (!dom.loadXML(xml)) // parse error .. window.alert(dom.parseError.reason + dom.parseError.srcText); } catch (e) { dom = null; } } else alert("oops"); return dom; }
JavaScript
function notBlacklisted(domain) { for (let i = 0; i < config.domainlist.length; i++) { if (domain.includes(config.domainlist[i])) { return !config.blacklist; } } return config.blacklist; }
function notBlacklisted(domain) { for (let i = 0; i < config.domainlist.length; i++) { if (domain.includes(config.domainlist[i])) { return !config.blacklist; } } return config.blacklist; }
JavaScript
function bumpLogCount() { if (config.logrequestnum) { let today = new Date(); logPath = path.join(config.logdir, 'p2z_' + today.getFullYear() + '.json'); let data = {}; try { data = JSON.parse(fs.readFileSync(logPath, { encoding: 'utf8' })); } catch (ex) { console.log(ex); } let month = today.getMonth() + 1; if (!(month in data)) { data[month] = {}; } data[month].requests = ('requests' in data[month]) ? data[month].requests + 1 : 1; fs.writeFileSync(logPath, JSON.stringify(data), { encoding: 'utf8' }); } }
function bumpLogCount() { if (config.logrequestnum) { let today = new Date(); logPath = path.join(config.logdir, 'p2z_' + today.getFullYear() + '.json'); let data = {}; try { data = JSON.parse(fs.readFileSync(logPath, { encoding: 'utf8' })); } catch (ex) { console.log(ex); } let month = today.getMonth() + 1; if (!(month in data)) { data[month] = {}; } data[month].requests = ('requests' in data[month]) ? data[month].requests + 1 : 1; fs.writeFileSync(logPath, JSON.stringify(data), { encoding: 'utf8' }); } }
JavaScript
function proxifyUrls(feed, host) { return (config.deepproxy === true) ? feed.replace(MATCHURL, match => { return `${host}/proxy/file${getFilename(match).ext}?url=${encodeURIComponent(btoa(match.replace(XMLENCODEDAMP, '&')))}`; }) : feed; }
function proxifyUrls(feed, host) { return (config.deepproxy === true) ? feed.replace(MATCHURL, match => { return `${host}/proxy/file${getFilename(match).ext}?url=${encodeURIComponent(btoa(match.replace(XMLENCODEDAMP, '&')))}`; }) : feed; }
JavaScript
function logDomain(domain) { if (config.logrequestdomains) { let today = new Date(); logPath = path.join(config.logdir, 'p2z_' + today.getFullYear() + '.json'); let data = {}; try { data = JSON.parse(fs.readFileSync(logPath, { encoding: 'utf8' })); } catch (ex) { console.log(ex); } let month = today.getMonth() + 1; if (!(month in data)) { data[month] = {}; } let domains = [] if ('domains' in data[month]) { domains = data[month].domains; } if (domains.indexOf(domain) < 0) { domains.push(domain); data[month].domains = domains; fs.writeFileSync(logPath, JSON.stringify(data), { encoding: 'utf8' }); } } }
function logDomain(domain) { if (config.logrequestdomains) { let today = new Date(); logPath = path.join(config.logdir, 'p2z_' + today.getFullYear() + '.json'); let data = {}; try { data = JSON.parse(fs.readFileSync(logPath, { encoding: 'utf8' })); } catch (ex) { console.log(ex); } let month = today.getMonth() + 1; if (!(month in data)) { data[month] = {}; } let domains = [] if ('domains' in data[month]) { domains = data[month].domains; } if (domains.indexOf(domain) < 0) { domains.push(domain); data[month].domains = domains; fs.writeFileSync(logPath, JSON.stringify(data), { encoding: 'utf8' }); } } }
JavaScript
function nonsupported(useragent) { for (var i = 0; i < unsupportedAgents.length; i++) { if (useragent.os.includes(unsupportedAgents[i])) { return true; } } return false; }
function nonsupported(useragent) { for (var i = 0; i < unsupportedAgents.length; i++) { if (useragent.os.includes(unsupportedAgents[i])) { return true; } } return false; }
JavaScript
static disableD3Transitions() { //Inspired by http://stackoverflow.com/a/15387984 const injectedMethods = ['delay', 'duration', 'ease']; //Replace the transition method with a function that just returns //the original selection object _d3.selection.prototype.transition = function(){ return this; }; //Augment the selection prototype with the methods of transition //that are likely to be used and are not already in selection injectedMethods.forEach(method => { _d3.selection.prototype[method] = function(){ return this; }; }); }
static disableD3Transitions() { //Inspired by http://stackoverflow.com/a/15387984 const injectedMethods = ['delay', 'duration', 'ease']; //Replace the transition method with a function that just returns //the original selection object _d3.selection.prototype.transition = function(){ return this; }; //Augment the selection prototype with the methods of transition //that are likely to be used and are not already in selection injectedMethods.forEach(method => { _d3.selection.prototype[method] = function(){ return this; }; }); }
JavaScript
static to(src, dest) { if(!dest) { //This means we are using this method in the form //prettyData.svg().then(PrettyData.to('myfile.svg'))) dest = src; return src => this.to(src, dest); } return new Promise((resolve, reject) => { fs.rename(src, dest, error => { if(error) { return reject(error); } resolve(dest); }); }); }
static to(src, dest) { if(!dest) { //This means we are using this method in the form //prettyData.svg().then(PrettyData.to('myfile.svg'))) dest = src; return src => this.to(src, dest); } return new Promise((resolve, reject) => { fs.rename(src, dest, error => { if(error) { return reject(error); } resolve(dest); }); }); }
JavaScript
function initializeElements() { for (var i = 0; i < 3; i++) { elements.push(new Element(elementNames[i], initialPrices[i], initialRates[i])); document.getElementsByClassName(elementNames[i])[1].style.visibility = 'hidden'; } }
function initializeElements() { for (var i = 0; i < 3; i++) { elements.push(new Element(elementNames[i], initialPrices[i], initialRates[i])); document.getElementsByClassName(elementNames[i])[1].style.visibility = 'hidden'; } }
JavaScript
function debounce (fn, options = {}) { typeCheck(fn, 'function') options.wait = options.wait || 100 let timeout return function () { clearTimeout(timeout) timeout = setTimeout(() => { timeout = null fn.apply(this, arguments) }, options.wait) } }
function debounce (fn, options = {}) { typeCheck(fn, 'function') options.wait = options.wait || 100 let timeout return function () { clearTimeout(timeout) timeout = setTimeout(() => { timeout = null fn.apply(this, arguments) }, options.wait) } }
JavaScript
static calculateDayFromDate(dd, mm, yyyy) { const t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]; const week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; const monVal = (mm < 3) ? 1 : 0; yyyy -= monVal; const day = (yyyy + yyyy / 4 - yyyy / 100 + yyyy / 400 + t[mm - 1] + dd) % 7; return week[Math.floor(day)]; }
static calculateDayFromDate(dd, mm, yyyy) { const t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]; const week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; const monVal = (mm < 3) ? 1 : 0; yyyy -= monVal; const day = (yyyy + yyyy / 4 - yyyy / 100 + yyyy / 400 + t[mm - 1] + dd) % 7; return week[Math.floor(day)]; }
JavaScript
static calcayan(t) { const ln = 125.0445550 - 1934.1361849 * t + 0.0020762 * t * t; // Mean lunar node let off = 280.466449 + 36000.7698231 * t + 0.00031060 * t * t; // Mean Sun off = 17.23 * Math.sin(d2r * ln) + 1.27 * Math.sin(d2r * off) - (5025.64 + 1.11 * t) * t; off = (off - 85886.27) / 3600.0; return off; }
static calcayan(t) { const ln = 125.0445550 - 1934.1361849 * t + 0.0020762 * t * t; // Mean lunar node let off = 280.466449 + 36000.7698231 * t + 0.00031060 * t * t; // Mean Sun off = 17.23 * Math.sin(d2r * ln) + 1.27 * Math.sin(d2r * off) - (5025.64 + 1.11 * t) * t; off = (off - 85886.27) / 3600.0; return off; }
JavaScript
static lon2dmsz(x) { let d; let m; let s; x = Math.abs(x); d = Math.floor(x); m = (x - d); s = m * 60; m = Math.floor(s); s -= m; const z = Math.floor(d / 30); d %= 30; const str = `${zsign[z]} ${d}°${m}'${Math.floor(s * 60)}"`; return str; }
static lon2dmsz(x) { let d; let m; let s; x = Math.abs(x); d = Math.floor(x); m = (x - d); s = m * 60; m = Math.floor(s); s -= m; const z = Math.floor(d / 30); d %= 30; const str = `${zsign[z]} ${d}°${m}'${Math.floor(s * 60)}"`; return str; }
JavaScript
static lon2zodiac(x) { let d; let m; let s; x = Math.abs(x); d = Math.floor(x); m = (x - d); s = m * 60; m = Math.floor(s); s -= m; const z = Math.floor(d / 30); d %= 30; const str2 = `${d}° ${m}' ${Math.floor(s * 60)}" ${zsign[z]}`; prediction = `${vinter1} ${zsign[z]} ${vinter2} ${vinter4[z]}`; return str2; }
static lon2zodiac(x) { let d; let m; let s; x = Math.abs(x); d = Math.floor(x); m = (x - d); s = m * 60; m = Math.floor(s); s -= m; const z = Math.floor(d / 30); d %= 30; const str2 = `${d}° ${m}' ${Math.floor(s * 60)}" ${zsign[z]}`; prediction = `${vinter1} ${zsign[z]} ${vinter2} ${vinter4[z]}`; return str2; }
JavaScript
function restrictListProducts(prods, restrictions) { let products = []; for (let i=0; i<prods.length; i+=1) { var selected = true; var prod = prods[i]; for (var j = 0; j < restrictions.length; j++) { var restriction = restrictions[j]; if ((restriction == "LactoseFree") && (prod.lactoseFree != true) || (restriction == "NutsFree") && (prod.nutsFree != true) || (restriction == "Organic") && (prod.organic != true)){ selected = false; } } if (selected) { products.push(prod); } } // Custom sort function by price products.sort(function(elem1, elem2){ return elem1.price > elem2.price ? 1 : -1; }) return products; }
function restrictListProducts(prods, restrictions) { let products = []; for (let i=0; i<prods.length; i+=1) { var selected = true; var prod = prods[i]; for (var j = 0; j < restrictions.length; j++) { var restriction = restrictions[j]; if ((restriction == "LactoseFree") && (prod.lactoseFree != true) || (restriction == "NutsFree") && (prod.nutsFree != true) || (restriction == "Organic") && (prod.organic != true)){ selected = false; } } if (selected) { products.push(prod); } } // Custom sort function by price products.sort(function(elem1, elem2){ return elem1.price > elem2.price ? 1 : -1; }) return products; }
JavaScript
function populateListProductChoices(inputsDivId, displayDivId) { var inputs = document.getElementById(inputsDivId).getElementsByTagName("input"); var displayDiv = document.getElementById(displayDivId); var restrictions = []; for (var i = 0; i < inputs.length; i++) { var input = inputs[i]; if (input.checked) { restrictions.push(input.value); } } // displayDiv represents the <div> in the Products tab, which shows the product list, so we first set it empty displayDiv.innerHTML = ""; // obtain a reduced list of products based on restrictions var optionArray = restrictListProducts(products, restrictions); // for each item in the array, create a checkbox element, each containing information such as: // <input type="checkbox" name="product" value="Bread"> // <label for="Bread">Bread/label><br> for (i = 0; i < optionArray.length; i++) { var productName = optionArray[i].name; var productPrice = optionArray[i].price; var container = document.createElement("label"); container.className = "items-container"; container.appendChild(document.createTextNode(productName + " - " + productPrice + "$")); var checkbox = document.createElement("input"); checkbox.type = "checkbox"; checkbox.name = "product"; checkbox.value = productName; container.appendChild(checkbox); var checkmark = document.createElement("span"); checkmark.className = "checkmark"; container.appendChild(checkmark); displayDiv.appendChild(container); } }
function populateListProductChoices(inputsDivId, displayDivId) { var inputs = document.getElementById(inputsDivId).getElementsByTagName("input"); var displayDiv = document.getElementById(displayDivId); var restrictions = []; for (var i = 0; i < inputs.length; i++) { var input = inputs[i]; if (input.checked) { restrictions.push(input.value); } } // displayDiv represents the <div> in the Products tab, which shows the product list, so we first set it empty displayDiv.innerHTML = ""; // obtain a reduced list of products based on restrictions var optionArray = restrictListProducts(products, restrictions); // for each item in the array, create a checkbox element, each containing information such as: // <input type="checkbox" name="product" value="Bread"> // <label for="Bread">Bread/label><br> for (i = 0; i < optionArray.length; i++) { var productName = optionArray[i].name; var productPrice = optionArray[i].price; var container = document.createElement("label"); container.className = "items-container"; container.appendChild(document.createTextNode(productName + " - " + productPrice + "$")); var checkbox = document.createElement("input"); checkbox.type = "checkbox"; checkbox.name = "product"; checkbox.value = productName; container.appendChild(checkbox); var checkmark = document.createElement("span"); checkmark.className = "checkmark"; container.appendChild(checkmark); displayDiv.appendChild(container); } }
JavaScript
function selectedItems(){ var ele = document.getElementsByName("product"); var chosenProducts = []; var itemsContainer = document.getElementById('cart-items'); itemsContainer.innerHTML = ""; var notification = document.getElementById('cart-notification'); // build list of selected item var list = document.createElement("ul"); for (i = 0; i < ele.length; i++) { if (ele[i].checked) { var listElem = document.createElement("li"); listElem.innerHTML = ele[i].value + " - " + getPrice(ele[i].value) + "$"; list.appendChild(listElem); chosenProducts.push(ele[i].value); } } if (chosenProducts.length > 0) { itemsContainer.appendChild(list); notification.innerHTML = "Successfully put " + chosenProducts.length + " item(s) in the cart"; notification.className += " visible"; setTimeout( function() { var notification = document.getElementById('cart-notification'); notification.className = notification.className.replace(" visible", ""); }, 2000); } else { var text = document.createElement("p"); text.innerHTML = "You don't have any item in your cart"; itemsContainer.appendChild(text); } // add total price document.getElementById('total-price').innerHTML = "Total Price is " + getTotalPrice(chosenProducts); }
function selectedItems(){ var ele = document.getElementsByName("product"); var chosenProducts = []; var itemsContainer = document.getElementById('cart-items'); itemsContainer.innerHTML = ""; var notification = document.getElementById('cart-notification'); // build list of selected item var list = document.createElement("ul"); for (i = 0; i < ele.length; i++) { if (ele[i].checked) { var listElem = document.createElement("li"); listElem.innerHTML = ele[i].value + " - " + getPrice(ele[i].value) + "$"; list.appendChild(listElem); chosenProducts.push(ele[i].value); } } if (chosenProducts.length > 0) { itemsContainer.appendChild(list); notification.innerHTML = "Successfully put " + chosenProducts.length + " item(s) in the cart"; notification.className += " visible"; setTimeout( function() { var notification = document.getElementById('cart-notification'); notification.className = notification.className.replace(" visible", ""); }, 2000); } else { var text = document.createElement("p"); text.innerHTML = "You don't have any item in your cart"; itemsContainer.appendChild(text); } // add total price document.getElementById('total-price').innerHTML = "Total Price is " + getTotalPrice(chosenProducts); }
JavaScript
function UpdateMatch(matchData) { return Match.findById(matchData.id) .then(match=>{ match.teamOne.score = matchData.teamOneScore match.teamOne.conceded = matchData.teamTwoScore match.teamTwo.score = matchData.teamTwoScore match.teamTwo.conceded = matchData.teamOneScore if (match.teamOne.score > match.teamOne.conceded) { match.teamOne.point = 3 match.teamTwo.point = 0 match.winScore = matchData.teamOneScore match.loseScore = matchData.teamTwoScore match.winner.id = matchData.teamOne.id match.winner.score = matchData.teamOneScore match.winner.point = 3 match.looser.id = matchData.teamTwo.id match.looser.score = matchData.teamTwoScore match.looser.point = 0 } else if (match.teamOne.score === match.teamOne.conceded) { match.drow = true match.teamOne.point = 1 match.teamTwo.point = 1 match.looser.name = null match.winner.name = null match.looser.score = match.teamOne.score match.winner.score = match.teamOne.conceded } else { match.teamOne.point = 0 match.teamTwo.point = 3 match.winScore = matchData.teamTwoScore match.loseScore = matchData.teamOneScore match.winner.id = matchData.teamTwo.id match.winner.score = matchData.teamTwoScore match.winner.point = 3 match.looser.id = matchData.teamOne.id match.looser.score = matchData.teamOneScore match.looser.point = 0 } match.finished = true return match.save() }).catch(err=>{ console.log(err); }) }
function UpdateMatch(matchData) { return Match.findById(matchData.id) .then(match=>{ match.teamOne.score = matchData.teamOneScore match.teamOne.conceded = matchData.teamTwoScore match.teamTwo.score = matchData.teamTwoScore match.teamTwo.conceded = matchData.teamOneScore if (match.teamOne.score > match.teamOne.conceded) { match.teamOne.point = 3 match.teamTwo.point = 0 match.winScore = matchData.teamOneScore match.loseScore = matchData.teamTwoScore match.winner.id = matchData.teamOne.id match.winner.score = matchData.teamOneScore match.winner.point = 3 match.looser.id = matchData.teamTwo.id match.looser.score = matchData.teamTwoScore match.looser.point = 0 } else if (match.teamOne.score === match.teamOne.conceded) { match.drow = true match.teamOne.point = 1 match.teamTwo.point = 1 match.looser.name = null match.winner.name = null match.looser.score = match.teamOne.score match.winner.score = match.teamOne.conceded } else { match.teamOne.point = 0 match.teamTwo.point = 3 match.winScore = matchData.teamTwoScore match.loseScore = matchData.teamOneScore match.winner.id = matchData.teamTwo.id match.winner.score = matchData.teamTwoScore match.winner.point = 3 match.looser.id = matchData.teamOne.id match.looser.score = matchData.teamOneScore match.looser.point = 0 } match.finished = true return match.save() }).catch(err=>{ console.log(err); }) }
JavaScript
async function createTeam(newTeamData) { var deferred = q.defer(); var newTeam = new Team({ title: newTeamData.title, continent: newTeamData.continent, group: newTeamData.group, flag: newTeamData.flag, ranking: newTeamData.ranking, appearence: newTeamData.appearence, }) newTeam.save(function(err, data){ if (err) { deferred.reject(err) } else { deferred.resolve(data) } }) return deferred.promise; }
async function createTeam(newTeamData) { var deferred = q.defer(); var newTeam = new Team({ title: newTeamData.title, continent: newTeamData.continent, group: newTeamData.group, flag: newTeamData.flag, ranking: newTeamData.ranking, appearence: newTeamData.appearence, }) newTeam.save(function(err, data){ if (err) { deferred.reject(err) } else { deferred.resolve(data) } }) return deferred.promise; }
JavaScript
function findTeamsByName(name) { var deferred = q.defer() Team.findOne({ title: name }, function (err, team) { if (err) { deferred.reject(err) } else { deferred.resolve(team._id) } }) return deferred.promise; }
function findTeamsByName(name) { var deferred = q.defer() Team.findOne({ title: name }, function (err, team) { if (err) { deferred.reject(err) } else { deferred.resolve(team._id) } }) return deferred.promise; }
JavaScript
function updateTeamOneMatchResult(matchDetail) { return Team.findById(matchDetail.teamOne.id) .then(function ( team) { if (team.matches.indexOf(matchDetail._id) === -1) { team.opponents.push(matchDetail.teamTwo.id); team.play = team.play + 1, team.goalFor = team.goalFor + matchDetail.teamOne.score team.goalAganist = team.goalAganist + matchDetail.teamOne.conceded team.goalDiff = team.goalFor - team.goalAganist if (matchDetail.teamOne.point === 3) { team.win = team.win + 1 team.point = team.point + 3 team.resultSummer.push('w') } else if (matchDetail.teamOne.point === 1) { team.draw = team.draw + 1 team.point = team.point + 1 team.resultSummer.push('d') } else { team.lost = team.lost + 1 team.point = team.point + 0 team.resultSummer.push('l') } team.matches.push(matchDetail._id); return team.save() } }) }
function updateTeamOneMatchResult(matchDetail) { return Team.findById(matchDetail.teamOne.id) .then(function ( team) { if (team.matches.indexOf(matchDetail._id) === -1) { team.opponents.push(matchDetail.teamTwo.id); team.play = team.play + 1, team.goalFor = team.goalFor + matchDetail.teamOne.score team.goalAganist = team.goalAganist + matchDetail.teamOne.conceded team.goalDiff = team.goalFor - team.goalAganist if (matchDetail.teamOne.point === 3) { team.win = team.win + 1 team.point = team.point + 3 team.resultSummer.push('w') } else if (matchDetail.teamOne.point === 1) { team.draw = team.draw + 1 team.point = team.point + 1 team.resultSummer.push('d') } else { team.lost = team.lost + 1 team.point = team.point + 0 team.resultSummer.push('l') } team.matches.push(matchDetail._id); return team.save() } }) }
JavaScript
function updateTeamTwoMatchResult(matchDetail) { return Team.findById(matchDetail.teamTwo.id) .then(function (team) { console.log(team); if (team.matches.indexOf(matchDetail._id) == -1) { team.opponents.push(matchDetail.teamOne.id); team.play = team.play + 1, team.goalFor = team.goalFor + matchDetail.teamTwo.score team.goalAganist = team.goalAganist + matchDetail.teamTwo.conceded team.goalDiff = team.goalFor - team.goalAganist team.matches.push(matchDetail._id); if (matchDetail.teamTwo.point === 3) { team.win = team.win + 1 team.point = team.point + 3 team.resultSummer.push('w') } else if (matchDetail.teamTwo.point === 1) { team.draw = team.draw + 1 team.point = team.point + 1 team.resultSummer.push('d') } else { team.lost = team.lost + 1 team.point = team.point + 0 team.resultSummer.push('l') } return team.save() } }) }
function updateTeamTwoMatchResult(matchDetail) { return Team.findById(matchDetail.teamTwo.id) .then(function (team) { console.log(team); if (team.matches.indexOf(matchDetail._id) == -1) { team.opponents.push(matchDetail.teamOne.id); team.play = team.play + 1, team.goalFor = team.goalFor + matchDetail.teamTwo.score team.goalAganist = team.goalAganist + matchDetail.teamTwo.conceded team.goalDiff = team.goalFor - team.goalAganist team.matches.push(matchDetail._id); if (matchDetail.teamTwo.point === 3) { team.win = team.win + 1 team.point = team.point + 3 team.resultSummer.push('w') } else if (matchDetail.teamTwo.point === 1) { team.draw = team.draw + 1 team.point = team.point + 1 team.resultSummer.push('d') } else { team.lost = team.lost + 1 team.point = team.point + 0 team.resultSummer.push('l') } return team.save() } }) }
JavaScript
function updateMatch(req, res) { const matchDetail = req.body.match Match.UpdateMatch(matchDetail).then(response => { Team.updateTeamOneMatchResult(response).then(result=>{ Team.updateTeamTwoMatchResult(response).then(doc=>{ Match.getMatch().then(resData=>{ res.json(resData) }) }) }) }) }
function updateMatch(req, res) { const matchDetail = req.body.match Match.UpdateMatch(matchDetail).then(response => { Team.updateTeamOneMatchResult(response).then(result=>{ Team.updateTeamTwoMatchResult(response).then(doc=>{ Match.getMatch().then(resData=>{ res.json(resData) }) }) }) }) }
JavaScript
async function generateQTable() { // create a new qtable and limit its values ranging from -1 to 1 const qtable = new QTable(0, -1, 1); /* TODO: choose good values for alpha, gamma, epochs, episodes and maxScore Why are the curr */ const alpha = 1.0; // learning rate (0-1) const gamma = 1.0; // discount factor (0-1) const epochs = 5; // number of epochs const episodes = 100; // number of episodes per epoch const maxScore = 10; // max score of each episode const agent = $.Agent({ /** * Async update-callback to decide which action to take. * @param {$.Observations} obs * @return {Promise<$.EAction>} */ async update(obs) { const state = observationsToState(obs); const action = qtable.getBestAction(state); return action; }, /** * Async result-callback, called after update has been resolved. * @param {$.Observations} obs * @param {$.EAction} action * @param {$.Observations} newObs * @param {boolean} alive * @return {Promise<void>} */ async result(obs, action, newObs, alive) { // create the old and new states const s_t0 = observationsToState(obs); const s_t1 = observationsToState(newObs); // only update when the states are different if (s_t0 !== s_t1 || !alive) { /* TODO: update the q-value for the given state s_t0 and action */ qtable.set(s_t0, action, 0); } } }); // for each epoch... for (let epoch = 0; epoch < epochs; epoch++) { console.log(`training episodes ${epoch * episodes} - ${(epoch + 1) * episodes}`); // ...run each episode and accumulate the score let scoreAccumulated = 0; for (let episode = 0; episode < episodes; episode++) { // render only when the number of trainings correlates to // the showProgressFrequency const countTrainings = episode + epoch * epochs; const render = countTrainings % showProgressFrequency === 0; if(render){ await qtable.render(observationsToState); } // create and run a game given the settings const settings = $.Settings(maxScore); const score = await $.run(settings, agent, render, -renderFrameSkip); scoreAccumulated += score; } // print the score average and render the current state of the qtable console.log(`average score: ${scoreAccumulated / episodes}`); await qtable.render(observationsToState); } // save the qtable into a json-file await qtable.store('qtable'); console.log('training finished!'); }
async function generateQTable() { // create a new qtable and limit its values ranging from -1 to 1 const qtable = new QTable(0, -1, 1); /* TODO: choose good values for alpha, gamma, epochs, episodes and maxScore Why are the curr */ const alpha = 1.0; // learning rate (0-1) const gamma = 1.0; // discount factor (0-1) const epochs = 5; // number of epochs const episodes = 100; // number of episodes per epoch const maxScore = 10; // max score of each episode const agent = $.Agent({ /** * Async update-callback to decide which action to take. * @param {$.Observations} obs * @return {Promise<$.EAction>} */ async update(obs) { const state = observationsToState(obs); const action = qtable.getBestAction(state); return action; }, /** * Async result-callback, called after update has been resolved. * @param {$.Observations} obs * @param {$.EAction} action * @param {$.Observations} newObs * @param {boolean} alive * @return {Promise<void>} */ async result(obs, action, newObs, alive) { // create the old and new states const s_t0 = observationsToState(obs); const s_t1 = observationsToState(newObs); // only update when the states are different if (s_t0 !== s_t1 || !alive) { /* TODO: update the q-value for the given state s_t0 and action */ qtable.set(s_t0, action, 0); } } }); // for each epoch... for (let epoch = 0; epoch < epochs; epoch++) { console.log(`training episodes ${epoch * episodes} - ${(epoch + 1) * episodes}`); // ...run each episode and accumulate the score let scoreAccumulated = 0; for (let episode = 0; episode < episodes; episode++) { // render only when the number of trainings correlates to // the showProgressFrequency const countTrainings = episode + epoch * epochs; const render = countTrainings % showProgressFrequency === 0; if(render){ await qtable.render(observationsToState); } // create and run a game given the settings const settings = $.Settings(maxScore); const score = await $.run(settings, agent, render, -renderFrameSkip); scoreAccumulated += score; } // print the score average and render the current state of the qtable console.log(`average score: ${scoreAccumulated / episodes}`); await qtable.render(observationsToState); } // save the qtable into a json-file await qtable.store('qtable'); console.log('training finished!'); }
JavaScript
async result(obs, action, newObs, alive) { // create the old and new states const s_t0 = observationsToState(obs); const s_t1 = observationsToState(newObs); // only update when the states are different if (s_t0 !== s_t1 || !alive) { /* TODO: update the q-value for the given state s_t0 and action */ qtable.set(s_t0, action, 0); } }
async result(obs, action, newObs, alive) { // create the old and new states const s_t0 = observationsToState(obs); const s_t1 = observationsToState(newObs); // only update when the states are different if (s_t0 !== s_t1 || !alive) { /* TODO: update the q-value for the given state s_t0 and action */ qtable.set(s_t0, action, 0); } }
JavaScript
function Settings(maxScore, seed = Math.random()){ return { maxScore, seed, } }
function Settings(maxScore, seed = Math.random()){ return { maxScore, seed, } }
JavaScript
async function run(settings, agent, render = true, frameDelay = 10) { let alive = true; const bird = { distance: 0, height: CANVAS_HEIGHT / 2, velocity: 0, // ...settings.bird, } let score = ~~(bird.distance / PIPE_DISTANCE); const pipes = [ getNextPipe(settings.seed, score, bird.distance % PIPE_DISTANCE), ]; pipes[0].x -= PIPE_WIDTH_2; if (render) { await _.loadImages([ 'project/bird1.png', 'project/bird2.png', 'project/floor.png', 'project/crate.png', 'project/sign.png', 'project/background.png', ]); ctx.setTransform(scale, 0, 0, scale, 0, 0); ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = "high"; const render = () => { drawState(pipes, bird, score); if (alive && score <= settings.maxScore) { requestAnimationFrame(render); } } requestAnimationFrame(render); } if (agent.init instanceof Function) await agent.init(); let obs = getObservations(bird, pipes); while (score < settings.maxScore && alive) { const action = await agent.update(obs); score = ~~(bird.distance / PIPE_DISTANCE); if ((bird.distance + PIPE_WIDTH_2) % PIPE_DISTANCE === 0) { pipes.push(getNextPipe(settings.seed, score, 0)); if (pipes.length > MAX_PIPES) { pipes.shift(); } } bird.distance++; for (let pipe of pipes) { pipe.x--; } if (action === 1) { bird.velocity = JUMP_STRENGTH; } bird.velocity -= GRAVITY; bird.height -= bird.velocity; alive = !getCollision(bird, pipes); const newObs = getObservations(bird, pipes); if (agent.result instanceof Function) await agent.result(obs, action, newObs, alive); obs = newObs; if (render && (frameDelay === 0 || (frameDelay < 0 && bird.distance % -frameDelay === 0))) { await _.sleep(0); } if (frameDelay > 0) { await _.sleep(frameDelay); } } if (agent.finish instanceof Function){ await agent.finish(score, alive); } if(render){ await _.sleep(500); } return score; }
async function run(settings, agent, render = true, frameDelay = 10) { let alive = true; const bird = { distance: 0, height: CANVAS_HEIGHT / 2, velocity: 0, // ...settings.bird, } let score = ~~(bird.distance / PIPE_DISTANCE); const pipes = [ getNextPipe(settings.seed, score, bird.distance % PIPE_DISTANCE), ]; pipes[0].x -= PIPE_WIDTH_2; if (render) { await _.loadImages([ 'project/bird1.png', 'project/bird2.png', 'project/floor.png', 'project/crate.png', 'project/sign.png', 'project/background.png', ]); ctx.setTransform(scale, 0, 0, scale, 0, 0); ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = "high"; const render = () => { drawState(pipes, bird, score); if (alive && score <= settings.maxScore) { requestAnimationFrame(render); } } requestAnimationFrame(render); } if (agent.init instanceof Function) await agent.init(); let obs = getObservations(bird, pipes); while (score < settings.maxScore && alive) { const action = await agent.update(obs); score = ~~(bird.distance / PIPE_DISTANCE); if ((bird.distance + PIPE_WIDTH_2) % PIPE_DISTANCE === 0) { pipes.push(getNextPipe(settings.seed, score, 0)); if (pipes.length > MAX_PIPES) { pipes.shift(); } } bird.distance++; for (let pipe of pipes) { pipe.x--; } if (action === 1) { bird.velocity = JUMP_STRENGTH; } bird.velocity -= GRAVITY; bird.height -= bird.velocity; alive = !getCollision(bird, pipes); const newObs = getObservations(bird, pipes); if (agent.result instanceof Function) await agent.result(obs, action, newObs, alive); obs = newObs; if (render && (frameDelay === 0 || (frameDelay < 0 && bird.distance % -frameDelay === 0))) { await _.sleep(0); } if (frameDelay > 0) { await _.sleep(frameDelay); } } if (agent.finish instanceof Function){ await agent.finish(score, alive); } if(render){ await _.sleep(500); } return score; }
JavaScript
function main() { return through.obj(function (file, enc, cb) { if (file.isNull()) { cb(null, file); return; } if (file.isStream()) { cb(new PluginError("Process Imports", "Streaming not supported.")); } let data = file.contents.toString(); data = processImports(data); // Go to disk. fs.writeFileSync(file.path, data); return cb(); }); }
function main() { return through.obj(function (file, enc, cb) { if (file.isNull()) { cb(null, file); return; } if (file.isStream()) { cb(new PluginError("Process Imports", "Streaming not supported.")); } let data = file.contents.toString(); data = processImports(data); // Go to disk. fs.writeFileSync(file.path, data); return cb(); }); }
JavaScript
function smoosh(base, options = {}) { const smooshedSrc = returnSmooshed(base, options); const outputFile = `./${base}.${suffix}`; fs.writeFileSync(outputFile, smooshedSrc, 'utf8'); log.logSuccess(`Smooshed ${outputFile}`); }
function smoosh(base, options = {}) { const smooshedSrc = returnSmooshed(base, options); const outputFile = `./${base}.${suffix}`; fs.writeFileSync(outputFile, smooshedSrc, 'utf8'); log.logSuccess(`Smooshed ${outputFile}`); }
JavaScript
function replaceExportDeclareType(text) { const reT = /^export declare type /gm; const reI = /^export declare interface /gm; return text.replace(reT, 'export type ').replace(reI, 'export interface '); }
function replaceExportDeclareType(text) { const reT = /^export declare type /gm; const reI = /^export declare interface /gm; return text.replace(reT, 'export type ').replace(reI, 'export interface '); }
JavaScript
function linkFromFileToFile(sourceFile, targetFile) { const relativePathFromDirToDir = path.relative(sourceFile, path.dirname(targetFile)); const fileName = path.basename(targetFile, '.md'); if (fileName === 'README') { return relativePathFromDirToDir; } return path.join(relativePathFromDirToDir, fileName); }
function linkFromFileToFile(sourceFile, targetFile) { const relativePathFromDirToDir = path.relative(sourceFile, path.dirname(targetFile)); const fileName = path.basename(targetFile, '.md'); if (fileName === 'README') { return relativePathFromDirToDir; } return path.join(relativePathFromDirToDir, fileName); }
JavaScript
function doOpen() { if (OS_ANDROID) { //Add a title to the tabgroup. We could also add menu items here if // needed var activity = $.getView().activity; var menuItem = null; activity.onCreateOptionsMenu = function(e) { Ti.API.info('IN activity.onCreateOptionsMenu'); Ti.API.info('Active Tab: ' + $.tabGroup.activeTab.title); if ($.tabGroup.activeTab.title === "Settings") { menuItem = e.menu.add({ title : "Logout", showAsAction : Ti.Android.SHOW_AS_ACTION_ALWAYS, }); menuItem.addEventListener("click", function(e) { $.settingsController.handleLogoutMenuClick(); }); } else if ($.tabGroup.activeTab.title === "Feed") { menuItem = e.menu.add({ //itemId : "PHOTO", title : "Take Photo", showAsAction : Ti.Android.SHOW_AS_ACTION_ALWAYS, icon : Ti.Android.R.drawable.ic_menu_camera }); menuItem.addEventListener("click", function(e) { $.feedController.cameraButtonClicked(); }); } }; activity.invalidateOptionsMenu(); // this forces the menu to update when the tab changes $.tabGroup.addEventListener('blur', function(_event) { $.getView().activity.invalidateOptionsMenu(); }); } }
function doOpen() { if (OS_ANDROID) { //Add a title to the tabgroup. We could also add menu items here if // needed var activity = $.getView().activity; var menuItem = null; activity.onCreateOptionsMenu = function(e) { Ti.API.info('IN activity.onCreateOptionsMenu'); Ti.API.info('Active Tab: ' + $.tabGroup.activeTab.title); if ($.tabGroup.activeTab.title === "Settings") { menuItem = e.menu.add({ title : "Logout", showAsAction : Ti.Android.SHOW_AS_ACTION_ALWAYS, }); menuItem.addEventListener("click", function(e) { $.settingsController.handleLogoutMenuClick(); }); } else if ($.tabGroup.activeTab.title === "Feed") { menuItem = e.menu.add({ //itemId : "PHOTO", title : "Take Photo", showAsAction : Ti.Android.SHOW_AS_ACTION_ALWAYS, icon : Ti.Android.R.drawable.ic_menu_camera }); menuItem.addEventListener("click", function(e) { $.feedController.cameraButtonClicked(); }); } }; activity.invalidateOptionsMenu(); // this forces the menu to update when the tab changes $.tabGroup.addEventListener('blur', function(_event) { $.getView().activity.invalidateOptionsMenu(); }); } }
JavaScript
function processACSPhotos(model, method, options) { switch (method) { case "create": // include attributes into the params for ACS Cloud.Photos.create(model.toJSON(), function(e) { if (e.success) { // save the meta data with object model.meta = e.meta; // return the individual photo object found options.success(e.photos[0]); // trigger fetch for UI updates model.trigger("fetch"); } else { Ti.API.error("Photos.create " + e.message); options.error(e.error && e.message || e); } }); break; case "read": model.id && (options.data.photo_id = model.id); var method = model.id ? Cloud.Photos.show : Cloud.Photos.query; method((options.data || {}), function(e) { if (e.success) { model.meta = e.meta; if (e.photos.length === 1) { options.success(e.photos[0]); } else { options.success(e.photos); } model.trigger("fetch"); return; } else { Ti.API.error("Cloud.Photos.query " + e.message); options.error(e.error && e.message || e); } }); break; case "update": case "delete": // Not currently implemented, let the user know alert("Not Implemented Yet"); break; } }
function processACSPhotos(model, method, options) { switch (method) { case "create": // include attributes into the params for ACS Cloud.Photos.create(model.toJSON(), function(e) { if (e.success) { // save the meta data with object model.meta = e.meta; // return the individual photo object found options.success(e.photos[0]); // trigger fetch for UI updates model.trigger("fetch"); } else { Ti.API.error("Photos.create " + e.message); options.error(e.error && e.message || e); } }); break; case "read": model.id && (options.data.photo_id = model.id); var method = model.id ? Cloud.Photos.show : Cloud.Photos.query; method((options.data || {}), function(e) { if (e.success) { model.meta = e.meta; if (e.photos.length === 1) { options.success(e.photos[0]); } else { options.success(e.photos); } model.trigger("fetch"); return; } else { Ti.API.error("Cloud.Photos.query " + e.message); options.error(e.error && e.message || e); } }); break; case "update": case "delete": // Not currently implemented, let the user know alert("Not Implemented Yet"); break; } }
JavaScript
function processImage(_mediaObject, _callback) { geo.getCurrentLocation(function(_coords) { var parameters = { "photo" : _mediaObject, "title" : "Sample Photo " + new Date(), "photo_sizes[preview]" : "200x200#", "photo_sizes[iphone]" : "320x320#", // We need this since we are showing the image immediately "photo_sync_sizes[]" : "preview" }; // if we got a location, then set it if (_coords) { parameters.custom_fields = { coordinates : [_coords.coords.longitude, _coords.coords.latitude], location_string : _coords.title }; } var photo = Alloy.createModel('Photo', parameters); photo.save({}, { success : function(_model, _response) { Ti.API.debug('success: ' + _model.toJSON()); _callback({ model : _model, message : null, success : true }); }, error : function(e) { Ti.API.error('error: ' + e.message); _callback({ model : parameters, message : e.message, success : false }); } }); }); }
function processImage(_mediaObject, _callback) { geo.getCurrentLocation(function(_coords) { var parameters = { "photo" : _mediaObject, "title" : "Sample Photo " + new Date(), "photo_sizes[preview]" : "200x200#", "photo_sizes[iphone]" : "320x320#", // We need this since we are showing the image immediately "photo_sync_sizes[]" : "preview" }; // if we got a location, then set it if (_coords) { parameters.custom_fields = { coordinates : [_coords.coords.longitude, _coords.coords.latitude], location_string : _coords.title }; } var photo = Alloy.createModel('Photo', parameters); photo.save({}, { success : function(_model, _response) { Ti.API.debug('success: ' + _model.toJSON()); _callback({ model : _model, message : null, success : true }); }, error : function(e) { Ti.API.error('error: ' + e.message); _callback({ model : parameters, message : e.message, success : false }); } }); }); }
JavaScript
function showLocalImages() { // create new photo collection $.locationCollection = Alloy.createCollection('photo'); // find all photos within 5 miles of current location geo.getCurrentLocation(function(_coords) { var user = Alloy.Globals.currentUser; $.locationCollection.findPhotosNearMe(user, _coords, 5, { success : function(_collection, _response) { Ti.API.debug('findPhotosNearMe ' + JSON.stringify(_collection)); // add the annotations/map pins to map if (_collection.models.length) { addPhotosToMap(_collection); } else { alert("No Local Images Found"); filterTabbedBarClicked({ index : 0, rowIndex : 0, }); if (OS_ANDROID) { $.filter.setSelectedRow(0, 0, false); } else { $.filter.setIndex(0); } } }, error : function(error) { alert('Error loading Feed ' + error.message); Ti.API.error(JSON.stringify(error)); } }); }); }
function showLocalImages() { // create new photo collection $.locationCollection = Alloy.createCollection('photo'); // find all photos within 5 miles of current location geo.getCurrentLocation(function(_coords) { var user = Alloy.Globals.currentUser; $.locationCollection.findPhotosNearMe(user, _coords, 5, { success : function(_collection, _response) { Ti.API.debug('findPhotosNearMe ' + JSON.stringify(_collection)); // add the annotations/map pins to map if (_collection.models.length) { addPhotosToMap(_collection); } else { alert("No Local Images Found"); filterTabbedBarClicked({ index : 0, rowIndex : 0, }); if (OS_ANDROID) { $.filter.setSelectedRow(0, 0, false); } else { $.filter.setIndex(0); } } }, error : function(error) { alert('Error loading Feed ' + error.message); Ti.API.error(JSON.stringify(error)); } }); }); }
JavaScript
function degreeCentrality(options) { options = defaults$1(options); var cy = this.cy(); var callingEles = this; var _options = options, root = _options.root, weight = _options.weight, directed = _options.directed, alpha = _options.alpha; root = cy.collection(root)[0]; if (!directed) { var connEdges = root.connectedEdges().intersection(callingEles); var k = connEdges.length; var s = 0; // Now, sum edge weights for (var i = 0; i < connEdges.length; i++) { s += weight(connEdges[i]); } return { degree: Math.pow(k, 1 - alpha) * Math.pow(s, alpha) }; } else { var edges = root.connectedEdges(); var incoming = edges.filter(function (edge) { return edge.target().same(root) && callingEles.has(edge); }); var outgoing = edges.filter(function (edge) { return edge.source().same(root) && callingEles.has(edge); }); var k_in = incoming.length; var k_out = outgoing.length; var s_in = 0; var s_out = 0; // Now, sum incoming edge weights for (var _i2 = 0; _i2 < incoming.length; _i2++) { s_in += weight(incoming[_i2]); } // Now, sum outgoing edge weights for (var _i3 = 0; _i3 < outgoing.length; _i3++) { s_out += weight(outgoing[_i3]); } return { indegree: Math.pow(k_in, 1 - alpha) * Math.pow(s_in, alpha), outdegree: Math.pow(k_out, 1 - alpha) * Math.pow(s_out, alpha) }; } } // degreeCentrality
function degreeCentrality(options) { options = defaults$1(options); var cy = this.cy(); var callingEles = this; var _options = options, root = _options.root, weight = _options.weight, directed = _options.directed, alpha = _options.alpha; root = cy.collection(root)[0]; if (!directed) { var connEdges = root.connectedEdges().intersection(callingEles); var k = connEdges.length; var s = 0; // Now, sum edge weights for (var i = 0; i < connEdges.length; i++) { s += weight(connEdges[i]); } return { degree: Math.pow(k, 1 - alpha) * Math.pow(s, alpha) }; } else { var edges = root.connectedEdges(); var incoming = edges.filter(function (edge) { return edge.target().same(root) && callingEles.has(edge); }); var outgoing = edges.filter(function (edge) { return edge.source().same(root) && callingEles.has(edge); }); var k_in = incoming.length; var k_out = outgoing.length; var s_in = 0; var s_out = 0; // Now, sum incoming edge weights for (var _i2 = 0; _i2 < incoming.length; _i2++) { s_in += weight(incoming[_i2]); } // Now, sum outgoing edge weights for (var _i3 = 0; _i3 < outgoing.length; _i3++) { s_out += weight(outgoing[_i3]); } return { indegree: Math.pow(k_in, 1 - alpha) * Math.pow(s_in, alpha), outdegree: Math.pow(k_out, 1 - alpha) * Math.pow(s_out, alpha) }; } } // degreeCentrality
JavaScript
function betweennessCentrality(options) { var _defaults = defaults$3(options), directed = _defaults.directed, weight = _defaults.weight; var weighted = weight != null; var cy = this.cy(); // starting var V = this.nodes(); var A = {}; var _C = {}; var max = 0; var C = { set: function set(key, val) { _C[key] = val; if (val > max) { max = val; } }, get: function get(key) { return _C[key]; } }; // A contains the neighborhoods of every node for (var i = 0; i < V.length; i++) { var v = V[i]; var vid = v.id(); if (directed) { A[vid] = v.outgoers().nodes(); // get outgoers of every node } else { A[vid] = v.openNeighborhood().nodes(); // get neighbors of every node } C.set(vid, 0); } var _loop = function _loop(s) { var sid = V[s].id(); var S = []; // stack var P = {}; var g = {}; var d = {}; var Q = new Heap(function (a, b) { return d[a] - d[b]; }); // queue // init dictionaries for (var _i = 0; _i < V.length; _i++) { var _vid = V[_i].id(); P[_vid] = []; g[_vid] = 0; d[_vid] = Infinity; } g[sid] = 1; // sigma d[sid] = 0; // distance to s Q.push(sid); while (!Q.empty()) { var _v = Q.pop(); S.push(_v); if (weighted) { for (var j = 0; j < A[_v].length; j++) { var w = A[_v][j]; var vEle = cy.getElementById(_v); var edge = void 0; if (vEle.edgesTo(w).length > 0) { edge = vEle.edgesTo(w)[0]; } else { edge = w.edgesTo(vEle)[0]; } var edgeWeight = weight(edge); w = w.id(); if (d[w] > d[_v] + edgeWeight) { d[w] = d[_v] + edgeWeight; if (Q.nodes.indexOf(w) < 0) { //if w is not in Q Q.push(w); } else { // update position if w is in Q Q.updateItem(w); } g[w] = 0; P[w] = []; } if (d[w] == d[_v] + edgeWeight) { g[w] = g[w] + g[_v]; P[w].push(_v); } } } else { for (var _j = 0; _j < A[_v].length; _j++) { var _w = A[_v][_j].id(); if (d[_w] == Infinity) { Q.push(_w); d[_w] = d[_v] + 1; } if (d[_w] == d[_v] + 1) { g[_w] = g[_w] + g[_v]; P[_w].push(_v); } } } } var e = {}; for (var _i2 = 0; _i2 < V.length; _i2++) { e[V[_i2].id()] = 0; } while (S.length > 0) { var _w2 = S.pop(); for (var _j2 = 0; _j2 < P[_w2].length; _j2++) { var _v2 = P[_w2][_j2]; e[_v2] = e[_v2] + g[_v2] / g[_w2] * (1 + e[_w2]); if (_w2 != V[s].id()) { C.set(_w2, C.get(_w2) + e[_w2]); } } } }; for (var s = 0; s < V.length; s++) { _loop(s); } var ret = { betweenness: function betweenness(node) { var id = cy.collection(node).id(); return C.get(id); }, betweennessNormalized: function betweennessNormalized(node) { if (max == 0) { return 0; } var id = cy.collection(node).id(); return C.get(id) / max; } }; // alias ret.betweennessNormalised = ret.betweennessNormalized; return ret; } // betweennessCentrality
function betweennessCentrality(options) { var _defaults = defaults$3(options), directed = _defaults.directed, weight = _defaults.weight; var weighted = weight != null; var cy = this.cy(); // starting var V = this.nodes(); var A = {}; var _C = {}; var max = 0; var C = { set: function set(key, val) { _C[key] = val; if (val > max) { max = val; } }, get: function get(key) { return _C[key]; } }; // A contains the neighborhoods of every node for (var i = 0; i < V.length; i++) { var v = V[i]; var vid = v.id(); if (directed) { A[vid] = v.outgoers().nodes(); // get outgoers of every node } else { A[vid] = v.openNeighborhood().nodes(); // get neighbors of every node } C.set(vid, 0); } var _loop = function _loop(s) { var sid = V[s].id(); var S = []; // stack var P = {}; var g = {}; var d = {}; var Q = new Heap(function (a, b) { return d[a] - d[b]; }); // queue // init dictionaries for (var _i = 0; _i < V.length; _i++) { var _vid = V[_i].id(); P[_vid] = []; g[_vid] = 0; d[_vid] = Infinity; } g[sid] = 1; // sigma d[sid] = 0; // distance to s Q.push(sid); while (!Q.empty()) { var _v = Q.pop(); S.push(_v); if (weighted) { for (var j = 0; j < A[_v].length; j++) { var w = A[_v][j]; var vEle = cy.getElementById(_v); var edge = void 0; if (vEle.edgesTo(w).length > 0) { edge = vEle.edgesTo(w)[0]; } else { edge = w.edgesTo(vEle)[0]; } var edgeWeight = weight(edge); w = w.id(); if (d[w] > d[_v] + edgeWeight) { d[w] = d[_v] + edgeWeight; if (Q.nodes.indexOf(w) < 0) { //if w is not in Q Q.push(w); } else { // update position if w is in Q Q.updateItem(w); } g[w] = 0; P[w] = []; } if (d[w] == d[_v] + edgeWeight) { g[w] = g[w] + g[_v]; P[w].push(_v); } } } else { for (var _j = 0; _j < A[_v].length; _j++) { var _w = A[_v][_j].id(); if (d[_w] == Infinity) { Q.push(_w); d[_w] = d[_v] + 1; } if (d[_w] == d[_v] + 1) { g[_w] = g[_w] + g[_v]; P[_w].push(_v); } } } } var e = {}; for (var _i2 = 0; _i2 < V.length; _i2++) { e[V[_i2].id()] = 0; } while (S.length > 0) { var _w2 = S.pop(); for (var _j2 = 0; _j2 < P[_w2].length; _j2++) { var _v2 = P[_w2][_j2]; e[_v2] = e[_v2] + g[_v2] / g[_w2] * (1 + e[_w2]); if (_w2 != V[s].id()) { C.set(_w2, C.get(_w2) + e[_w2]); } } } }; for (var s = 0; s < V.length; s++) { _loop(s); } var ret = { betweenness: function betweenness(node) { var id = cy.collection(node).id(); return C.get(id); }, betweennessNormalized: function betweennessNormalized(node) { if (max == 0) { return 0; } var id = cy.collection(node).id(); return C.get(id) / max; } }; // alias ret.betweennessNormalised = ret.betweennessNormalized; return ret; } // betweennessCentrality
JavaScript
function renderedPosition(dim, val) { var ele = this[0]; var cy = this.cy(); var zoom = cy.zoom(); var pan = cy.pan(); var rpos = plainObject(dim) ? dim : undefined; var setting = rpos !== undefined || val !== undefined && string(dim); if (ele && ele.isNode()) { // must have an element and must be a node to return position if (setting) { for (var i = 0; i < this.length; i++) { var _ele = this[i]; if (val !== undefined) { // set one dimension _ele.position(dim, (val - pan[dim]) / zoom); } else if (rpos !== undefined) { // set whole position _ele.position(renderedToModelPosition(rpos, zoom, pan)); } } } else { // getting var pos = ele.position(); rpos = modelToRenderedPosition(pos, zoom, pan); if (dim === undefined) { // then return the whole rendered position return rpos; } else { // then return the specified dimension return rpos[dim]; } } } else if (!setting) { return undefined; // for empty collection case } return this; // chaining }
function renderedPosition(dim, val) { var ele = this[0]; var cy = this.cy(); var zoom = cy.zoom(); var pan = cy.pan(); var rpos = plainObject(dim) ? dim : undefined; var setting = rpos !== undefined || val !== undefined && string(dim); if (ele && ele.isNode()) { // must have an element and must be a node to return position if (setting) { for (var i = 0; i < this.length; i++) { var _ele = this[i]; if (val !== undefined) { // set one dimension _ele.position(dim, (val - pan[dim]) / zoom); } else if (rpos !== undefined) { // set whole position _ele.position(renderedToModelPosition(rpos, zoom, pan)); } } } else { // getting var pos = ele.position(); rpos = modelToRenderedPosition(pos, zoom, pan); if (dim === undefined) { // then return the whole rendered position return rpos; } else { // then return the specified dimension return rpos[dim]; } } } else if (!setting) { return undefined; // for empty collection case } return this; // chaining }
JavaScript
function relativePosition(dim, val) { var ele = this[0]; var cy = this.cy(); var ppos = plainObject(dim) ? dim : undefined; var setting = ppos !== undefined || val !== undefined && string(dim); var hasCompoundNodes = cy.hasCompoundNodes(); if (ele && ele.isNode()) { // must have an element and must be a node to return position if (setting) { for (var i = 0; i < this.length; i++) { var _ele2 = this[i]; var parent = hasCompoundNodes ? _ele2.parent() : null; var hasParent = parent && parent.length > 0; var relativeToParent = hasParent; if (hasParent) { parent = parent[0]; } var origin = relativeToParent ? parent.position() : { x: 0, y: 0 }; if (val !== undefined) { // set one dimension _ele2.position(dim, val + origin[dim]); } else if (ppos !== undefined) { // set whole position _ele2.position({ x: ppos.x + origin.x, y: ppos.y + origin.y }); } } } else { // getting var pos = ele.position(); var _parent = hasCompoundNodes ? ele.parent() : null; var _hasParent = _parent && _parent.length > 0; var _relativeToParent = _hasParent; if (_hasParent) { _parent = _parent[0]; } var _origin = _relativeToParent ? _parent.position() : { x: 0, y: 0 }; ppos = { x: pos.x - _origin.x, y: pos.y - _origin.y }; if (dim === undefined) { // then return the whole rendered position return ppos; } else { // then return the specified dimension return ppos[dim]; } } } else if (!setting) { return undefined; // for empty collection case } return this; // chaining }
function relativePosition(dim, val) { var ele = this[0]; var cy = this.cy(); var ppos = plainObject(dim) ? dim : undefined; var setting = ppos !== undefined || val !== undefined && string(dim); var hasCompoundNodes = cy.hasCompoundNodes(); if (ele && ele.isNode()) { // must have an element and must be a node to return position if (setting) { for (var i = 0; i < this.length; i++) { var _ele2 = this[i]; var parent = hasCompoundNodes ? _ele2.parent() : null; var hasParent = parent && parent.length > 0; var relativeToParent = hasParent; if (hasParent) { parent = parent[0]; } var origin = relativeToParent ? parent.position() : { x: 0, y: 0 }; if (val !== undefined) { // set one dimension _ele2.position(dim, val + origin[dim]); } else if (ppos !== undefined) { // set whole position _ele2.position({ x: ppos.x + origin.x, y: ppos.y + origin.y }); } } } else { // getting var pos = ele.position(); var _parent = hasCompoundNodes ? ele.parent() : null; var _hasParent = _parent && _parent.length > 0; var _relativeToParent = _hasParent; if (_hasParent) { _parent = _parent[0]; } var _origin = _relativeToParent ? _parent.position() : { x: 0, y: 0 }; ppos = { x: pos.x - _origin.x, y: pos.y - _origin.y }; if (dim === undefined) { // then return the whole rendered position return ppos; } else { // then return the specified dimension return ppos[dim]; } } } else if (!setting) { return undefined; // for empty collection case } return this; // chaining }
JavaScript
function byGroup() { var nodes = this.spawn(); var edges = this.spawn(); for (var i = 0; i < this.length; i++) { var ele = this[i]; if (ele.isNode()) { nodes.merge(ele); } else { edges.merge(ele); } } return { nodes: nodes, edges: edges }; }
function byGroup() { var nodes = this.spawn(); var edges = this.spawn(); for (var i = 0; i < this.length; i++) { var ele = this[i]; if (ele.isNode()) { nodes.merge(ele); } else { edges.merge(ele); } } return { nodes: nodes, edges: edges }; }
JavaScript
function merge(toAdd) { var _p = this._private; var cy = _p.cy; if (!toAdd) { return this; } if (toAdd && string(toAdd)) { var selector = toAdd; toAdd = cy.mutableElements().filter(selector); } var map = _p.map; for (var i = 0; i < toAdd.length; i++) { var toAddEle = toAdd[i]; var id = toAddEle._private.data.id; var add = !map.has(id); if (add) { var index = this.length++; this[index] = toAddEle; map.set(id, { ele: toAddEle, index: index }); } else { // replace var _index = map.get(id).index; this[_index] = toAddEle; map.set(id, { ele: toAddEle, index: _index }); } } return this; // chaining }
function merge(toAdd) { var _p = this._private; var cy = _p.cy; if (!toAdd) { return this; } if (toAdd && string(toAdd)) { var selector = toAdd; toAdd = cy.mutableElements().filter(selector); } var map = _p.map; for (var i = 0; i < toAdd.length; i++) { var toAddEle = toAdd[i]; var id = toAddEle._private.data.id; var add = !map.has(id); if (add) { var index = this.length++; this[index] = toAddEle; map.set(id, { ele: toAddEle, index: index }); } else { // replace var _index = map.get(id).index; this[_index] = toAddEle; map.set(id, { ele: toAddEle, index: _index }); } } return this; // chaining }
JavaScript
function unmergeOne(ele) { ele = ele[0]; var _p = this._private; var id = ele._private.data.id; var map = _p.map; var entry = map.get(id); if (!entry) { return this; // no need to remove } var i = entry.index; this.unmergeAt(i); return this; }
function unmergeOne(ele) { ele = ele[0]; var _p = this._private; var id = ele._private.data.id; var map = _p.map; var entry = map.get(id); if (!entry) { return this; // no need to remove } var i = entry.index; this.unmergeAt(i); return this; }
JavaScript
function unmerge(toRemove) { var cy = this._private.cy; if (!toRemove) { return this; } if (toRemove && string(toRemove)) { var selector = toRemove; toRemove = cy.mutableElements().filter(selector); } for (var i = 0; i < toRemove.length; i++) { this.unmergeOne(toRemove[i]); } return this; // chaining }
function unmerge(toRemove) { var cy = this._private.cy; if (!toRemove) { return this; } if (toRemove && string(toRemove)) { var selector = toRemove; toRemove = cy.mutableElements().filter(selector); } for (var i = 0; i < toRemove.length; i++) { this.unmergeOne(toRemove[i]); } return this; // chaining }
JavaScript
function layoutDimensions(options) { options = getLayoutDimensionOptions(options); if (options.nodeDimensionsIncludeLabels) { var bbDim = this.boundingBox(); return { w: bbDim.w, h: bbDim.h }; } else { return { w: this.outerWidth(), h: this.outerHeight() }; } }
function layoutDimensions(options) { options = getLayoutDimensionOptions(options); if (options.nodeDimensionsIncludeLabels) { var bbDim = this.boundingBox(); return { w: bbDim.w, h: bbDim.h }; } else { return { w: this.outerWidth(), h: this.outerHeight() }; } }
JavaScript
function layoutPositions(layout, options, fn) { var nodes = this.nodes(); var cy = this.cy(); var layoutEles = options.eles; // nodes & edges var getMemoizeKey = function getMemoizeKey(node) { return node.id(); }; var fnMem = memoize(fn, getMemoizeKey); // memoized version of position function layout.emit({ type: 'layoutstart', layout: layout }); layout.animations = []; var calculateSpacing = function calculateSpacing(spacing, nodesBb, pos) { var center = { x: nodesBb.x1 + nodesBb.w / 2, y: nodesBb.y1 + nodesBb.h / 2 }; var spacingVector = { // scale from center of bounding box (not necessarily 0,0) x: (pos.x - center.x) * spacing, y: (pos.y - center.y) * spacing }; return { x: center.x + spacingVector.x, y: center.y + spacingVector.y }; }; var useSpacingFactor = options.spacingFactor && options.spacingFactor !== 1; var spacingBb = function spacingBb() { if (!useSpacingFactor) { return null; } var bb = makeBoundingBox(); for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; var pos = fnMem(node, i); expandBoundingBoxByPoint(bb, pos.x, pos.y); } return bb; }; var bb = spacingBb(); var getFinalPos = memoize(function (node, i) { var newPos = fnMem(node, i); if (useSpacingFactor) { var spacing = Math.abs(options.spacingFactor); newPos = calculateSpacing(spacing, bb, newPos); } if (options.transform != null) { newPos = options.transform(node, newPos); } return newPos; }, getMemoizeKey); if (options.animate) { for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; var newPos = getFinalPos(node, i); var animateNode = options.animateFilter == null || options.animateFilter(node, i); if (animateNode) { var ani = node.animation({ position: newPos, duration: options.animationDuration, easing: options.animationEasing }); layout.animations.push(ani); } else { node.position(newPos); } } if (options.fit) { var fitAni = cy.animation({ fit: { boundingBox: layoutEles.boundingBoxAt(getFinalPos), padding: options.padding }, duration: options.animationDuration, easing: options.animationEasing }); layout.animations.push(fitAni); } else if (options.zoom !== undefined && options.pan !== undefined) { var zoomPanAni = cy.animation({ zoom: options.zoom, pan: options.pan, duration: options.animationDuration, easing: options.animationEasing }); layout.animations.push(zoomPanAni); } layout.animations.forEach(function (ani) { return ani.play(); }); layout.one('layoutready', options.ready); layout.emit({ type: 'layoutready', layout: layout }); Promise$1.all(layout.animations.map(function (ani) { return ani.promise(); })).then(function () { layout.one('layoutstop', options.stop); layout.emit({ type: 'layoutstop', layout: layout }); }); } else { nodes.positions(getFinalPos); if (options.fit) { cy.fit(options.eles, options.padding); } if (options.zoom != null) { cy.zoom(options.zoom); } if (options.pan) { cy.pan(options.pan); } layout.one('layoutready', options.ready); layout.emit({ type: 'layoutready', layout: layout }); layout.one('layoutstop', options.stop); layout.emit({ type: 'layoutstop', layout: layout }); } return this; // chaining }
function layoutPositions(layout, options, fn) { var nodes = this.nodes(); var cy = this.cy(); var layoutEles = options.eles; // nodes & edges var getMemoizeKey = function getMemoizeKey(node) { return node.id(); }; var fnMem = memoize(fn, getMemoizeKey); // memoized version of position function layout.emit({ type: 'layoutstart', layout: layout }); layout.animations = []; var calculateSpacing = function calculateSpacing(spacing, nodesBb, pos) { var center = { x: nodesBb.x1 + nodesBb.w / 2, y: nodesBb.y1 + nodesBb.h / 2 }; var spacingVector = { // scale from center of bounding box (not necessarily 0,0) x: (pos.x - center.x) * spacing, y: (pos.y - center.y) * spacing }; return { x: center.x + spacingVector.x, y: center.y + spacingVector.y }; }; var useSpacingFactor = options.spacingFactor && options.spacingFactor !== 1; var spacingBb = function spacingBb() { if (!useSpacingFactor) { return null; } var bb = makeBoundingBox(); for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; var pos = fnMem(node, i); expandBoundingBoxByPoint(bb, pos.x, pos.y); } return bb; }; var bb = spacingBb(); var getFinalPos = memoize(function (node, i) { var newPos = fnMem(node, i); if (useSpacingFactor) { var spacing = Math.abs(options.spacingFactor); newPos = calculateSpacing(spacing, bb, newPos); } if (options.transform != null) { newPos = options.transform(node, newPos); } return newPos; }, getMemoizeKey); if (options.animate) { for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; var newPos = getFinalPos(node, i); var animateNode = options.animateFilter == null || options.animateFilter(node, i); if (animateNode) { var ani = node.animation({ position: newPos, duration: options.animationDuration, easing: options.animationEasing }); layout.animations.push(ani); } else { node.position(newPos); } } if (options.fit) { var fitAni = cy.animation({ fit: { boundingBox: layoutEles.boundingBoxAt(getFinalPos), padding: options.padding }, duration: options.animationDuration, easing: options.animationEasing }); layout.animations.push(fitAni); } else if (options.zoom !== undefined && options.pan !== undefined) { var zoomPanAni = cy.animation({ zoom: options.zoom, pan: options.pan, duration: options.animationDuration, easing: options.animationEasing }); layout.animations.push(zoomPanAni); } layout.animations.forEach(function (ani) { return ani.play(); }); layout.one('layoutready', options.ready); layout.emit({ type: 'layoutready', layout: layout }); Promise$1.all(layout.animations.map(function (ani) { return ani.promise(); })).then(function () { layout.one('layoutstop', options.stop); layout.emit({ type: 'layoutstop', layout: layout }); }); } else { nodes.positions(getFinalPos); if (options.fit) { cy.fit(options.eles, options.padding); } if (options.zoom != null) { cy.zoom(options.zoom); } if (options.pan) { cy.pan(options.pan); } layout.one('layoutready', options.ready); layout.emit({ type: 'layoutready', layout: layout }); layout.one('layoutstop', options.stop); layout.emit({ type: 'layoutstop', layout: layout }); } return this; // chaining }
JavaScript
function updateStyle(notifyRenderer) { var cy = this._private.cy; if (!cy.styleEnabled()) { return this; } if (cy.batching()) { var bEles = cy._private.batchStyleEles; bEles.merge(this); return this; // chaining and exit early when batching } var hasCompounds = cy.hasCompoundNodes(); var style = cy.style(); var updatedEles = this; notifyRenderer = notifyRenderer || notifyRenderer === undefined ? true : false; if (hasCompounds) { // then add everything up and down for compound selector checks updatedEles = this.spawnSelf().merge(this.descendants()).merge(this.parents()); } var changedEles = style.apply(updatedEles); if (notifyRenderer) { changedEles.emitAndNotify('style'); // let renderer know we changed style } else { changedEles.emit('style'); // just fire the event } return this; // chaining }
function updateStyle(notifyRenderer) { var cy = this._private.cy; if (!cy.styleEnabled()) { return this; } if (cy.batching()) { var bEles = cy._private.batchStyleEles; bEles.merge(this); return this; // chaining and exit early when batching } var hasCompounds = cy.hasCompoundNodes(); var style = cy.style(); var updatedEles = this; notifyRenderer = notifyRenderer || notifyRenderer === undefined ? true : false; if (hasCompounds) { // then add everything up and down for compound selector checks updatedEles = this.spawnSelf().merge(this.descendants()).merge(this.parents()); } var changedEles = style.apply(updatedEles); if (notifyRenderer) { changedEles.emitAndNotify('style'); // let renderer know we changed style } else { changedEles.emit('style'); // just fire the event } return this; // chaining }
JavaScript
function parsedStyle(property) { var includeNonDefault = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var ele = this[0]; var cy = ele.cy(); if (!cy.styleEnabled()) { return; } if (ele) { var overriddenStyle = ele._private.style[property]; if (overriddenStyle != null) { return overriddenStyle; } else if (includeNonDefault) { return cy.style().getDefaultProperty(property); } else { return null; } } }
function parsedStyle(property) { var includeNonDefault = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var ele = this[0]; var cy = ele.cy(); if (!cy.styleEnabled()) { return; } if (ele) { var overriddenStyle = ele._private.style[property]; if (overriddenStyle != null) { return overriddenStyle; } else if (includeNonDefault) { return cy.style().getDefaultProperty(property); } else { return null; } } }
JavaScript
function renderedStyle(property) { var cy = this.cy(); if (!cy.styleEnabled()) { return this; } var ele = this[0]; if (ele) { return cy.style().getRenderedStyle(ele, property); } }
function renderedStyle(property) { var cy = this.cy(); if (!cy.styleEnabled()) { return this; } var ele = this[0]; if (ele) { return cy.style().getRenderedStyle(ele, property); } }
JavaScript
function style(name, value) { var cy = this.cy(); if (!cy.styleEnabled()) { return this; } var updateTransitions = false; var style = cy.style(); if (plainObject(name)) { // then extend the bypass var props = name; style.applyBypass(this, props, updateTransitions); this.emitAndNotify('style'); // let the renderer know we've updated style } else if (string(name)) { if (value === undefined) { // then get the property from the style var ele = this[0]; if (ele) { return style.getStylePropertyValue(ele, name); } else { // empty collection => can't get any value return; } } else { // then set the bypass with the property value style.applyBypass(this, name, value, updateTransitions); this.emitAndNotify('style'); // let the renderer know we've updated style } } else if (name === undefined) { var _ele = this[0]; if (_ele) { return style.getRawStyle(_ele); } else { // empty collection => can't get any value return; } } return this; // chaining }
function style(name, value) { var cy = this.cy(); if (!cy.styleEnabled()) { return this; } var updateTransitions = false; var style = cy.style(); if (plainObject(name)) { // then extend the bypass var props = name; style.applyBypass(this, props, updateTransitions); this.emitAndNotify('style'); // let the renderer know we've updated style } else if (string(name)) { if (value === undefined) { // then get the property from the style var ele = this[0]; if (ele) { return style.getStylePropertyValue(ele, name); } else { // empty collection => can't get any value return; } } else { // then set the bypass with the property value style.applyBypass(this, name, value, updateTransitions); this.emitAndNotify('style'); // let the renderer know we've updated style } } else if (name === undefined) { var _ele = this[0]; if (_ele) { return style.getRawStyle(_ele); } else { // empty collection => can't get any value return; } } return this; // chaining }