language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function findTdAtColIdx($tr, colIdx) {
var colspan,
res = null,
idx = 0;
$tr.children().each(function() {
if (idx >= colIdx) {
res = $(this);
return false;
}
colspan = $(this).prop("colspan");
idx += colspan ? colspan : 1;
});
return res;
} | function findTdAtColIdx($tr, colIdx) {
var colspan,
res = null,
idx = 0;
$tr.children().each(function() {
if (idx >= colIdx) {
res = $(this);
return false;
}
colspan = $(this).prop("colspan");
idx += colspan ? colspan : 1;
});
return res;
} |
JavaScript | function findNeighbourTd($target, keyCode) {
var $tr,
colIdx,
$td = $target.closest("td"),
$tdNext = null;
switch (keyCode) {
case KC.LEFT:
$tdNext = $td.prev();
break;
case KC.RIGHT:
$tdNext = $td.next();
break;
case KC.UP:
case KC.DOWN:
$tr = $td.parent();
colIdx = getColIdx($tr, $td);
while (true) {
$tr = keyCode === KC.UP ? $tr.prev() : $tr.next();
if (!$tr.length) {
break;
}
// Skip hidden rows
if ($tr.is(":hidden")) {
continue;
}
// Find adjacent cell in the same column
$tdNext = findTdAtColIdx($tr, colIdx);
// Skip cells that don't conatain a focusable element
if ($tdNext && $tdNext.find(":input,a").length) {
break;
}
}
break;
}
return $tdNext;
} | function findNeighbourTd($target, keyCode) {
var $tr,
colIdx,
$td = $target.closest("td"),
$tdNext = null;
switch (keyCode) {
case KC.LEFT:
$tdNext = $td.prev();
break;
case KC.RIGHT:
$tdNext = $td.next();
break;
case KC.UP:
case KC.DOWN:
$tr = $td.parent();
colIdx = getColIdx($tr, $td);
while (true) {
$tr = keyCode === KC.UP ? $tr.prev() : $tr.next();
if (!$tr.length) {
break;
}
// Skip hidden rows
if ($tr.is(":hidden")) {
continue;
}
// Find adjacent cell in the same column
$tdNext = findTdAtColIdx($tr, colIdx);
// Skip cells that don't conatain a focusable element
if ($tdNext && $tdNext.find(":input,a").length) {
break;
}
}
break;
}
return $tdNext;
} |
JavaScript | function findNeighbourTd(tree, $target, keyCode) {
var nextNode,
node,
navMap = { "ctrl+home": "first", "ctrl+end": "last" },
$td = $target.closest("td"),
$tr = $td.parent(),
treeOpts = tree.options,
colIdx = getColIdx($tr, $td),
$tdNext = null;
keyCode = navMap[keyCode] || keyCode;
switch (keyCode) {
case "left":
$tdNext = treeOpts.rtl ? $td.next() : $td.prev();
break;
case "right":
$tdNext = treeOpts.rtl ? $td.prev() : $td.next();
break;
case "up":
case "down":
case "ctrl+home":
case "ctrl+end":
node = $tr[0].ftnode;
nextNode = tree.findRelatedNode(node, keyCode);
if (nextNode) {
nextNode.makeVisible();
nextNode.setActive();
$tdNext = findTdAtColIdx($(nextNode.tr), colIdx);
}
break;
case "home":
$tdNext = treeOpts.rtl
? $tr.children("td").last()
: $tr.children("td").first();
break;
case "end":
$tdNext = treeOpts.rtl
? $tr.children("td").first()
: $tr.children("td").last();
break;
}
return $tdNext && $tdNext.length ? $tdNext : null;
} | function findNeighbourTd(tree, $target, keyCode) {
var nextNode,
node,
navMap = { "ctrl+home": "first", "ctrl+end": "last" },
$td = $target.closest("td"),
$tr = $td.parent(),
treeOpts = tree.options,
colIdx = getColIdx($tr, $td),
$tdNext = null;
keyCode = navMap[keyCode] || keyCode;
switch (keyCode) {
case "left":
$tdNext = treeOpts.rtl ? $td.next() : $td.prev();
break;
case "right":
$tdNext = treeOpts.rtl ? $td.prev() : $td.next();
break;
case "up":
case "down":
case "ctrl+home":
case "ctrl+end":
node = $tr[0].ftnode;
nextNode = tree.findRelatedNode(node, keyCode);
if (nextNode) {
nextNode.makeVisible();
nextNode.setActive();
$tdNext = findTdAtColIdx($(nextNode.tr), colIdx);
}
break;
case "home":
$tdNext = treeOpts.rtl
? $tr.children("td").last()
: $tr.children("td").first();
break;
case "end":
$tdNext = treeOpts.rtl
? $tr.children("td").first()
: $tr.children("td").last();
break;
}
return $tdNext && $tdNext.length ? $tdNext : null;
} |
JavaScript | function _removeArrayMember(arr, elem) {
// TODO: use Array.indexOf for IE >= 9
var i;
for (i = arr.length - 1; i >= 0; i--) {
if (arr[i] === elem) {
arr.splice(i, 1);
return true;
}
}
return false;
} | function _removeArrayMember(arr, elem) {
// TODO: use Array.indexOf for IE >= 9
var i;
for (i = arr.length - 1; i >= 0; i--) {
if (arr[i] === elem) {
arr.splice(i, 1);
return true;
}
}
return false;
} |
JavaScript | function calcUniqueKey(node) {
var key,
h1,
path = $.map(node.getParentList(false, true), function(e) {
return e.refKey || e.key;
});
path = path.join("/");
// 32-bit has a high probability of collisions, so we pump up to 64-bit
// https://security.stackexchange.com/q/209882/207588
h1 = hashMurmur3(path, true);
key = "id_" + h1 + hashMurmur3(h1 + path, true);
return key;
} | function calcUniqueKey(node) {
var key,
h1,
path = $.map(node.getParentList(false, true), function(e) {
return e.refKey || e.key;
});
path = path.join("/");
// 32-bit has a high probability of collisions, so we pump up to 64-bit
// https://security.stackexchange.com/q/209882/207588
h1 = hashMurmur3(path, true);
key = "id_" + h1 + hashMurmur3(h1 + path, true);
return key;
} |
JavaScript | function isVersionAtLeast(dottedVersion, major, minor, patch) {
var i,
v,
t,
verParts = $.map($.trim(dottedVersion).split("."), function(e) {
return parseInt(e, 10);
}),
testParts = $.map(
Array.prototype.slice.call(arguments, 1),
function(e) {
return parseInt(e, 10);
}
);
for (i = 0; i < testParts.length; i++) {
v = verParts[i] || 0;
t = testParts[i] || 0;
if (v !== t) {
return v > t;
}
}
return true;
} | function isVersionAtLeast(dottedVersion, major, minor, patch) {
var i,
v,
t,
verParts = $.map($.trim(dottedVersion).split("."), function(e) {
return parseInt(e, 10);
}),
testParts = $.map(
Array.prototype.slice.call(arguments, 1),
function(e) {
return parseInt(e, 10);
}
);
for (i = 0; i < testParts.length; i++) {
v = verParts[i] || 0;
t = testParts[i] || 0;
if (v !== t) {
return v > t;
}
}
return true;
} |
JavaScript | function _subclassObject(tree, base, extension, extName) {
// $.ui.fancytree.debug("_subclassObject", tree, base, extension, extName);
for (var attrName in extension) {
if (typeof extension[attrName] === "function") {
if (typeof tree[attrName] === "function") {
// override existing method
tree[attrName] = _makeVirtualFunction(
attrName,
tree,
base,
extension,
extName
);
} else if (attrName.charAt(0) === "_") {
// Create private methods in tree.ext.EXTENSION namespace
tree.ext[extName][attrName] = _makeVirtualFunction(
attrName,
tree,
base,
extension,
extName
);
} else {
$.error(
"Could not override tree." +
attrName +
". Use prefix '_' to create tree." +
extName +
"._" +
attrName
);
}
} else {
// Create member variables in tree.ext.EXTENSION namespace
if (attrName !== "options") {
tree.ext[extName][attrName] = extension[attrName];
}
}
}
} | function _subclassObject(tree, base, extension, extName) {
// $.ui.fancytree.debug("_subclassObject", tree, base, extension, extName);
for (var attrName in extension) {
if (typeof extension[attrName] === "function") {
if (typeof tree[attrName] === "function") {
// override existing method
tree[attrName] = _makeVirtualFunction(
attrName,
tree,
base,
extension,
extName
);
} else if (attrName.charAt(0) === "_") {
// Create private methods in tree.ext.EXTENSION namespace
tree.ext[extName][attrName] = _makeVirtualFunction(
attrName,
tree,
base,
extension,
extName
);
} else {
$.error(
"Could not override tree." +
attrName +
". Use prefix '_' to create tree." +
extName +
"._" +
attrName
);
}
} else {
// Create member variables in tree.ext.EXTENSION namespace
if (attrName !== "options") {
tree.ext[extName][attrName] = extension[attrName];
}
}
}
} |
JavaScript | function FancytreeNode(parent, obj) {
var i, l, name, cl;
this.parent = parent;
this.tree = parent.tree;
this.ul = null;
this.li = null; // <li id='key' ftnode=this> tag
this.statusNodeType = null; // if this is a temp. node to display the status of its parent
this._isLoading = false; // if this node itself is loading
this._error = null; // {message: '...'} if a load error occurred
this.data = {};
// TODO: merge this code with node.toDict()
// copy attributes from obj object
for (i = 0, l = NODE_ATTRS.length; i < l; i++) {
name = NODE_ATTRS[i];
this[name] = obj[name];
}
// unselectableIgnore and unselectableStatus imply unselectable
if (
this.unselectableIgnore != null ||
this.unselectableStatus != null
) {
this.unselectable = true;
}
if (obj.hideCheckbox) {
$.error(
"'hideCheckbox' node option was removed in v2.23.0: use 'checkbox: false'"
);
}
// node.data += obj.data
if (obj.data) {
$.extend(this.data, obj.data);
}
// Copy all other attributes to this.data.NAME
for (name in obj) {
if (
!NODE_ATTR_MAP[name] &&
(this.tree.options.copyFunctionsToData ||
!$.isFunction(obj[name])) &&
!NONE_NODE_DATA_MAP[name]
) {
// node.data.NAME = obj.NAME
this.data[name] = obj[name];
}
}
// Fix missing key
if (this.key == null) {
// test for null OR undefined
if (this.tree.options.defaultKey) {
this.key = "" + this.tree.options.defaultKey(this);
_assert(this.key, "defaultKey() must return a unique key");
} else {
this.key = "_" + FT._nextNodeKey++;
}
} else {
this.key = "" + this.key; // Convert to string (#217)
}
// Fix tree.activeNode
// TODO: not elegant: we use obj.active as marker to set tree.activeNode
// when loading from a dictionary.
if (obj.active) {
_assert(
this.tree.activeNode === null,
"only one active node allowed"
);
this.tree.activeNode = this;
}
if (obj.selected) {
// #186
this.tree.lastSelectedNode = this;
}
// TODO: handle obj.focus = true
// Create child nodes
cl = obj.children;
if (cl) {
if (cl.length) {
this._setChildren(cl);
} else {
// if an empty array was passed for a lazy node, keep it, in order to mark it 'loaded'
this.children = this.lazy ? [] : null;
}
} else {
this.children = null;
}
// Add to key/ref map (except for root node)
// if( parent ) {
this.tree._callHook("treeRegisterNode", this.tree, true, this);
// }
} | function FancytreeNode(parent, obj) {
var i, l, name, cl;
this.parent = parent;
this.tree = parent.tree;
this.ul = null;
this.li = null; // <li id='key' ftnode=this> tag
this.statusNodeType = null; // if this is a temp. node to display the status of its parent
this._isLoading = false; // if this node itself is loading
this._error = null; // {message: '...'} if a load error occurred
this.data = {};
// TODO: merge this code with node.toDict()
// copy attributes from obj object
for (i = 0, l = NODE_ATTRS.length; i < l; i++) {
name = NODE_ATTRS[i];
this[name] = obj[name];
}
// unselectableIgnore and unselectableStatus imply unselectable
if (
this.unselectableIgnore != null ||
this.unselectableStatus != null
) {
this.unselectable = true;
}
if (obj.hideCheckbox) {
$.error(
"'hideCheckbox' node option was removed in v2.23.0: use 'checkbox: false'"
);
}
// node.data += obj.data
if (obj.data) {
$.extend(this.data, obj.data);
}
// Copy all other attributes to this.data.NAME
for (name in obj) {
if (
!NODE_ATTR_MAP[name] &&
(this.tree.options.copyFunctionsToData ||
!$.isFunction(obj[name])) &&
!NONE_NODE_DATA_MAP[name]
) {
// node.data.NAME = obj.NAME
this.data[name] = obj[name];
}
}
// Fix missing key
if (this.key == null) {
// test for null OR undefined
if (this.tree.options.defaultKey) {
this.key = "" + this.tree.options.defaultKey(this);
_assert(this.key, "defaultKey() must return a unique key");
} else {
this.key = "_" + FT._nextNodeKey++;
}
} else {
this.key = "" + this.key; // Convert to string (#217)
}
// Fix tree.activeNode
// TODO: not elegant: we use obj.active as marker to set tree.activeNode
// when loading from a dictionary.
if (obj.active) {
_assert(
this.tree.activeNode === null,
"only one active node allowed"
);
this.tree.activeNode = this;
}
if (obj.selected) {
// #186
this.tree.lastSelectedNode = this;
}
// TODO: handle obj.focus = true
// Create child nodes
cl = obj.children;
if (cl) {
if (cl.length) {
this._setChildren(cl);
} else {
// if an empty array was passed for a lazy node, keep it, in order to mark it 'loaded'
this.children = this.lazy ? [] : null;
}
} else {
this.children = null;
}
// Add to key/ref map (except for root node)
// if( parent ) {
this.tree._callHook("treeRegisterNode", this.tree, true, this);
// }
} |
JavaScript | function _walk(node) {
var i,
l,
child,
s,
state,
allSelected,
someSelected,
unselIgnore,
unselState,
children = node.children;
if (children && children.length) {
// check all children recursively
allSelected = true;
someSelected = false;
for (i = 0, l = children.length; i < l; i++) {
child = children[i];
// the selection state of a node is not relevant; we need the end-nodes
s = _walk(child);
// if( !child.unselectableIgnore ) {
unselIgnore = FT.evalOption(
"unselectableIgnore",
child,
child,
opts,
false
);
if (!unselIgnore) {
if (s !== false) {
someSelected = true;
}
if (s !== true) {
allSelected = false;
}
}
}
// eslint-disable-next-line no-nested-ternary
state = allSelected
? true
: someSelected
? undefined
: false;
} else {
// This is an end-node: simply report the status
unselState = FT.evalOption(
"unselectableStatus",
node,
node,
opts,
undefined
);
state = unselState == null ? !!node.selected : !!unselState;
}
// #939: Keep a `partsel` flag that was explicitly set on a lazy node
if (
node.partsel &&
!node.selected &&
node.lazy &&
node.children == null
) {
state = undefined;
}
node._changeSelectStatusAttrs(state);
return state;
} | function _walk(node) {
var i,
l,
child,
s,
state,
allSelected,
someSelected,
unselIgnore,
unselState,
children = node.children;
if (children && children.length) {
// check all children recursively
allSelected = true;
someSelected = false;
for (i = 0, l = children.length; i < l; i++) {
child = children[i];
// the selection state of a node is not relevant; we need the end-nodes
s = _walk(child);
// if( !child.unselectableIgnore ) {
unselIgnore = FT.evalOption(
"unselectableIgnore",
child,
child,
opts,
false
);
if (!unselIgnore) {
if (s !== false) {
someSelected = true;
}
if (s !== true) {
allSelected = false;
}
}
}
// eslint-disable-next-line no-nested-ternary
state = allSelected
? true
: someSelected
? undefined
: false;
} else {
// This is an end-node: simply report the status
unselState = FT.evalOption(
"unselectableStatus",
node,
node,
opts,
undefined
);
state = unselState == null ? !!node.selected : !!unselState;
}
// #939: Keep a `partsel` flag that was explicitly set on a lazy node
if (
node.partsel &&
!node.selected &&
node.lazy &&
node.children == null
) {
state = undefined;
}
node._changeSelectStatusAttrs(state);
return state;
} |
JavaScript | function __lazyload(dfd, parent, pathSegList) {
// console.log("__lazyload", parent, "pathSegList=", pathSegList);
opts.callback(self, parent, "loading");
parent
.load()
.done(function() {
self._loadKeyPathImpl
.call(self, dfd, opts, parent, pathSegList)
.always(_makeResolveFunc(dfd, self));
})
.fail(function(errMsg) {
self.warn("loadKeyPath: error loading lazy " + parent);
opts.callback(self, node, "error");
dfd.rejectWith(self);
});
} | function __lazyload(dfd, parent, pathSegList) {
// console.log("__lazyload", parent, "pathSegList=", pathSegList);
opts.callback(self, parent, "loading");
parent
.load()
.done(function() {
self._loadKeyPathImpl
.call(self, dfd, opts, parent, pathSegList)
.always(_makeResolveFunc(dfd, self));
})
.fail(function(errMsg) {
self.warn("loadKeyPath: error loading lazy " + parent);
opts.callback(self, node, "error");
dfd.rejectWith(self);
});
} |
JavaScript | function autoScroll(tree, event) {
var spOfs,
scrollTop,
delta,
dndOpts = tree.options.dnd5,
sp = tree.$scrollParent[0],
sensitivity = dndOpts.scrollSensitivity,
speed = dndOpts.scrollSpeed,
scrolled = 0;
if (sp !== document && sp.tagName !== "HTML") {
spOfs = tree.$scrollParent.offset();
scrollTop = sp.scrollTop;
if (spOfs.top + sp.offsetHeight - event.pageY < sensitivity) {
delta =
sp.scrollHeight -
tree.$scrollParent.innerHeight() -
scrollTop;
// console.log ("sp.offsetHeight: " + sp.offsetHeight
// + ", spOfs.top: " + spOfs.top
// + ", scrollTop: " + scrollTop
// + ", innerHeight: " + tree.$scrollParent.innerHeight()
// + ", scrollHeight: " + sp.scrollHeight
// + ", delta: " + delta
// );
if (delta > 0) {
sp.scrollTop = scrolled = scrollTop + speed;
}
} else if (scrollTop > 0 && event.pageY - spOfs.top < sensitivity) {
sp.scrollTop = scrolled = scrollTop - speed;
}
} else {
scrollTop = $(document).scrollTop();
if (scrollTop > 0 && event.pageY - scrollTop < sensitivity) {
scrolled = scrollTop - speed;
$(document).scrollTop(scrolled);
} else if (
$(window).height() - (event.pageY - scrollTop) <
sensitivity
) {
scrolled = scrollTop + speed;
$(document).scrollTop(scrolled);
}
}
if (scrolled) {
tree.debug("autoScroll: " + scrolled + "px");
}
return scrolled;
} | function autoScroll(tree, event) {
var spOfs,
scrollTop,
delta,
dndOpts = tree.options.dnd5,
sp = tree.$scrollParent[0],
sensitivity = dndOpts.scrollSensitivity,
speed = dndOpts.scrollSpeed,
scrolled = 0;
if (sp !== document && sp.tagName !== "HTML") {
spOfs = tree.$scrollParent.offset();
scrollTop = sp.scrollTop;
if (spOfs.top + sp.offsetHeight - event.pageY < sensitivity) {
delta =
sp.scrollHeight -
tree.$scrollParent.innerHeight() -
scrollTop;
// console.log ("sp.offsetHeight: " + sp.offsetHeight
// + ", spOfs.top: " + spOfs.top
// + ", scrollTop: " + scrollTop
// + ", innerHeight: " + tree.$scrollParent.innerHeight()
// + ", scrollHeight: " + sp.scrollHeight
// + ", delta: " + delta
// );
if (delta > 0) {
sp.scrollTop = scrolled = scrollTop + speed;
}
} else if (scrollTop > 0 && event.pageY - spOfs.top < sensitivity) {
sp.scrollTop = scrolled = scrollTop - speed;
}
} else {
scrollTop = $(document).scrollTop();
if (scrollTop > 0 && event.pageY - scrollTop < sensitivity) {
scrolled = scrollTop - speed;
$(document).scrollTop(scrolled);
} else if (
$(window).height() - (event.pageY - scrollTop) <
sensitivity
) {
scrolled = scrollTop + speed;
$(document).scrollTop(scrolled);
}
}
if (scrolled) {
tree.debug("autoScroll: " + scrolled + "px");
}
return scrolled;
} |
JavaScript | function evalEffectModifiers(tree, event, effectDefault) {
var res = effectDefault;
if (isMac) {
if (event.metaKey && event.altKey) {
// Mac: [Control] + [Option]
res = "link";
} else if (event.ctrlKey) {
// Chrome on Mac: [Control]
res = "link";
} else if (event.metaKey) {
// Mac: [Command]
res = "move";
} else if (event.altKey) {
// Mac: [Option]
res = "copy";
}
} else {
if (event.ctrlKey) {
// Windows: [Ctrl]
res = "copy";
} else if (event.shiftKey) {
// Windows: [Shift]
res = "move";
} else if (event.altKey) {
// Windows: [Alt]
res = "link";
}
}
if (res !== SUGGESTED_DROP_EFFECT) {
tree.info(
"evalEffectModifiers: " +
event.type +
" - evalEffectModifiers(): " +
SUGGESTED_DROP_EFFECT +
" -> " +
res
);
}
SUGGESTED_DROP_EFFECT = res;
// tree.debug("evalEffectModifiers: " + res);
return res;
} | function evalEffectModifiers(tree, event, effectDefault) {
var res = effectDefault;
if (isMac) {
if (event.metaKey && event.altKey) {
// Mac: [Control] + [Option]
res = "link";
} else if (event.ctrlKey) {
// Chrome on Mac: [Control]
res = "link";
} else if (event.metaKey) {
// Mac: [Command]
res = "move";
} else if (event.altKey) {
// Mac: [Option]
res = "copy";
}
} else {
if (event.ctrlKey) {
// Windows: [Ctrl]
res = "copy";
} else if (event.shiftKey) {
// Windows: [Shift]
res = "move";
} else if (event.altKey) {
// Windows: [Alt]
res = "link";
}
}
if (res !== SUGGESTED_DROP_EFFECT) {
tree.info(
"evalEffectModifiers: " +
event.type +
" - evalEffectModifiers(): " +
SUGGESTED_DROP_EFFECT +
" -> " +
res
);
}
SUGGESTED_DROP_EFFECT = res;
// tree.debug("evalEffectModifiers: " + res);
return res;
} |
JavaScript | function handleDragOver(event, data) {
// Implement auto-scrolling
if (data.options.dnd5.scroll) {
autoScroll(data.tree, event);
}
// Bail out with previous response if we get an invalid dragover
if (!data.node) {
data.tree.warn("Ignored dragover for non-node"); //, event, data);
return LAST_HIT_MODE;
}
var markerOffsetX,
nodeOfs,
pos,
relPosY,
hitMode = null,
tree = data.tree,
options = tree.options,
dndOpts = options.dnd5,
targetNode = data.node,
sourceNode = data.otherNode,
markerAt = "center",
$target = $(targetNode.span),
$targetTitle = $target.find("span.fancytree-title");
if (DRAG_ENTER_RESPONSE === false) {
tree.debug("Ignored dragover, since dragenter returned false.");
return false;
} else if (typeof DRAG_ENTER_RESPONSE === "string") {
$.error("assert failed: dragenter returned string");
}
// Calculate hitMode from relative cursor position.
nodeOfs = $target.offset();
relPosY = (event.pageY - nodeOfs.top) / $target.height();
if (event.pageY === undefined) {
tree.warn("event.pageY is undefined: see issue #1013.");
}
if (DRAG_ENTER_RESPONSE.after && relPosY > 0.75) {
hitMode = "after";
} else if (
!DRAG_ENTER_RESPONSE.over &&
DRAG_ENTER_RESPONSE.after &&
relPosY > 0.5
) {
hitMode = "after";
} else if (DRAG_ENTER_RESPONSE.before && relPosY <= 0.25) {
hitMode = "before";
} else if (
!DRAG_ENTER_RESPONSE.over &&
DRAG_ENTER_RESPONSE.before &&
relPosY <= 0.5
) {
hitMode = "before";
} else if (DRAG_ENTER_RESPONSE.over) {
hitMode = "over";
}
// Prevent no-ops like 'before source node'
// TODO: these are no-ops when moving nodes, but not in copy mode
if (dndOpts.preventVoidMoves && data.dropEffect === "move") {
if (targetNode === sourceNode) {
targetNode.debug("Drop over source node prevented.");
hitMode = null;
} else if (
hitMode === "before" &&
sourceNode &&
targetNode === sourceNode.getNextSibling()
) {
targetNode.debug("Drop after source node prevented.");
hitMode = null;
} else if (
hitMode === "after" &&
sourceNode &&
targetNode === sourceNode.getPrevSibling()
) {
targetNode.debug("Drop before source node prevented.");
hitMode = null;
} else if (
hitMode === "over" &&
sourceNode &&
sourceNode.parent === targetNode &&
sourceNode.isLastSibling()
) {
targetNode.debug("Drop last child over own parent prevented.");
hitMode = null;
}
}
// Let callback modify the calculated hitMode
data.hitMode = hitMode;
if (hitMode && dndOpts.dragOver) {
prepareDropEffectCallback(event, data);
dndOpts.dragOver(targetNode, data);
var allowDrop = !!hitMode;
applyDropEffectCallback(event, data, allowDrop);
hitMode = data.hitMode;
}
LAST_HIT_MODE = hitMode;
//
if (hitMode === "after" || hitMode === "before" || hitMode === "over") {
markerOffsetX = dndOpts.dropMarkerOffsetX || 0;
switch (hitMode) {
case "before":
markerAt = "top";
markerOffsetX += dndOpts.dropMarkerInsertOffsetX || 0;
break;
case "after":
markerAt = "bottom";
markerOffsetX += dndOpts.dropMarkerInsertOffsetX || 0;
break;
}
pos = {
my: "left" + offsetString(markerOffsetX) + " center",
at: "left " + markerAt,
of: $targetTitle,
};
if (options.rtl) {
pos.my = "right" + offsetString(-markerOffsetX) + " center";
pos.at = "right " + markerAt;
// console.log("rtl", pos);
}
$dropMarker
.toggleClass(classDropAfter, hitMode === "after")
.toggleClass(classDropOver, hitMode === "over")
.toggleClass(classDropBefore, hitMode === "before")
.show()
.position(FT.fixPositionOptions(pos));
} else {
$dropMarker.hide();
// console.log("hide dropmarker")
}
$(targetNode.span)
.toggleClass(
classDropTarget,
hitMode === "after" ||
hitMode === "before" ||
hitMode === "over"
)
.toggleClass(classDropAfter, hitMode === "after")
.toggleClass(classDropBefore, hitMode === "before")
.toggleClass(classDropAccept, hitMode === "over")
.toggleClass(classDropReject, hitMode === false);
return hitMode;
} | function handleDragOver(event, data) {
// Implement auto-scrolling
if (data.options.dnd5.scroll) {
autoScroll(data.tree, event);
}
// Bail out with previous response if we get an invalid dragover
if (!data.node) {
data.tree.warn("Ignored dragover for non-node"); //, event, data);
return LAST_HIT_MODE;
}
var markerOffsetX,
nodeOfs,
pos,
relPosY,
hitMode = null,
tree = data.tree,
options = tree.options,
dndOpts = options.dnd5,
targetNode = data.node,
sourceNode = data.otherNode,
markerAt = "center",
$target = $(targetNode.span),
$targetTitle = $target.find("span.fancytree-title");
if (DRAG_ENTER_RESPONSE === false) {
tree.debug("Ignored dragover, since dragenter returned false.");
return false;
} else if (typeof DRAG_ENTER_RESPONSE === "string") {
$.error("assert failed: dragenter returned string");
}
// Calculate hitMode from relative cursor position.
nodeOfs = $target.offset();
relPosY = (event.pageY - nodeOfs.top) / $target.height();
if (event.pageY === undefined) {
tree.warn("event.pageY is undefined: see issue #1013.");
}
if (DRAG_ENTER_RESPONSE.after && relPosY > 0.75) {
hitMode = "after";
} else if (
!DRAG_ENTER_RESPONSE.over &&
DRAG_ENTER_RESPONSE.after &&
relPosY > 0.5
) {
hitMode = "after";
} else if (DRAG_ENTER_RESPONSE.before && relPosY <= 0.25) {
hitMode = "before";
} else if (
!DRAG_ENTER_RESPONSE.over &&
DRAG_ENTER_RESPONSE.before &&
relPosY <= 0.5
) {
hitMode = "before";
} else if (DRAG_ENTER_RESPONSE.over) {
hitMode = "over";
}
// Prevent no-ops like 'before source node'
// TODO: these are no-ops when moving nodes, but not in copy mode
if (dndOpts.preventVoidMoves && data.dropEffect === "move") {
if (targetNode === sourceNode) {
targetNode.debug("Drop over source node prevented.");
hitMode = null;
} else if (
hitMode === "before" &&
sourceNode &&
targetNode === sourceNode.getNextSibling()
) {
targetNode.debug("Drop after source node prevented.");
hitMode = null;
} else if (
hitMode === "after" &&
sourceNode &&
targetNode === sourceNode.getPrevSibling()
) {
targetNode.debug("Drop before source node prevented.");
hitMode = null;
} else if (
hitMode === "over" &&
sourceNode &&
sourceNode.parent === targetNode &&
sourceNode.isLastSibling()
) {
targetNode.debug("Drop last child over own parent prevented.");
hitMode = null;
}
}
// Let callback modify the calculated hitMode
data.hitMode = hitMode;
if (hitMode && dndOpts.dragOver) {
prepareDropEffectCallback(event, data);
dndOpts.dragOver(targetNode, data);
var allowDrop = !!hitMode;
applyDropEffectCallback(event, data, allowDrop);
hitMode = data.hitMode;
}
LAST_HIT_MODE = hitMode;
//
if (hitMode === "after" || hitMode === "before" || hitMode === "over") {
markerOffsetX = dndOpts.dropMarkerOffsetX || 0;
switch (hitMode) {
case "before":
markerAt = "top";
markerOffsetX += dndOpts.dropMarkerInsertOffsetX || 0;
break;
case "after":
markerAt = "bottom";
markerOffsetX += dndOpts.dropMarkerInsertOffsetX || 0;
break;
}
pos = {
my: "left" + offsetString(markerOffsetX) + " center",
at: "left " + markerAt,
of: $targetTitle,
};
if (options.rtl) {
pos.my = "right" + offsetString(-markerOffsetX) + " center";
pos.at = "right " + markerAt;
// console.log("rtl", pos);
}
$dropMarker
.toggleClass(classDropAfter, hitMode === "after")
.toggleClass(classDropOver, hitMode === "over")
.toggleClass(classDropBefore, hitMode === "before")
.show()
.position(FT.fixPositionOptions(pos));
} else {
$dropMarker.hide();
// console.log("hide dropmarker")
}
$(targetNode.span)
.toggleClass(
classDropTarget,
hitMode === "after" ||
hitMode === "before" ||
hitMode === "over"
)
.toggleClass(classDropAfter, hitMode === "after")
.toggleClass(classDropBefore, hitMode === "before")
.toggleClass(classDropAccept, hitMode === "over")
.toggleClass(classDropReject, hitMode === false);
return hitMode;
} |
JavaScript | function onDragEvent(event) {
var json,
tree = this,
dndOpts = tree.options.dnd5,
node = FT.getNode(event),
dataTransfer =
event.dataTransfer || event.originalEvent.dataTransfer,
data = {
tree: tree,
node: node,
options: tree.options,
originalEvent: event.originalEvent,
widget: tree.widget,
dataTransfer: dataTransfer,
useDefaultImage: true,
dropEffect: undefined,
dropEffectSuggested: undefined,
effectAllowed: undefined, // set by dragstart
files: undefined, // only for drop events
isCancelled: undefined, // set by dragend
isMove: undefined,
};
switch (event.type) {
case "dragstart":
if (!node) {
tree.info("Ignored dragstart on a non-node.");
return false;
}
// Store current source node in different formats
SOURCE_NODE = node;
// Also optionally store selected nodes
if (dndOpts.multiSource === false) {
SOURCE_NODE_LIST = [node];
} else if (dndOpts.multiSource === true) {
if (node.isSelected()) {
SOURCE_NODE_LIST = tree.getSelectedNodes();
} else {
SOURCE_NODE_LIST = [node];
}
} else {
SOURCE_NODE_LIST = dndOpts.multiSource(node, data);
}
// Cache as array of jQuery objects for faster access:
$sourceList = $(
$.map(SOURCE_NODE_LIST, function(n) {
return n.span;
})
);
// Set visual feedback
$sourceList.addClass(classDragSource);
// Set payload
// Note:
// Transfer data is only accessible on dragstart and drop!
// For all other events the formats and kinds in the drag
// data store list of items representing dragged data can be
// enumerated, but the data itself is unavailable and no new
// data can be added.
var nodeData = node.toDict(true, dndOpts.sourceCopyHook);
nodeData.treeId = node.tree._id;
json = JSON.stringify(nodeData);
try {
dataTransfer.setData(nodeMimeType, json);
dataTransfer.setData("text/html", $(node.span).html());
dataTransfer.setData("text/plain", node.title);
} catch (ex) {
// IE only accepts 'text' type
tree.warn(
"Could not set data (IE only accepts 'text') - " + ex
);
}
// We always need to set the 'text' type if we want to drag
// Because IE 11 only accepts this single type.
// If we pass JSON here, IE can can access all node properties,
// even when the source lives in another window. (D'n'd inside
// the same window will always work.)
// The drawback is, that in this case ALL browsers will see
// the JSON representation as 'text', so dragging
// to a text field will insert the JSON string instead of
// the node title.
if (dndOpts.setTextTypeJson) {
dataTransfer.setData("text", json);
} else {
dataTransfer.setData("text", node.title);
}
// Set the allowed drag modes (combinations of move, copy, and link)
// (effectAllowed can only be set in the dragstart event.)
// This can be overridden in the dragStart() callback
prepareDropEffectCallback(event, data);
// Let user cancel or modify above settings
// Realize potential changes by previous callback
if (dndOpts.dragStart(node, data) === false) {
// Cancel dragging
// dataTransfer.dropEffect = "none";
_clearGlobals();
return false;
}
applyDropEffectCallback(event, data);
// Unless user set `data.useDefaultImage` to false in dragStart,
// generata a default drag image now:
$extraHelper = null;
if (data.useDefaultImage) {
// Set the title as drag image (otherwise it would contain the expander)
$dragImage = $(node.span).find(".fancytree-title");
if (SOURCE_NODE_LIST && SOURCE_NODE_LIST.length > 1) {
// Add a counter badge to node title if dragging more than one node.
// We want this, because the element that is used as drag image
// must be *visible* in the DOM, so we cannot create some hidden
// custom markup.
// See https://kryogenix.org/code/browser/custom-drag-image.html
// Also, since IE 11 and Edge don't support setDragImage() alltogether,
// it gives som feedback to the user.
// The badge will be removed later on drag end.
$extraHelper = $(
"<span class='fancytree-childcounter'/>"
)
.text("+" + (SOURCE_NODE_LIST.length - 1))
.appendTo($dragImage);
}
if (dataTransfer.setDragImage) {
// IE 11 and Edge do not support this
dataTransfer.setDragImage($dragImage[0], -10, -10);
}
}
return true;
case "drag":
// Called every few milliseconds (no matter if the
// cursor is over a valid drop target)
// data.tree.info("drag", SOURCE_NODE)
prepareDropEffectCallback(event, data);
dndOpts.dragDrag(node, data);
applyDropEffectCallback(event, data);
$sourceList.toggleClass(classDragRemove, data.isMove);
break;
case "dragend":
// Called at the end of a d'n'd process (after drop)
// Note caveat: If drop removed the dragged source element,
// we may not get this event, since the target does not exist
// anymore
prepareDropEffectCallback(event, data);
_clearGlobals();
data.isCancelled = !LAST_HIT_MODE;
dndOpts.dragEnd(node, data, !LAST_HIT_MODE);
// applyDropEffectCallback(event, data);
break;
}
} | function onDragEvent(event) {
var json,
tree = this,
dndOpts = tree.options.dnd5,
node = FT.getNode(event),
dataTransfer =
event.dataTransfer || event.originalEvent.dataTransfer,
data = {
tree: tree,
node: node,
options: tree.options,
originalEvent: event.originalEvent,
widget: tree.widget,
dataTransfer: dataTransfer,
useDefaultImage: true,
dropEffect: undefined,
dropEffectSuggested: undefined,
effectAllowed: undefined, // set by dragstart
files: undefined, // only for drop events
isCancelled: undefined, // set by dragend
isMove: undefined,
};
switch (event.type) {
case "dragstart":
if (!node) {
tree.info("Ignored dragstart on a non-node.");
return false;
}
// Store current source node in different formats
SOURCE_NODE = node;
// Also optionally store selected nodes
if (dndOpts.multiSource === false) {
SOURCE_NODE_LIST = [node];
} else if (dndOpts.multiSource === true) {
if (node.isSelected()) {
SOURCE_NODE_LIST = tree.getSelectedNodes();
} else {
SOURCE_NODE_LIST = [node];
}
} else {
SOURCE_NODE_LIST = dndOpts.multiSource(node, data);
}
// Cache as array of jQuery objects for faster access:
$sourceList = $(
$.map(SOURCE_NODE_LIST, function(n) {
return n.span;
})
);
// Set visual feedback
$sourceList.addClass(classDragSource);
// Set payload
// Note:
// Transfer data is only accessible on dragstart and drop!
// For all other events the formats and kinds in the drag
// data store list of items representing dragged data can be
// enumerated, but the data itself is unavailable and no new
// data can be added.
var nodeData = node.toDict(true, dndOpts.sourceCopyHook);
nodeData.treeId = node.tree._id;
json = JSON.stringify(nodeData);
try {
dataTransfer.setData(nodeMimeType, json);
dataTransfer.setData("text/html", $(node.span).html());
dataTransfer.setData("text/plain", node.title);
} catch (ex) {
// IE only accepts 'text' type
tree.warn(
"Could not set data (IE only accepts 'text') - " + ex
);
}
// We always need to set the 'text' type if we want to drag
// Because IE 11 only accepts this single type.
// If we pass JSON here, IE can can access all node properties,
// even when the source lives in another window. (D'n'd inside
// the same window will always work.)
// The drawback is, that in this case ALL browsers will see
// the JSON representation as 'text', so dragging
// to a text field will insert the JSON string instead of
// the node title.
if (dndOpts.setTextTypeJson) {
dataTransfer.setData("text", json);
} else {
dataTransfer.setData("text", node.title);
}
// Set the allowed drag modes (combinations of move, copy, and link)
// (effectAllowed can only be set in the dragstart event.)
// This can be overridden in the dragStart() callback
prepareDropEffectCallback(event, data);
// Let user cancel or modify above settings
// Realize potential changes by previous callback
if (dndOpts.dragStart(node, data) === false) {
// Cancel dragging
// dataTransfer.dropEffect = "none";
_clearGlobals();
return false;
}
applyDropEffectCallback(event, data);
// Unless user set `data.useDefaultImage` to false in dragStart,
// generata a default drag image now:
$extraHelper = null;
if (data.useDefaultImage) {
// Set the title as drag image (otherwise it would contain the expander)
$dragImage = $(node.span).find(".fancytree-title");
if (SOURCE_NODE_LIST && SOURCE_NODE_LIST.length > 1) {
// Add a counter badge to node title if dragging more than one node.
// We want this, because the element that is used as drag image
// must be *visible* in the DOM, so we cannot create some hidden
// custom markup.
// See https://kryogenix.org/code/browser/custom-drag-image.html
// Also, since IE 11 and Edge don't support setDragImage() alltogether,
// it gives som feedback to the user.
// The badge will be removed later on drag end.
$extraHelper = $(
"<span class='fancytree-childcounter'/>"
)
.text("+" + (SOURCE_NODE_LIST.length - 1))
.appendTo($dragImage);
}
if (dataTransfer.setDragImage) {
// IE 11 and Edge do not support this
dataTransfer.setDragImage($dragImage[0], -10, -10);
}
}
return true;
case "drag":
// Called every few milliseconds (no matter if the
// cursor is over a valid drop target)
// data.tree.info("drag", SOURCE_NODE)
prepareDropEffectCallback(event, data);
dndOpts.dragDrag(node, data);
applyDropEffectCallback(event, data);
$sourceList.toggleClass(classDragRemove, data.isMove);
break;
case "dragend":
// Called at the end of a d'n'd process (after drop)
// Note caveat: If drop removed the dragged source element,
// we may not get this event, since the target does not exist
// anymore
prepareDropEffectCallback(event, data);
_clearGlobals();
data.isCancelled = !LAST_HIT_MODE;
dndOpts.dragEnd(node, data, !LAST_HIT_MODE);
// applyDropEffectCallback(event, data);
break;
}
} |
JavaScript | function hexToRGB(hex) {
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
} | function hexToRGB(hex) {
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
} |
JavaScript | function loopDigits(charaters,digits){
var finalDigit = digits
digits = 2
var stCombine = intialWordlist(charaters)
var finalDictList ={wordlist:[]}
finalDictList.wordlist.push(dictSturct(digits,stCombine,stCombine.length))
digits = 3
for(var i=0; i < finalDigit-2; ++i ){
if(digits < finalDigit || digits == finalDigit ){
var NewCombine = WordMaker(charaters,stCombine)
finalDictList.wordlist.push(dictSturct(i+digits,NewCombine,NewCombine.length))
stCombine = NewCombine
digits += i
}
else{
console.log("Completed")
return false
}
}
console.log(finalDictList)
} | function loopDigits(charaters,digits){
var finalDigit = digits
digits = 2
var stCombine = intialWordlist(charaters)
var finalDictList ={wordlist:[]}
finalDictList.wordlist.push(dictSturct(digits,stCombine,stCombine.length))
digits = 3
for(var i=0; i < finalDigit-2; ++i ){
if(digits < finalDigit || digits == finalDigit ){
var NewCombine = WordMaker(charaters,stCombine)
finalDictList.wordlist.push(dictSturct(i+digits,NewCombine,NewCombine.length))
stCombine = NewCombine
digits += i
}
else{
console.log("Completed")
return false
}
}
console.log(finalDictList)
} |
JavaScript | function intialWordlist(string){
var predefine = string
var wordlistsArray=[]
for(var i =0; i < string.length; ++i){
var letter = string[i]
var newString = SliceAndKeep(string)
if(predefine != newString){
for(var j=0; j < newString.length; ++j){
var frist = letter
letter += newString[j]
wordlistsArray.push(letter)
letter = frist
}
}
}
return wordlistsArray
} | function intialWordlist(string){
var predefine = string
var wordlistsArray=[]
for(var i =0; i < string.length; ++i){
var letter = string[i]
var newString = SliceAndKeep(string)
if(predefine != newString){
for(var j=0; j < newString.length; ++j){
var frist = letter
letter += newString[j]
wordlistsArray.push(letter)
letter = frist
}
}
}
return wordlistsArray
} |
JavaScript | function WordMaker(string,conitinuesArry){
var predefine = string
var wordlistsArray=[]
for(var i =0; i < conitinuesArry.length; ++i){
var letter = conitinuesArry[i]
var newString = SliceAndKeep(string)
if(predefine != newString){
for(var j=0; j < newString.length; ++j){
var frist = letter
letter += newString[j]
wordlistsArray.push(letter)
letter = frist
}
}
}
return wordlistsArray
} | function WordMaker(string,conitinuesArry){
var predefine = string
var wordlistsArray=[]
for(var i =0; i < conitinuesArry.length; ++i){
var letter = conitinuesArry[i]
var newString = SliceAndKeep(string)
if(predefine != newString){
for(var j=0; j < newString.length; ++j){
var frist = letter
letter += newString[j]
wordlistsArray.push(letter)
letter = frist
}
}
}
return wordlistsArray
} |
JavaScript | function SliceAndKeep(string){
var fristCharater = string[0]
var Newstring = string.slice(1)
Newstring += fristCharater
return Newstring
} | function SliceAndKeep(string){
var fristCharater = string[0]
var Newstring = string.slice(1)
Newstring += fristCharater
return Newstring
} |
JavaScript | function generateLoaders(loader, loaderOptions) {
let loaders = []
if (loader) {
loaders = [{
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
}]
}
if (options.extract) {
let extractLoader = {
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '../../'
}
}
return [extractLoader, 'css-loader'].concat(['postcss-loader'], loaders)
} else {
return ['vue-style-loader', 'css-loader'].concat(['postcss-loader'], loaders)
}
} | function generateLoaders(loader, loaderOptions) {
let loaders = []
if (loader) {
loaders = [{
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
}]
}
if (options.extract) {
let extractLoader = {
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '../../'
}
}
return [extractLoader, 'css-loader'].concat(['postcss-loader'], loaders)
} else {
return ['vue-style-loader', 'css-loader'].concat(['postcss-loader'], loaders)
}
} |
JavaScript | static get defaultOptions() {
return mergeObject(super.defaultOptions, {
classes: ["tidy5e", "dnd5e", "sheet", "actor", "npc"],
width: 740,
height: 720
});
} | static get defaultOptions() {
return mergeObject(super.defaultOptions, {
classes: ["tidy5e", "dnd5e", "sheet", "actor", "npc"],
width: 740,
height: 720
});
} |
JavaScript | _prepareItems(data) {
// Categorize Items as Features and Spells
const features = {
passive: { label: game.i18n.localize("DND5E.Features"), items: [], dataset: {type: "feat"} },
weapons: { label: game.i18n.localize("DND5E.AttackPl"), items: [] , hasActions: true, dataset: {type: "weapon", "weapon-type": "natural"} },
actions: { label: game.i18n.localize("DND5E.ActionPl"), items: [] , hasActions: true, dataset: {type: "feat", "activation.type": "action"} },
equipment: { label: game.i18n.localize("DND5E.Inventory"), items: [], dataset: {type: "loot"}}
};
// Start by classifying items into groups for rendering
let [spells, other] = data.items.reduce((arr, item) => {
item.img = item.img || DEFAULT_TOKEN;
item.isStack = item.data.quantity ? item.data.quantity > 1 : false;
item.hasUses = item.data.uses && (item.data.uses.max > 0);
item.isOnCooldown = item.data.recharge && !!item.data.recharge.value && (item.data.recharge.charged === false);
item.isDepleted = item.isOnCooldown && (item.data.uses.per && (item.data.uses.value > 0));
item.hasTarget = !!item.data.target && !(["none",""].includes(item.data.target.type));
if ( item.type === "spell" ) arr[0].push(item);
else arr[1].push(item);
return arr;
}, [[], []]);
// Apply item filters
spells = this._filterItems(spells, this._filters.spellbook);
other = this._filterItems(other, this._filters.features);
// Organize Spellbook
const spellbook = this._prepareSpellbook(data, spells);
// Organize Features
/*
for ( let item of other ) {
// if ( item.type === "weapon" ) features.weapons.items.push(item);
// else
if ( item.type === "weapon" || item.type === "feat" ) {
if ( item.data.activation.type ) features.actions.items.push(item);
else features.passive.items.push(item);
}
else features.equipment.items.push(item);
}
*/
for ( let item of other ) {
if ( item.type === "weapon" ) features.weapons.items.push(item);
else if ( item.type === "feat" ) {
if ( item.data.activation.type ) features.actions.items.push(item);
else features.passive.items.push(item);
}
else features.equipment.items.push(item);
}
// Assign and return
data.features = Object.values(features);
data.spellbook = spellbook;
} | _prepareItems(data) {
// Categorize Items as Features and Spells
const features = {
passive: { label: game.i18n.localize("DND5E.Features"), items: [], dataset: {type: "feat"} },
weapons: { label: game.i18n.localize("DND5E.AttackPl"), items: [] , hasActions: true, dataset: {type: "weapon", "weapon-type": "natural"} },
actions: { label: game.i18n.localize("DND5E.ActionPl"), items: [] , hasActions: true, dataset: {type: "feat", "activation.type": "action"} },
equipment: { label: game.i18n.localize("DND5E.Inventory"), items: [], dataset: {type: "loot"}}
};
// Start by classifying items into groups for rendering
let [spells, other] = data.items.reduce((arr, item) => {
item.img = item.img || DEFAULT_TOKEN;
item.isStack = item.data.quantity ? item.data.quantity > 1 : false;
item.hasUses = item.data.uses && (item.data.uses.max > 0);
item.isOnCooldown = item.data.recharge && !!item.data.recharge.value && (item.data.recharge.charged === false);
item.isDepleted = item.isOnCooldown && (item.data.uses.per && (item.data.uses.value > 0));
item.hasTarget = !!item.data.target && !(["none",""].includes(item.data.target.type));
if ( item.type === "spell" ) arr[0].push(item);
else arr[1].push(item);
return arr;
}, [[], []]);
// Apply item filters
spells = this._filterItems(spells, this._filters.spellbook);
other = this._filterItems(other, this._filters.features);
// Organize Spellbook
const spellbook = this._prepareSpellbook(data, spells);
// Organize Features
/*
for ( let item of other ) {
// if ( item.type === "weapon" ) features.weapons.items.push(item);
// else
if ( item.type === "weapon" || item.type === "feat" ) {
if ( item.data.activation.type ) features.actions.items.push(item);
else features.passive.items.push(item);
}
else features.equipment.items.push(item);
}
*/
for ( let item of other ) {
if ( item.type === "weapon" ) features.weapons.items.push(item);
else if ( item.type === "feat" ) {
if ( item.data.activation.type ) features.actions.items.push(item);
else features.passive.items.push(item);
}
else features.equipment.items.push(item);
}
// Assign and return
data.features = Object.values(features);
data.spellbook = spellbook;
} |
JavaScript | function handleClassForDW(dom, bMS, nMS, beforeP, nextP, classes) {
if (bMS !== 0 && nMS !== 0) {
for (let i = 0; i < dom.length; i++) {
const dD = dom[i]
resetClassByInterval(dD, bMS, nMS, classes)
}
} else if (bMS !== 0) {
const removeCls = getClassByInterval(bMS, classes)
for (let i = 0; i < dom.length; i++) {
const dD = dom[i]
const date = i + 1
const interval = judgeInterval(date, nextP)
const addCls = getClassByInterval(interval, classes)
removeClass(dD, removeCls)
addClass(dD, addCls)
}
} else if (nMS !== 0) {
const addCls = getClassByInterval(nMS, classes)
for (let i = 0; i < dom.length; i++) {
const dD = dom[i]
const date = i + 1
const interval = judgeInterval(date, beforeP)
const removeCls = getClassByInterval(interval, classes)
removeClass(dD, removeCls)
addClass(dD, addCls)
}
}
} | function handleClassForDW(dom, bMS, nMS, beforeP, nextP, classes) {
if (bMS !== 0 && nMS !== 0) {
for (let i = 0; i < dom.length; i++) {
const dD = dom[i]
resetClassByInterval(dD, bMS, nMS, classes)
}
} else if (bMS !== 0) {
const removeCls = getClassByInterval(bMS, classes)
for (let i = 0; i < dom.length; i++) {
const dD = dom[i]
const date = i + 1
const interval = judgeInterval(date, nextP)
const addCls = getClassByInterval(interval, classes)
removeClass(dD, removeCls)
addClass(dD, addCls)
}
} else if (nMS !== 0) {
const addCls = getClassByInterval(nMS, classes)
for (let i = 0; i < dom.length; i++) {
const dD = dom[i]
const date = i + 1
const interval = judgeInterval(date, beforeP)
const removeCls = getClassByInterval(interval, classes)
removeClass(dD, removeCls)
addClass(dD, addCls)
}
}
} |
JavaScript | function resetYMDs(ymDs, diffM, doms) {
const {
beforeYM: { year: by, month: bm },
nextYM: { year: ny, month: nm }
} = diffM
ymDs[ny] || (ymDs[ny] = {})
ymDs[ny][nm] = doms
delete ymDs[by][bm]
} | function resetYMDs(ymDs, diffM, doms) {
const {
beforeYM: { year: by, month: bm },
nextYM: { year: ny, month: nm }
} = diffM
ymDs[ny] || (ymDs[ny] = {})
ymDs[ny][nm] = doms
delete ymDs[by][bm]
} |
JavaScript | function resetYMDs(ymDs, diffM, doms) {
var _diffM$beforeYM = diffM.beforeYM,
by = _diffM$beforeYM.year,
bm = _diffM$beforeYM.month,
_diffM$nextYM = diffM.nextYM,
ny = _diffM$nextYM.year,
nm = _diffM$nextYM.month;
ymDs[ny] || (ymDs[ny] = {});
ymDs[ny][nm] = doms;
delete ymDs[by][bm];
} // step2. move | function resetYMDs(ymDs, diffM, doms) {
var _diffM$beforeYM = diffM.beforeYM,
by = _diffM$beforeYM.year,
bm = _diffM$beforeYM.month,
_diffM$nextYM = diffM.nextYM,
ny = _diffM$nextYM.year,
nm = _diffM$nextYM.month;
ymDs[ny] || (ymDs[ny] = {});
ymDs[ny][nm] = doms;
delete ymDs[by][bm];
} // step2. move |
JavaScript | function initEmptyFDDoms(fd, yms, opts) {
const { tag_empFDate, cls_empFDate, cls_passEmpFDate, cls_unPassEmpFDate } = opts
const { mStatus } = yms
const sCls = mStatus <= 0 ? cls_passEmpFDate : cls_unPassEmpFDate
return initO1EmptyDoms(1, fd, tag_empFDate, [...cls_empFDate, ...sCls])
} | function initEmptyFDDoms(fd, yms, opts) {
const { tag_empFDate, cls_empFDate, cls_passEmpFDate, cls_unPassEmpFDate } = opts
const { mStatus } = yms
const sCls = mStatus <= 0 ? cls_passEmpFDate : cls_unPassEmpFDate
return initO1EmptyDoms(1, fd, tag_empFDate, [...cls_empFDate, ...sCls])
} |
JavaScript | function stripFirstWord (message) {
var index = message.indexOf(' ');
if(index > -1){
return message.substr(index + 1);
} else {
return "null"
}
} | function stripFirstWord (message) {
var index = message.indexOf(' ');
if(index > -1){
return message.substr(index + 1);
} else {
return "null"
}
} |
JavaScript | promptPlayer() {
this.print();
this.move = prompt('\nWhich way? [w (up), a (left), s (down), d (right)] ');
if (!moves.includes(this.move)) {
console.log('Invalid move. Please try again.');
this.promptPlayer();
}
} | promptPlayer() {
this.print();
this.move = prompt('\nWhich way? [w (up), a (left), s (down), d (right)] ');
if (!moves.includes(this.move)) {
console.log('Invalid move. Please try again.');
this.promptPlayer();
}
} |
JavaScript | static patchOnlineMonitoringRules(deviceId, config) {
return ApiService.call(
`/devices/${deviceId}/onlinemonitoring`,
'PATCH',
config
);
} | static patchOnlineMonitoringRules(deviceId, config) {
return ApiService.call(
`/devices/${deviceId}/onlinemonitoring`,
'PATCH',
config
);
} |
JavaScript | static uninstallApplication(applicationId) {
return ApiService.call(
`/applications/${applicationId}/installation`,
'DELETE'
);
} | static uninstallApplication(applicationId) {
return ApiService.call(
`/applications/${applicationId}/installation`,
'DELETE'
);
} |
JavaScript | static patchOnlineMonitoringRules(deviceTypeId, config) {
return ApiService.call(
`/device-types/${deviceTypeId}/onlinemonitoring`,
'PATCH',
config
);
} | static patchOnlineMonitoringRules(deviceTypeId, config) {
return ApiService.call(
`/device-types/${deviceTypeId}/onlinemonitoring`,
'PATCH',
config
);
} |
JavaScript | changeTenant(tenantId) {
return tenantId
? this.manager.changeTenant(tenantId)
: this.manager.signinRedirect();
} | changeTenant(tenantId) {
return tenantId
? this.manager.changeTenant(tenantId)
: this.manager.signinRedirect();
} |
JavaScript | function startBusinessTZDay(businessData, utcDate) {
var originalDateUnits = _.reduce(['year', 'month', 'date'], function(ret, unit) {
ret[unit] = utcDate.get(unit);
return ret;
}, {});
setBusinessDateTZ(businessData, utcDate);
_.each(originalDateUnits, function(value, unit) {
utcDate.set(unit, value);
});
// If timezone is greater than zero,
// then add this offset to the time zone's business day was the same
utcDate.startOf('day');
var businessUtcOffset = businessTimezoneUtcOffset(businessData);
if (businessUtcOffset > 0) {
utcDate.add(businessUtcOffset, 'minute');
}
} | function startBusinessTZDay(businessData, utcDate) {
var originalDateUnits = _.reduce(['year', 'month', 'date'], function(ret, unit) {
ret[unit] = utcDate.get(unit);
return ret;
}, {});
setBusinessDateTZ(businessData, utcDate);
_.each(originalDateUnits, function(value, unit) {
utcDate.set(unit, value);
});
// If timezone is greater than zero,
// then add this offset to the time zone's business day was the same
utcDate.startOf('day');
var businessUtcOffset = businessTimezoneUtcOffset(businessData);
if (businessUtcOffset > 0) {
utcDate.add(businessUtcOffset, 'minute');
}
} |
JavaScript | function cutSlots(iterator) {
let slot, slots = [];
while ((slot = iterator.nextSlot())) {
slots.push(slot);
}
return slots;
} | function cutSlots(iterator) {
let slot, slots = [];
while ((slot = iterator.nextSlot())) {
slots.push(slot);
}
return slots;
} |
JavaScript | function cutSlotsWithoutBusy(iterator) {
let slot, slots = [];
while ((slot = iterator.nextSlot())) {
if (slot.available) slots.push(slot);
}
return slots;
} | function cutSlotsWithoutBusy(iterator) {
let slot, slots = [];
while ((slot = iterator.nextSlot())) {
if (slot.available) slots.push(slot);
}
return slots;
} |
JavaScript | function cutSlotsWithoutStartBusy(iterator) {
let slot, slots = [];
// skip unavailable slots from start of day
while ((slot = iterator.nextSlot()) && !slot.available) {}
if (!slot) return slots;
slots.push(slot);
while ((slot = iterator.nextSlot())) {
slots.push(slot);
}
return slots;
} | function cutSlotsWithoutStartBusy(iterator) {
let slot, slots = [];
// skip unavailable slots from start of day
while ((slot = iterator.nextSlot()) && !slot.available) {}
if (!slot) return slots;
slots.push(slot);
while ((slot = iterator.nextSlot())) {
slots.push(slot);
}
return slots;
} |
JavaScript | function cutSlotsWithoutStartFinishBusy(iterator) {
let slots = cutSlotsWithoutStartBusy(iterator);
// skip unavailable slots from end of day
let lastPosition = -1;
for (let i = slots.length - 1; i >= 0; i--) {
if (slots[i].available) {
lastPosition = i;
break;
}
}
return lastPosition < 0 ? [] : slots.slice(0, lastPosition + 1);
} | function cutSlotsWithoutStartFinishBusy(iterator) {
let slots = cutSlotsWithoutStartBusy(iterator);
// skip unavailable slots from end of day
let lastPosition = -1;
for (let i = slots.length - 1; i >= 0; i--) {
if (slots[i].available) {
lastPosition = i;
break;
}
}
return lastPosition < 0 ? [] : slots.slice(0, lastPosition + 1);
} |
JavaScript | function startBusinessTZDay(businessData, utcDate) {
var originalDateUnits = reduce(['year', 'month', 'date'], function (ret, unit) {
ret[unit] = utcDate.get(unit);
return ret;
}, {});
setBusinessDateTZ(businessData, utcDate);
each(originalDateUnits, function (value, unit) {
utcDate.set(unit, value);
});
// If timezone is greater than zero,
// then add this offset to the time zone's business day was the same
utcDate.startOf('day');
var businessUtcOffset = businessTimezoneUtcOffset(businessData);
if (businessUtcOffset > 0) {
utcDate.add(businessUtcOffset, 'minute');
}
} | function startBusinessTZDay(businessData, utcDate) {
var originalDateUnits = reduce(['year', 'month', 'date'], function (ret, unit) {
ret[unit] = utcDate.get(unit);
return ret;
}, {});
setBusinessDateTZ(businessData, utcDate);
each(originalDateUnits, function (value, unit) {
utcDate.set(unit, value);
});
// If timezone is greater than zero,
// then add this offset to the time zone's business day was the same
utcDate.startOf('day');
var businessUtcOffset = businessTimezoneUtcOffset(businessData);
if (businessUtcOffset > 0) {
utcDate.add(businessUtcOffset, 'minute');
}
} |
JavaScript | function isDateForbidden(widgetConfiguration, date, ignoreStartDate) {
if (ignoreStartDate === null || typeof ignoreStartDate == 'undefined') {
ignoreStartDate = false;
}
if (widgetConfiguration && widgetConfiguration.bookableDateRanges && widgetConfiguration.bookableDateRanges.enabled) {
var dateMoment = moment(date),
dateAvailable = true,
start = widgetConfiguration.bookableDateRanges.start,
end = widgetConfiguration.bookableDateRanges.end;
if (start && end && !ignoreStartDate) {
dateAvailable = dateMoment.isAfter(moment(start).startOf('day')) && dateMoment.isBefore(moment(end).endOf('day'));
} else if (start && !ignoreStartDate) {
dateAvailable = dateMoment.isAfter(moment(start).startOf('day'));
} else if (end) {
dateAvailable = dateMoment.isBefore(moment(end).endOf('day'));
}
return !dateAvailable;
}
//bookable weeks calculation
if (widgetConfiguration.bookableMonthsCount > 0 && widgetConfiguration.bookableMonthsCount < 1) {
var weeks = Math.round(widgetConfiguration.bookableMonthsCount / 0.23);
return moment().add(weeks, 'weeks').isBefore(date);
}
return !!(widgetConfiguration && widgetConfiguration.bookableMonthsCount > 0 && moment().add('M', widgetConfiguration.bookableMonthsCount - 1).endOf('M').isBefore(date));
} | function isDateForbidden(widgetConfiguration, date, ignoreStartDate) {
if (ignoreStartDate === null || typeof ignoreStartDate == 'undefined') {
ignoreStartDate = false;
}
if (widgetConfiguration && widgetConfiguration.bookableDateRanges && widgetConfiguration.bookableDateRanges.enabled) {
var dateMoment = moment(date),
dateAvailable = true,
start = widgetConfiguration.bookableDateRanges.start,
end = widgetConfiguration.bookableDateRanges.end;
if (start && end && !ignoreStartDate) {
dateAvailable = dateMoment.isAfter(moment(start).startOf('day')) && dateMoment.isBefore(moment(end).endOf('day'));
} else if (start && !ignoreStartDate) {
dateAvailable = dateMoment.isAfter(moment(start).startOf('day'));
} else if (end) {
dateAvailable = dateMoment.isBefore(moment(end).endOf('day'));
}
return !dateAvailable;
}
//bookable weeks calculation
if (widgetConfiguration.bookableMonthsCount > 0 && widgetConfiguration.bookableMonthsCount < 1) {
var weeks = Math.round(widgetConfiguration.bookableMonthsCount / 0.23);
return moment().add(weeks, 'weeks').isBefore(date);
}
return !!(widgetConfiguration && widgetConfiguration.bookableMonthsCount > 0 && moment().add('M', widgetConfiguration.bookableMonthsCount - 1).endOf('M').isBefore(date));
} |
JavaScript | function alignmentBusySlotsByTaxonomyDuration(startDate, taxonomyDuration, slotSize, busySlots) {
each(busySlots, function (busySlot) {
busySlot.duration = taxonomyDuration;
});
var duration = slotSize || taxonomyDuration;
each(busySlots, function (busySlot) {
var busyTimeMin = moment.utc(busySlot.time).diff(moment.utc(startDate), 'minute');
var alignBusyTimeMin = Math.floor(busyTimeMin / duration) * duration;
if (busyTimeMin !== alignBusyTimeMin) {
var alignBusySlotTime = moment.utc(startDate).add(alignBusyTimeMin, 'minutes').toISOString();
var alignEndBusyTimeMin = Math.ceil((busyTimeMin + busySlot.duration) / duration) * duration;
busySlot.time = alignBusySlotTime;
busySlot.duration = alignEndBusyTimeMin - alignBusyTimeMin;
}
});
} | function alignmentBusySlotsByTaxonomyDuration(startDate, taxonomyDuration, slotSize, busySlots) {
each(busySlots, function (busySlot) {
busySlot.duration = taxonomyDuration;
});
var duration = slotSize || taxonomyDuration;
each(busySlots, function (busySlot) {
var busyTimeMin = moment.utc(busySlot.time).diff(moment.utc(startDate), 'minute');
var alignBusyTimeMin = Math.floor(busyTimeMin / duration) * duration;
if (busyTimeMin !== alignBusyTimeMin) {
var alignBusySlotTime = moment.utc(startDate).add(alignBusyTimeMin, 'minutes').toISOString();
var alignEndBusyTimeMin = Math.ceil((busyTimeMin + busySlot.duration) / duration) * duration;
busySlot.time = alignBusySlotTime;
busySlot.duration = alignEndBusyTimeMin - alignBusyTimeMin;
}
});
} |
JavaScript | function cutSlots$1(iterator) {
var slot = void 0,
slots = [];
while (slot = iterator.nextSlot()) {
slots.push(slot);
}
return slots;
} | function cutSlots$1(iterator) {
var slot = void 0,
slots = [];
while (slot = iterator.nextSlot()) {
slots.push(slot);
}
return slots;
} |
JavaScript | function cutSlotsWithoutBusy(iterator) {
var slot = void 0,
slots = [];
while (slot = iterator.nextSlot()) {
if (slot.available) slots.push(slot);
}
return slots;
} | function cutSlotsWithoutBusy(iterator) {
var slot = void 0,
slots = [];
while (slot = iterator.nextSlot()) {
if (slot.available) slots.push(slot);
}
return slots;
} |
JavaScript | function cutSlotsWithoutStartBusy(iterator) {
var slot = void 0,
slots = [];
// skip unavailable slots from start of day
while ((slot = iterator.nextSlot()) && !slot.available) {}
if (!slot) return slots;
slots.push(slot);
while (slot = iterator.nextSlot()) {
slots.push(slot);
}
return slots;
} | function cutSlotsWithoutStartBusy(iterator) {
var slot = void 0,
slots = [];
// skip unavailable slots from start of day
while ((slot = iterator.nextSlot()) && !slot.available) {}
if (!slot) return slots;
slots.push(slot);
while (slot = iterator.nextSlot()) {
slots.push(slot);
}
return slots;
} |
JavaScript | function cutSlotsWithoutStartFinishBusy(iterator) {
var slots = cutSlotsWithoutStartBusy(iterator);
// skip unavailable slots from end of day
var lastPosition = -1;
for (var i = slots.length - 1; i >= 0; i--) {
if (slots[i].available) {
lastPosition = i;
break;
}
}
return lastPosition < 0 ? [] : slots.slice(0, lastPosition + 1);
} | function cutSlotsWithoutStartFinishBusy(iterator) {
var slots = cutSlotsWithoutStartBusy(iterator);
// skip unavailable slots from end of day
var lastPosition = -1;
for (var i = slots.length - 1; i >= 0; i--) {
if (slots[i].available) {
lastPosition = i;
break;
}
}
return lastPosition < 0 ? [] : slots.slice(0, lastPosition + 1);
} |
JavaScript | function bitsetStrToInt32Array(str, vectorSlotSize) {
str = str.replace(/\./g, '');
vectorSlotSize = vectorSlotSize || defaultVectorSlotSize;
var numberOfTimeUnits = Math.ceil(minutesInDay / vectorSlotSize);
if (str.length !== numberOfTimeUnits) throw Error('string bitset should contain ' + numberOfTimeUnits + ' chars');
var int32Count = numberOfTimeUnits >> 5;
var i = void 0,
bi = void 0,
bs = [];
// fill bitset array
for (i = 0; i < int32Count; ++i) {
bs[i] = 0;
}
for (i = str.length - 1; i >= 0; i--) {
// i - char index: from numberOfTimeUnits - 1 to 0
// bi - byte index: from 0 to 8
bi = numberOfTimeUnits - 1 - i >> 5;
bs[bi] = (bs[bi] << 1 | str[i] === "1") >>> 0;
}
return bs;
} | function bitsetStrToInt32Array(str, vectorSlotSize) {
str = str.replace(/\./g, '');
vectorSlotSize = vectorSlotSize || defaultVectorSlotSize;
var numberOfTimeUnits = Math.ceil(minutesInDay / vectorSlotSize);
if (str.length !== numberOfTimeUnits) throw Error('string bitset should contain ' + numberOfTimeUnits + ' chars');
var int32Count = numberOfTimeUnits >> 5;
var i = void 0,
bi = void 0,
bs = [];
// fill bitset array
for (i = 0; i < int32Count; ++i) {
bs[i] = 0;
}
for (i = str.length - 1; i >= 0; i--) {
// i - char index: from numberOfTimeUnits - 1 to 0
// bi - byte index: from 0 to 8
bi = numberOfTimeUnits - 1 - i >> 5;
bs[bi] = (bs[bi] << 1 | str[i] === "1") >>> 0;
}
return bs;
} |
JavaScript | function combineAdjacentSlots(adjasentTaxonomies, enhanceSlotFn, gcd, treshold, taxonomy) {
var sameTimeStart = taxonomy.adjacentSameTimeStart;
var slots = [];
if (!adjasentTaxonomies[0].slots || adjasentTaxonomies[0].slots.length === 0) {
return [];
}
var startTime = 1440;
var endTime = 0;
adjasentTaxonomies[0].slots.forEach(function (taxSlots) {
if (taxSlots.length === 0) {
return;
}
startTime = Math.min(taxSlots[0].start, startTime);
var taxSlotsCnt = taxSlots.length;
endTime = Math.max(taxSlots[taxSlotsCnt - 1].end, endTime);
});
var step = gcd;
if (sameTimeStart && gcd === 0) {
step = minBy(adjasentTaxonomies, function (t) {
return t.slotDuration;
});
if (taxonomy.duration < step) {
step = taxonomy.duration;
}
}
var time = startTime;
while (time < endTime) {
if (sameTimeStart) {
var adjacentSameTimeSlot = checkAdjacentSameTimeSlot(adjasentTaxonomies, time, step, gcd);
if (adjacentSameTimeSlot.available) {
adjacentSameTimeSlot.start = time;
adjacentSameTimeSlot.duration = taxonomy.duration;
if (enhanceSlotFn) {
adjacentSameTimeSlot = enhanceSlotFn(adjacentSameTimeSlot);
}
slots.push(adjacentSameTimeSlot);
}
time = adjacentSameTimeSlot.available ? time + taxonomy.duration : time + step;
} else {
var adjacentSlot = checkAdjacentSlot(adjasentTaxonomies, { end: time }, 0, gcd, treshold);
adjacentSlot.start = adjacentSlot.available ? adjacentSlot.adjasentStart[0] : time;
adjacentSlot.duration = adjacentSlot.end - time;
if (enhanceSlotFn) {
adjacentSlot = enhanceSlotFn(adjacentSlot);
}
slots.push(adjacentSlot);
//TODO: we can add some option per taxonomy to cut slots by duration of first taxononmy
time = adjacentSlot.end;
}
}
return slots.filter(function (s) {
return s.available;
});
} | function combineAdjacentSlots(adjasentTaxonomies, enhanceSlotFn, gcd, treshold, taxonomy) {
var sameTimeStart = taxonomy.adjacentSameTimeStart;
var slots = [];
if (!adjasentTaxonomies[0].slots || adjasentTaxonomies[0].slots.length === 0) {
return [];
}
var startTime = 1440;
var endTime = 0;
adjasentTaxonomies[0].slots.forEach(function (taxSlots) {
if (taxSlots.length === 0) {
return;
}
startTime = Math.min(taxSlots[0].start, startTime);
var taxSlotsCnt = taxSlots.length;
endTime = Math.max(taxSlots[taxSlotsCnt - 1].end, endTime);
});
var step = gcd;
if (sameTimeStart && gcd === 0) {
step = minBy(adjasentTaxonomies, function (t) {
return t.slotDuration;
});
if (taxonomy.duration < step) {
step = taxonomy.duration;
}
}
var time = startTime;
while (time < endTime) {
if (sameTimeStart) {
var adjacentSameTimeSlot = checkAdjacentSameTimeSlot(adjasentTaxonomies, time, step, gcd);
if (adjacentSameTimeSlot.available) {
adjacentSameTimeSlot.start = time;
adjacentSameTimeSlot.duration = taxonomy.duration;
if (enhanceSlotFn) {
adjacentSameTimeSlot = enhanceSlotFn(adjacentSameTimeSlot);
}
slots.push(adjacentSameTimeSlot);
}
time = adjacentSameTimeSlot.available ? time + taxonomy.duration : time + step;
} else {
var adjacentSlot = checkAdjacentSlot(adjasentTaxonomies, { end: time }, 0, gcd, treshold);
adjacentSlot.start = adjacentSlot.available ? adjacentSlot.adjasentStart[0] : time;
adjacentSlot.duration = adjacentSlot.end - time;
if (enhanceSlotFn) {
adjacentSlot = enhanceSlotFn(adjacentSlot);
}
slots.push(adjacentSlot);
//TODO: we can add some option per taxonomy to cut slots by duration of first taxononmy
time = adjacentSlot.end;
}
}
return slots.filter(function (s) {
return s.available;
});
} |
JavaScript | function findAvailableSlot(slots, adjasentTaxonomies, level, time, gcd, treshold) {
var duration = adjasentTaxonomies[level].slotDuration;
var slotsCnt = gcd === 0 ? 1 : Math.round(duration / gcd);
var start_slot = time;
var end_slot = start_slot + treshold + duration;
var prevSlot;
var slotRangeCheck = function slotRangeCheck(s) {
if (!s.available) {
return false;
}
if (slotsCnt === 1) {
return s.start >= start_slot && s.end <= end_slot;
}
return s.start <= start_slot && s.end > start_slot || s.start < end_slot && s.end >= end_slot || s.start >= start_slot && s.end <= end_slot;
};
var slotsChain = (slots || []).reduce(function (ret, s) {
if (slotRangeCheck(s) && (!prevSlot || prevSlot.end == s.start)) {
prevSlot = s;
ret.push(s);
} else if (ret.length < slotsCnt) {
ret = [];
prevSlot = undefined;
}
return ret;
}, []);
if (slotsChain.length < slotsCnt) {
return false;
}
slotsChain = slotsChain.splice(0, slotsCnt);
return {
start: slotsChain[0].start,
end: slotsChain[slotsCnt - 1].end,
available: true,
duration: adjasentTaxonomies[level].slotDuration
};
} | function findAvailableSlot(slots, adjasentTaxonomies, level, time, gcd, treshold) {
var duration = adjasentTaxonomies[level].slotDuration;
var slotsCnt = gcd === 0 ? 1 : Math.round(duration / gcd);
var start_slot = time;
var end_slot = start_slot + treshold + duration;
var prevSlot;
var slotRangeCheck = function slotRangeCheck(s) {
if (!s.available) {
return false;
}
if (slotsCnt === 1) {
return s.start >= start_slot && s.end <= end_slot;
}
return s.start <= start_slot && s.end > start_slot || s.start < end_slot && s.end >= end_slot || s.start >= start_slot && s.end <= end_slot;
};
var slotsChain = (slots || []).reduce(function (ret, s) {
if (slotRangeCheck(s) && (!prevSlot || prevSlot.end == s.start)) {
prevSlot = s;
ret.push(s);
} else if (ret.length < slotsCnt) {
ret = [];
prevSlot = undefined;
}
return ret;
}, []);
if (slotsChain.length < slotsCnt) {
return false;
}
slotsChain = slotsChain.splice(0, slotsCnt);
return {
start: slotsChain[0].start,
end: slotsChain[slotsCnt - 1].end,
available: true,
duration: adjasentTaxonomies[level].slotDuration
};
} |
JavaScript | function checkAdjacentSlot(adjasentTaxonomies, prevSlot, level, gcd, treshold) {
var time = prevSlot.end;
var adjasentStart = prevSlot.adjasentStart || [];
var slot = void 0;
adjasentTaxonomies[level].slots.forEach(function (resSlots) {
if (slot) {
return false;
}
if (!treshold && (!gcd || gcd == adjasentTaxonomies[level].slotDuration)) {
slot = (resSlots || []).find(function (s) {
return s.start === time && s.available;
});
} else {
slot = findAvailableSlot(resSlots, adjasentTaxonomies, level, time, gcd, treshold);
}
});
if (slot) {
slot.adjasentStart = adjasentStart || [];
slot.adjasentStart.push(slot.start);
if (adjasentTaxonomies.length === level + 1) {
return slot;
} else {
return checkAdjacentSlot(adjasentTaxonomies, slot, level + 1, gcd, treshold);
}
}
// if slot for some taxonomy was disabled we should skip duration of first taxonomy
var startTime = level === 0 ? time : time - adjasentTaxonomies[level - 1].slotDuration;
var endTime = level === 0 ? time + adjasentTaxonomies[0].slotDuration : time;
return {
start: startTime,
end: endTime,
available: false,
duration: adjasentTaxonomies[0].slotDuration
};
} | function checkAdjacentSlot(adjasentTaxonomies, prevSlot, level, gcd, treshold) {
var time = prevSlot.end;
var adjasentStart = prevSlot.adjasentStart || [];
var slot = void 0;
adjasentTaxonomies[level].slots.forEach(function (resSlots) {
if (slot) {
return false;
}
if (!treshold && (!gcd || gcd == adjasentTaxonomies[level].slotDuration)) {
slot = (resSlots || []).find(function (s) {
return s.start === time && s.available;
});
} else {
slot = findAvailableSlot(resSlots, adjasentTaxonomies, level, time, gcd, treshold);
}
});
if (slot) {
slot.adjasentStart = adjasentStart || [];
slot.adjasentStart.push(slot.start);
if (adjasentTaxonomies.length === level + 1) {
return slot;
} else {
return checkAdjacentSlot(adjasentTaxonomies, slot, level + 1, gcd, treshold);
}
}
// if slot for some taxonomy was disabled we should skip duration of first taxonomy
var startTime = level === 0 ? time : time - adjasentTaxonomies[level - 1].slotDuration;
var endTime = level === 0 ? time + adjasentTaxonomies[0].slotDuration : time;
return {
start: startTime,
end: endTime,
available: false,
duration: adjasentTaxonomies[0].slotDuration
};
} |
JavaScript | function toBusySlots(cracSlots, business, taxonomyIDs) {
var resourceIDs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
var scheduleStrategy = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
var daysOff = [];
var excludedResources = [];
var excludedResourcesCountMap = {};
function excludedResource(resource_id, date) {
excludedResourcesCountMap[resource_id] = (excludedResourcesCountMap[resource_id] || 0) + 1;
daysOff.push({ date: date, resource_id: resource_id });
}
var busySlotsResponse = {
taxonomyIDs: taxonomyIDs,
daysOff: daysOff,
excludedResources: excludedResources,
days: map(cracSlots, function (cracSlot) {
var date = cracSlot.date;
var dayBounds;
dayBounds = getDayBoundsFromCracSlot(date, cracSlot);
if (!dayBounds) {
var dayOffDate = isoDateForDayOff(date);
business.resources.forEach(function (rr) {
return excludedResource(rr.id, dayOffDate);
});
return {
date: date,
slots: {
busy: [],
available: false
}
};
} else {
var dayStart = dayBounds.start;
var startTime = dayBounds.start_time;
var dayEnd = dayBounds.end;
var slots = cutSlotsFromCrac(cracSlot, date, dayStart, dayEnd, scheduleStrategy, scheduleStrategy.getSlotSize(business, taxonomyIDs, resourceIDs[0]));
if (cracSlot.excludedResources) {
var _dayOffDate = isoDateForDayOff(date);
cracSlot.excludedResources.forEach(function (rid) {
return excludedResource(rid, _dayOffDate);
});
}
return {
date: date,
start_time: slots.start_time || startTime,
end_time: slots.end_time || dayBounds.end_time,
slots: slots
};
}
})
};
// Post processing of excludedResources
var daysCount = busySlotsResponse.days.length;
for (var resourceId in excludedResourcesCountMap) {
if (Object.prototype.hasOwnProperty.call(excludedResourcesCountMap, resourceId)) {
if (excludedResourcesCountMap[resourceId] >= daysCount) {
excludedResources.push(resourceId);
}
}
}
return busySlotsResponse;
} | function toBusySlots(cracSlots, business, taxonomyIDs) {
var resourceIDs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
var scheduleStrategy = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
var daysOff = [];
var excludedResources = [];
var excludedResourcesCountMap = {};
function excludedResource(resource_id, date) {
excludedResourcesCountMap[resource_id] = (excludedResourcesCountMap[resource_id] || 0) + 1;
daysOff.push({ date: date, resource_id: resource_id });
}
var busySlotsResponse = {
taxonomyIDs: taxonomyIDs,
daysOff: daysOff,
excludedResources: excludedResources,
days: map(cracSlots, function (cracSlot) {
var date = cracSlot.date;
var dayBounds;
dayBounds = getDayBoundsFromCracSlot(date, cracSlot);
if (!dayBounds) {
var dayOffDate = isoDateForDayOff(date);
business.resources.forEach(function (rr) {
return excludedResource(rr.id, dayOffDate);
});
return {
date: date,
slots: {
busy: [],
available: false
}
};
} else {
var dayStart = dayBounds.start;
var startTime = dayBounds.start_time;
var dayEnd = dayBounds.end;
var slots = cutSlotsFromCrac(cracSlot, date, dayStart, dayEnd, scheduleStrategy, scheduleStrategy.getSlotSize(business, taxonomyIDs, resourceIDs[0]));
if (cracSlot.excludedResources) {
var _dayOffDate = isoDateForDayOff(date);
cracSlot.excludedResources.forEach(function (rid) {
return excludedResource(rid, _dayOffDate);
});
}
return {
date: date,
start_time: slots.start_time || startTime,
end_time: slots.end_time || dayBounds.end_time,
slots: slots
};
}
})
};
// Post processing of excludedResources
var daysCount = busySlotsResponse.days.length;
for (var resourceId in excludedResourcesCountMap) {
if (Object.prototype.hasOwnProperty.call(excludedResourcesCountMap, resourceId)) {
if (excludedResourcesCountMap[resourceId] >= daysCount) {
excludedResources.push(resourceId);
}
}
}
return busySlotsResponse;
} |
JavaScript | function checkForParentDiscounts(businessData, taxonomyParentID, time) {
var parentDiscount = {
//discount: 0,
//provider: 'LOCAL'
};
var timeInMinutes = time.hour() * 60 + time.minute();
var t = businessData.business.taxonomies.filter(function (t) {
return t.id === taxonomyParentID;
});
if (t && t[0]) {
if (!parentDiscount.discount && typeof t[0].discounts.regular !== 'undefined') {
t[0].discounts.regular.forEach(function (discount) {
var end = moment$1(discount.start).add(discount.weeklyRepeat, 'weeks');
if (discount.active && (discount.unlimWeeklyRepeat || time.isAfter(discount.start) && time.isBefore(end))) {
for (var day in discount.week) {
discount.week[day].forEach(function (slot) {
if (time.day() === weekDaysMap[day] && timeInMinutes >= slot.start && timeInMinutes <= slot.end) {
parentDiscount = slot;
}
});
}
}
});
} else {
if (!parentDiscount.discount && typeof t[0].taxonomyParentID !== "undefined" && t[0].taxonomyParentID) {
parentDiscount = checkForParentDiscounts(businessData, t[0].taxonomyParentID, time);
}
}
}
return parentDiscount;
} | function checkForParentDiscounts(businessData, taxonomyParentID, time) {
var parentDiscount = {
//discount: 0,
//provider: 'LOCAL'
};
var timeInMinutes = time.hour() * 60 + time.minute();
var t = businessData.business.taxonomies.filter(function (t) {
return t.id === taxonomyParentID;
});
if (t && t[0]) {
if (!parentDiscount.discount && typeof t[0].discounts.regular !== 'undefined') {
t[0].discounts.regular.forEach(function (discount) {
var end = moment$1(discount.start).add(discount.weeklyRepeat, 'weeks');
if (discount.active && (discount.unlimWeeklyRepeat || time.isAfter(discount.start) && time.isBefore(end))) {
for (var day in discount.week) {
discount.week[day].forEach(function (slot) {
if (time.day() === weekDaysMap[day] && timeInMinutes >= slot.start && timeInMinutes <= slot.end) {
parentDiscount = slot;
}
});
}
}
});
} else {
if (!parentDiscount.discount && typeof t[0].taxonomyParentID !== "undefined" && t[0].taxonomyParentID) {
parentDiscount = checkForParentDiscounts(businessData, t[0].taxonomyParentID, time);
}
}
}
return parentDiscount;
} |
JavaScript | function checkForParentDiscountExceptions(businessData, taxonomyParentID, time) {
var parentDiscount = {
//discount: 0,
provider: 'LOCAL'
};
var timeInMinutes = time.hour() * 60 + time.minute();
businessData.business.taxonomies.forEach(function (t) {
if (t.id === taxonomyParentID && typeof t.discounts.exceptions !== 'undefined') {
t.discounts.exceptions.forEach(function (exception) {
var date = moment$1(exception.date);
if (exception.active && time.format("YYYY-MM-DD") === date.format("YYYY-MM-DD")) {
exception.slots.forEach(function (slot) {
if (timeInMinutes >= slot.start && timeInMinutes <= slot.end) {
parentDiscount = slot;
}
});
}
});
//if no discount exception found, check for parent's discount exceptions recursively
if ((typeof parentDiscount.discount === 'undefined' || parentDiscount.discount == null) && typeof service.taxonomyParentID !== "undefined" && service.taxonomyParentID) {
parentDiscount = checkForParentDiscountExceptions(taxonomyParentID, time);
}
return;
}
});
return parentDiscount;
} | function checkForParentDiscountExceptions(businessData, taxonomyParentID, time) {
var parentDiscount = {
//discount: 0,
provider: 'LOCAL'
};
var timeInMinutes = time.hour() * 60 + time.minute();
businessData.business.taxonomies.forEach(function (t) {
if (t.id === taxonomyParentID && typeof t.discounts.exceptions !== 'undefined') {
t.discounts.exceptions.forEach(function (exception) {
var date = moment$1(exception.date);
if (exception.active && time.format("YYYY-MM-DD") === date.format("YYYY-MM-DD")) {
exception.slots.forEach(function (slot) {
if (timeInMinutes >= slot.start && timeInMinutes <= slot.end) {
parentDiscount = slot;
}
});
}
});
//if no discount exception found, check for parent's discount exceptions recursively
if ((typeof parentDiscount.discount === 'undefined' || parentDiscount.discount == null) && typeof service.taxonomyParentID !== "undefined" && service.taxonomyParentID) {
parentDiscount = checkForParentDiscountExceptions(taxonomyParentID, time);
}
return;
}
});
return parentDiscount;
} |
JavaScript | function resourceTaxonomyDuration(businessWorker, businessTaxonomy) {
var duration = businessTaxonomy.duration;
if (businessWorker.taxonomyLevels && businessWorker.taxonomyLevels.length > 0) {
var taxonomyLevel = find(businessWorker.taxonomyLevels, { id: businessTaxonomy.id });
if (taxonomyLevel) {
var additionalDuration = find(businessTaxonomy.additionalDurations, { level: taxonomyLevel.level });
if (additionalDuration && additionalDuration.duration) {
duration = additionalDuration.duration;
}
}
}
return duration;
} | function resourceTaxonomyDuration(businessWorker, businessTaxonomy) {
var duration = businessTaxonomy.duration;
if (businessWorker.taxonomyLevels && businessWorker.taxonomyLevels.length > 0) {
var taxonomyLevel = find(businessWorker.taxonomyLevels, { id: businessTaxonomy.id });
if (taxonomyLevel) {
var additionalDuration = find(businessTaxonomy.additionalDurations, { level: taxonomyLevel.level });
if (additionalDuration && additionalDuration.duration) {
duration = additionalDuration.duration;
}
}
}
return duration;
} |
JavaScript | function calcResourceSlots(resourceVector) {
var resourceSlots = [];
for (var i = 0; i < resourceVector.length; i++) {
if (resourceVector[i]) {
resourceSlots.push({ time: i * SLOT_SIZE$1, duration: SLOT_SIZE$1, space_left: 1, discount: 10 });
}
}
return resourceSlots;
} | function calcResourceSlots(resourceVector) {
var resourceSlots = [];
for (var i = 0; i < resourceVector.length; i++) {
if (resourceVector[i]) {
resourceSlots.push({ time: i * SLOT_SIZE$1, duration: SLOT_SIZE$1, space_left: 1, discount: 10 });
}
}
return resourceSlots;
} |
JavaScript | function calExcludedResource(resources, excludedHash) {
var excludedResources = [];
resources.forEach(function (rId) {
if (!excludedHash[rId]) {
excludedResources.push(rId);
}
});
return excludedResources;
} | function calExcludedResource(resources, excludedHash) {
var excludedResources = [];
resources.forEach(function (rId) {
if (!excludedHash[rId]) {
excludedResources.push(rId);
}
});
return excludedResources;
} |
JavaScript | function initFreeVector() {
var set = [];
for (var i = 0; i < VECTOR_SIZE; i++) {
set[i] = 1;
}
return set;
} | function initFreeVector() {
var set = [];
for (var i = 0; i < VECTOR_SIZE; i++) {
set[i] = 1;
}
return set;
} |
JavaScript | function initBusyVector() {
var set = [];
for (var i = 0; i < VECTOR_SIZE; i++) {
set[i] = 0;
}
return set;
} | function initBusyVector() {
var set = [];
for (var i = 0; i < VECTOR_SIZE; i++) {
set[i] = 0;
}
return set;
} |
JavaScript | function toBusySlots$1(cracSlots, business, taxonomyIDs) {
var resourceIds = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
var businessTimetable = business.general_info.timetable;
var daysOff = [];
var excludedResources = [];
var excludedResourcesCountMap = {};
var maxSlotDuration = -1;
var resourceTimetables = [];
var resourceEvenOddTimeTable = [];
var timetableType = business.backoffice_configuration && business.backoffice_configuration.resourceTimetableType ? business.backoffice_configuration.resourceTimetableType : 'DEFAULT';
business.resources.forEach(function (rr) {
if (resourceIds.indexOf(rr.id) < 0) {
return;
}
if (timetableType == 'EVENODD') {
resourceEvenOddTimeTable.push(rr.evenOddTimetable);
} else {
resourceTimetables.push(rr.timetable && rr.timetable.active === true ? rr.timetable : businessTimetable);
}
});
if (resourceTimetables.length < 1) {
resourceTimetables.push(businessTimetable);
}
if (taxonomyIDs && taxonomyIDs.length) {
var taxonomies = filter(business.taxonomies, function (tt) {
return taxonomyIDs.indexOf(String(tt.id)) >= 0;
});
var maxTaxonomyDuration = max(taxonomies, 'duration');
if (maxTaxonomyDuration) {
maxSlotDuration = maxTaxonomyDuration.duration;
}
}
// const now = moment();
function excludedResource(resource_id, date) {
excludedResourcesCountMap[resource_id] = (excludedResourcesCountMap[resource_id] || 0) + 1;
daysOff.push({ date: date, resource_id: resource_id });
}
var busySlotsResponse = {
taxonomyId: taxonomyIDs && taxonomyIDs[0],
slots_size: maxSlotDuration > 0 ? maxSlotDuration : 0,
maxSlotCapacity: 1,
daysOff: daysOff,
excludedResources: excludedResources,
days: map(cracSlots, function (cracSlot) {
var date = cracSlot.date;
var dayBounds;
//dayBounds = getDayBoundsFromAllTimetables(date, resourceTimetables,resourceEvenOddTimeTable,timetableType);
dayBounds = getDayBoundsFromCracSlot$1(date, cracSlot, business.general_info);
if (!dayBounds) {
var dayOffDate = isoDateForDayOff$1(date);
business.resources.forEach(function (rr) {
return excludedResource(rr.id, dayOffDate);
});
return {
date: date,
slots: {
busy: [],
available: false
}
};
} else {
var dayStart = dayBounds.start;
var startTime = dayBounds.start_time;
var dayEnd = dayBounds.end;
var slots = getCrunchSlotsFromCrac(cracSlot, date, dayStart, dayEnd, maxSlotDuration);
if (cracSlot.excludedResources) {
var _dayOffDate = isoDateForDayOff$1(date);
cracSlot.excludedResources.forEach(function (rid) {
return excludedResource(rid, _dayOffDate);
});
}
return {
date: date,
start_time: slots.start_time || startTime,
end_time: slots.end_time || dayBounds.end_time,
slots: slots
};
}
})
};
// Post processing of excludedResources
var daysCount = busySlotsResponse.days.length;
for (var resourceId in excludedResourcesCountMap) {
if (Object.prototype.hasOwnProperty.call(excludedResourcesCountMap, resourceId)) {
if (excludedResourcesCountMap[resourceId] >= daysCount) {
excludedResources.push(resourceId);
}
}
}
return busySlotsResponse;
} | function toBusySlots$1(cracSlots, business, taxonomyIDs) {
var resourceIds = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
var businessTimetable = business.general_info.timetable;
var daysOff = [];
var excludedResources = [];
var excludedResourcesCountMap = {};
var maxSlotDuration = -1;
var resourceTimetables = [];
var resourceEvenOddTimeTable = [];
var timetableType = business.backoffice_configuration && business.backoffice_configuration.resourceTimetableType ? business.backoffice_configuration.resourceTimetableType : 'DEFAULT';
business.resources.forEach(function (rr) {
if (resourceIds.indexOf(rr.id) < 0) {
return;
}
if (timetableType == 'EVENODD') {
resourceEvenOddTimeTable.push(rr.evenOddTimetable);
} else {
resourceTimetables.push(rr.timetable && rr.timetable.active === true ? rr.timetable : businessTimetable);
}
});
if (resourceTimetables.length < 1) {
resourceTimetables.push(businessTimetable);
}
if (taxonomyIDs && taxonomyIDs.length) {
var taxonomies = filter(business.taxonomies, function (tt) {
return taxonomyIDs.indexOf(String(tt.id)) >= 0;
});
var maxTaxonomyDuration = max(taxonomies, 'duration');
if (maxTaxonomyDuration) {
maxSlotDuration = maxTaxonomyDuration.duration;
}
}
// const now = moment();
function excludedResource(resource_id, date) {
excludedResourcesCountMap[resource_id] = (excludedResourcesCountMap[resource_id] || 0) + 1;
daysOff.push({ date: date, resource_id: resource_id });
}
var busySlotsResponse = {
taxonomyId: taxonomyIDs && taxonomyIDs[0],
slots_size: maxSlotDuration > 0 ? maxSlotDuration : 0,
maxSlotCapacity: 1,
daysOff: daysOff,
excludedResources: excludedResources,
days: map(cracSlots, function (cracSlot) {
var date = cracSlot.date;
var dayBounds;
//dayBounds = getDayBoundsFromAllTimetables(date, resourceTimetables,resourceEvenOddTimeTable,timetableType);
dayBounds = getDayBoundsFromCracSlot$1(date, cracSlot, business.general_info);
if (!dayBounds) {
var dayOffDate = isoDateForDayOff$1(date);
business.resources.forEach(function (rr) {
return excludedResource(rr.id, dayOffDate);
});
return {
date: date,
slots: {
busy: [],
available: false
}
};
} else {
var dayStart = dayBounds.start;
var startTime = dayBounds.start_time;
var dayEnd = dayBounds.end;
var slots = getCrunchSlotsFromCrac(cracSlot, date, dayStart, dayEnd, maxSlotDuration);
if (cracSlot.excludedResources) {
var _dayOffDate = isoDateForDayOff$1(date);
cracSlot.excludedResources.forEach(function (rid) {
return excludedResource(rid, _dayOffDate);
});
}
return {
date: date,
start_time: slots.start_time || startTime,
end_time: slots.end_time || dayBounds.end_time,
slots: slots
};
}
})
};
// Post processing of excludedResources
var daysCount = busySlotsResponse.days.length;
for (var resourceId in excludedResourcesCountMap) {
if (Object.prototype.hasOwnProperty.call(excludedResourcesCountMap, resourceId)) {
if (excludedResourcesCountMap[resourceId] >= daysCount) {
excludedResources.push(resourceId);
}
}
}
return busySlotsResponse;
} |
JavaScript | function isDateForbidden(widgetConfiguration, date, ignoreStartDate) {
if (ignoreStartDate === null || typeof ignoreStartDate == 'undefined') {
ignoreStartDate = false;
}
if (widgetConfiguration && widgetConfiguration.bookableDateRanges && widgetConfiguration.bookableDateRanges.enabled) {
var dateMoment = moment(date),
dateAvailable = true,
start = widgetConfiguration.bookableDateRanges.start,
end = widgetConfiguration.bookableDateRanges.end;
if (start && end && !ignoreStartDate) {
dateAvailable = dateMoment.isAfter(moment(start).startOf('day')) && dateMoment.isBefore(moment(end).endOf('day'));
}
else if (start && !ignoreStartDate) {
dateAvailable = dateMoment.isAfter(moment(start).startOf('day'));
}
else if (end) {
dateAvailable = dateMoment.isBefore(moment(end).endOf('day'));
}
return !dateAvailable;
}
//bookable weeks calculation
if (widgetConfiguration.bookableMonthsCount > 0 && widgetConfiguration.bookableMonthsCount < 1) {
var weeks = Math.round(widgetConfiguration.bookableMonthsCount / 0.23);
return moment().add(weeks, 'weeks').isBefore(date)
}
return !!(widgetConfiguration && widgetConfiguration.bookableMonthsCount > 0 && moment().add('M', widgetConfiguration.bookableMonthsCount - 1).endOf('M').isBefore(date));
} | function isDateForbidden(widgetConfiguration, date, ignoreStartDate) {
if (ignoreStartDate === null || typeof ignoreStartDate == 'undefined') {
ignoreStartDate = false;
}
if (widgetConfiguration && widgetConfiguration.bookableDateRanges && widgetConfiguration.bookableDateRanges.enabled) {
var dateMoment = moment(date),
dateAvailable = true,
start = widgetConfiguration.bookableDateRanges.start,
end = widgetConfiguration.bookableDateRanges.end;
if (start && end && !ignoreStartDate) {
dateAvailable = dateMoment.isAfter(moment(start).startOf('day')) && dateMoment.isBefore(moment(end).endOf('day'));
}
else if (start && !ignoreStartDate) {
dateAvailable = dateMoment.isAfter(moment(start).startOf('day'));
}
else if (end) {
dateAvailable = dateMoment.isBefore(moment(end).endOf('day'));
}
return !dateAvailable;
}
//bookable weeks calculation
if (widgetConfiguration.bookableMonthsCount > 0 && widgetConfiguration.bookableMonthsCount < 1) {
var weeks = Math.round(widgetConfiguration.bookableMonthsCount / 0.23);
return moment().add(weeks, 'weeks').isBefore(date)
}
return !!(widgetConfiguration && widgetConfiguration.bookableMonthsCount > 0 && moment().add('M', widgetConfiguration.bookableMonthsCount - 1).endOf('M').isBefore(date));
} |
JavaScript | function alignmentBusySlotsByTaxonomyDuration(startDate, taxonomyDuration, slotSize, busySlots) {
_.each(busySlots, function(busySlot) {
busySlot.duration = taxonomyDuration;
});
var duration = slotSize || taxonomyDuration;
_.each(busySlots, function(busySlot) {
var busyTimeMin = moment.utc(busySlot.time).diff(moment.utc(startDate), 'minute');
var alignBusyTimeMin = Math.floor(busyTimeMin / duration) * duration;
if (busyTimeMin !== alignBusyTimeMin) {
var alignBusySlotTime = moment.utc(startDate).add(alignBusyTimeMin, 'minutes').toISOString();
var alignEndBusyTimeMin = Math.ceil((busyTimeMin+busySlot.duration) / duration) * duration;
busySlot.time = alignBusySlotTime;
busySlot.duration = alignEndBusyTimeMin - alignBusyTimeMin;
}
});
} | function alignmentBusySlotsByTaxonomyDuration(startDate, taxonomyDuration, slotSize, busySlots) {
_.each(busySlots, function(busySlot) {
busySlot.duration = taxonomyDuration;
});
var duration = slotSize || taxonomyDuration;
_.each(busySlots, function(busySlot) {
var busyTimeMin = moment.utc(busySlot.time).diff(moment.utc(startDate), 'minute');
var alignBusyTimeMin = Math.floor(busyTimeMin / duration) * duration;
if (busyTimeMin !== alignBusyTimeMin) {
var alignBusySlotTime = moment.utc(startDate).add(alignBusyTimeMin, 'minutes').toISOString();
var alignEndBusyTimeMin = Math.ceil((busyTimeMin+busySlot.duration) / duration) * duration;
busySlot.time = alignBusySlotTime;
busySlot.duration = alignEndBusyTimeMin - alignBusyTimeMin;
}
});
} |
JavaScript | function toBusySlots(cracSlots, business, taxonomyIDs, resourceIDs = [], scheduleStrategy = null) {
const daysOff = [];
const excludedResources = [];
const excludedResourcesCountMap = {};
function excludedResource(resource_id, date) {
excludedResourcesCountMap[resource_id] = (excludedResourcesCountMap[resource_id] || 0) + 1;
daysOff.push({ date, resource_id });
}
const busySlotsResponse = {
taxonomyIDs,
daysOff,
excludedResources,
days: _.map(cracSlots, function(cracSlot) {
const { date } = cracSlot;
var dayBounds;
dayBounds = getDayBoundsFromCracSlot(date, cracSlot);
if (!dayBounds) {
const dayOffDate = isoDateForDayOff(date);
business.resources.forEach((rr) => excludedResource(rr.id, dayOffDate));
return {
date,
slots: {
busy: [],
available: false
}
};
} else {
let dayStart = dayBounds.start;
let startTime = dayBounds.start_time;
const dayEnd = dayBounds.end;
const slots = cutSlotsFromCrac(cracSlot, date, dayStart, dayEnd, scheduleStrategy,
scheduleStrategy.getSlotSize(business, taxonomyIDs, resourceIDs[0]));
if (cracSlot.excludedResources) {
const dayOffDate = isoDateForDayOff(date);
cracSlot.excludedResources.forEach((rid) => excludedResource(rid, dayOffDate));
}
return {
date,
start_time: slots.start_time || startTime,
end_time: slots.end_time || dayBounds.end_time,
slots,
};
}
}),
};
// Post processing of excludedResources
const daysCount = busySlotsResponse.days.length;
for (const resourceId in excludedResourcesCountMap) {
if (Object.prototype.hasOwnProperty.call(excludedResourcesCountMap, resourceId)) {
if (excludedResourcesCountMap[resourceId] >= daysCount) {
excludedResources.push(resourceId);
}
}
}
return busySlotsResponse;
} | function toBusySlots(cracSlots, business, taxonomyIDs, resourceIDs = [], scheduleStrategy = null) {
const daysOff = [];
const excludedResources = [];
const excludedResourcesCountMap = {};
function excludedResource(resource_id, date) {
excludedResourcesCountMap[resource_id] = (excludedResourcesCountMap[resource_id] || 0) + 1;
daysOff.push({ date, resource_id });
}
const busySlotsResponse = {
taxonomyIDs,
daysOff,
excludedResources,
days: _.map(cracSlots, function(cracSlot) {
const { date } = cracSlot;
var dayBounds;
dayBounds = getDayBoundsFromCracSlot(date, cracSlot);
if (!dayBounds) {
const dayOffDate = isoDateForDayOff(date);
business.resources.forEach((rr) => excludedResource(rr.id, dayOffDate));
return {
date,
slots: {
busy: [],
available: false
}
};
} else {
let dayStart = dayBounds.start;
let startTime = dayBounds.start_time;
const dayEnd = dayBounds.end;
const slots = cutSlotsFromCrac(cracSlot, date, dayStart, dayEnd, scheduleStrategy,
scheduleStrategy.getSlotSize(business, taxonomyIDs, resourceIDs[0]));
if (cracSlot.excludedResources) {
const dayOffDate = isoDateForDayOff(date);
cracSlot.excludedResources.forEach((rid) => excludedResource(rid, dayOffDate));
}
return {
date,
start_time: slots.start_time || startTime,
end_time: slots.end_time || dayBounds.end_time,
slots,
};
}
}),
};
// Post processing of excludedResources
const daysCount = busySlotsResponse.days.length;
for (const resourceId in excludedResourcesCountMap) {
if (Object.prototype.hasOwnProperty.call(excludedResourcesCountMap, resourceId)) {
if (excludedResourcesCountMap[resourceId] >= daysCount) {
excludedResources.push(resourceId);
}
}
}
return busySlotsResponse;
} |
JavaScript | cutSlots(resourceID, duration, slotSize, enhanceSlotFn = null) {
if(this.isDayBefore()){
return [];
}
const iterator = this.getSlotsIterator(resourceID, duration, slotSize, enhanceSlotFn);
const _cutSlots = this.isThisDay() ? this.cutSlotsThisDayFn : this.cutSlotsFn;
return iterator ? _cutSlots(iterator) : null;
} | cutSlots(resourceID, duration, slotSize, enhanceSlotFn = null) {
if(this.isDayBefore()){
return [];
}
const iterator = this.getSlotsIterator(resourceID, duration, slotSize, enhanceSlotFn);
const _cutSlots = this.isThisDay() ? this.cutSlotsThisDayFn : this.cutSlotsFn;
return iterator ? _cutSlots(iterator) : null;
} |
JavaScript | function combineAdjacentSlots( adjasentTaxonomies, enhanceSlotFn, gcd, treshold, taxonomy ) {
var sameTimeStart = taxonomy.adjacentSameTimeStart;
const slots = [];
if ( !adjasentTaxonomies[ 0 ].slots || adjasentTaxonomies[ 0 ].slots.length === 0 ) {
return [];
}
let startTime = 1440;
let endTime = 0;
adjasentTaxonomies[ 0 ].slots.forEach( ( taxSlots ) => {
if ( taxSlots.length === 0 ) {
return;
}
startTime = Math.min( taxSlots[ 0 ].start, startTime )
const taxSlotsCnt = taxSlots.length;
endTime = Math.max( taxSlots[ taxSlotsCnt - 1 ].end, endTime );
} );
let step = gcd;
if(sameTimeStart && gcd === 0 ){
step = _.minBy(adjasentTaxonomies, t=>t.slotDuration);
if(taxonomy.duration < step){
step = taxonomy.duration;
}
}
let time = startTime;
while ( time < endTime ) {
if(sameTimeStart){
var adjacentSameTimeSlot = checkAdjacentSameTimeSlot(adjasentTaxonomies, time, step, gcd);
if(adjacentSameTimeSlot.available){
adjacentSameTimeSlot.start = time;
adjacentSameTimeSlot.duration = taxonomy.duration;
if ( enhanceSlotFn ) {
adjacentSameTimeSlot = enhanceSlotFn( adjacentSameTimeSlot );
}
slots.push( adjacentSameTimeSlot );
}
time = adjacentSameTimeSlot.available ? time + taxonomy.duration : time + step;
} else {
let adjacentSlot = checkAdjacentSlot( adjasentTaxonomies, { end:time }, 0, gcd, treshold );
adjacentSlot.start = adjacentSlot.available ? adjacentSlot.adjasentStart[ 0 ] : time;
adjacentSlot.duration = adjacentSlot.end - time;
if ( enhanceSlotFn ) {
adjacentSlot = enhanceSlotFn( adjacentSlot );
}
slots.push( adjacentSlot );
//TODO: we can add some option per taxonomy to cut slots by duration of first taxononmy
time = adjacentSlot.end;
}
}
return slots.filter( function ( s ) { return s.available });
} | function combineAdjacentSlots( adjasentTaxonomies, enhanceSlotFn, gcd, treshold, taxonomy ) {
var sameTimeStart = taxonomy.adjacentSameTimeStart;
const slots = [];
if ( !adjasentTaxonomies[ 0 ].slots || adjasentTaxonomies[ 0 ].slots.length === 0 ) {
return [];
}
let startTime = 1440;
let endTime = 0;
adjasentTaxonomies[ 0 ].slots.forEach( ( taxSlots ) => {
if ( taxSlots.length === 0 ) {
return;
}
startTime = Math.min( taxSlots[ 0 ].start, startTime )
const taxSlotsCnt = taxSlots.length;
endTime = Math.max( taxSlots[ taxSlotsCnt - 1 ].end, endTime );
} );
let step = gcd;
if(sameTimeStart && gcd === 0 ){
step = _.minBy(adjasentTaxonomies, t=>t.slotDuration);
if(taxonomy.duration < step){
step = taxonomy.duration;
}
}
let time = startTime;
while ( time < endTime ) {
if(sameTimeStart){
var adjacentSameTimeSlot = checkAdjacentSameTimeSlot(adjasentTaxonomies, time, step, gcd);
if(adjacentSameTimeSlot.available){
adjacentSameTimeSlot.start = time;
adjacentSameTimeSlot.duration = taxonomy.duration;
if ( enhanceSlotFn ) {
adjacentSameTimeSlot = enhanceSlotFn( adjacentSameTimeSlot );
}
slots.push( adjacentSameTimeSlot );
}
time = adjacentSameTimeSlot.available ? time + taxonomy.duration : time + step;
} else {
let adjacentSlot = checkAdjacentSlot( adjasentTaxonomies, { end:time }, 0, gcd, treshold );
adjacentSlot.start = adjacentSlot.available ? adjacentSlot.adjasentStart[ 0 ] : time;
adjacentSlot.duration = adjacentSlot.end - time;
if ( enhanceSlotFn ) {
adjacentSlot = enhanceSlotFn( adjacentSlot );
}
slots.push( adjacentSlot );
//TODO: we can add some option per taxonomy to cut slots by duration of first taxononmy
time = adjacentSlot.end;
}
}
return slots.filter( function ( s ) { return s.available });
} |
JavaScript | function findAvailableSlot( slots, adjasentTaxonomies, level, time, gcd, treshold ) {
var duration = adjasentTaxonomies[ level ].slotDuration;
var slotsCnt = gcd === 0 ? 1 : Math.round(duration / gcd);
var start_slot = time;
var end_slot = start_slot + treshold + duration;
var prevSlot;
var slotRangeCheck = function(s) {
if(!s.available){
return false;
}
if (slotsCnt === 1) {
return s.start >= start_slot && s.end<=end_slot;
}
return (s.start <= start_slot && s.end > start_slot)
|| (s.start < end_slot && s.end >= end_slot)
|| (s.start >= start_slot && s.end <= end_slot)
}
var slotsChain = (slots || []).reduce( function ( ret, s ) {
if ( slotRangeCheck(s) &&
( !prevSlot || prevSlot.end == s.start ) ) {
prevSlot = s;
ret.push( s );
} else if ( ret.length < slotsCnt ) {
ret = [];
prevSlot = undefined;
}
return ret;
}, [] );
if ( slotsChain.length < slotsCnt ) {
return false;
}
slotsChain = slotsChain.splice( 0, slotsCnt );
return {
start: slotsChain[ 0 ].start,
end: slotsChain[ slotsCnt - 1 ].end,
available: true,
duration: adjasentTaxonomies[ level ].slotDuration,
}
} | function findAvailableSlot( slots, adjasentTaxonomies, level, time, gcd, treshold ) {
var duration = adjasentTaxonomies[ level ].slotDuration;
var slotsCnt = gcd === 0 ? 1 : Math.round(duration / gcd);
var start_slot = time;
var end_slot = start_slot + treshold + duration;
var prevSlot;
var slotRangeCheck = function(s) {
if(!s.available){
return false;
}
if (slotsCnt === 1) {
return s.start >= start_slot && s.end<=end_slot;
}
return (s.start <= start_slot && s.end > start_slot)
|| (s.start < end_slot && s.end >= end_slot)
|| (s.start >= start_slot && s.end <= end_slot)
}
var slotsChain = (slots || []).reduce( function ( ret, s ) {
if ( slotRangeCheck(s) &&
( !prevSlot || prevSlot.end == s.start ) ) {
prevSlot = s;
ret.push( s );
} else if ( ret.length < slotsCnt ) {
ret = [];
prevSlot = undefined;
}
return ret;
}, [] );
if ( slotsChain.length < slotsCnt ) {
return false;
}
slotsChain = slotsChain.splice( 0, slotsCnt );
return {
start: slotsChain[ 0 ].start,
end: slotsChain[ slotsCnt - 1 ].end,
available: true,
duration: adjasentTaxonomies[ level ].slotDuration,
}
} |
JavaScript | function checkAdjacentSlot( adjasentTaxonomies, prevSlot, level, gcd, treshold ) {
let time = prevSlot.end;
let adjasentStart = prevSlot.adjasentStart || [];
let slot;
adjasentTaxonomies[ level ].slots.forEach( ( resSlots ) => {
if ( slot ) {
return false;
}
if ( !treshold && ( !gcd || gcd == adjasentTaxonomies[ level ].slotDuration ) ) {
slot = (resSlots || []).find( function ( s ) {
return s.start === time && s.available;
} );
} else {
slot = findAvailableSlot( resSlots, adjasentTaxonomies, level, time, gcd, treshold );
}
} );
if ( slot ) {
slot.adjasentStart = adjasentStart || [];
slot.adjasentStart.push( slot.start );
if ( adjasentTaxonomies.length === ( level + 1 ) ) {
return slot;
} else {
return checkAdjacentSlot( adjasentTaxonomies, slot, level + 1, gcd, treshold );
}
}
// if slot for some taxonomy was disabled we should skip duration of first taxonomy
let startTime = level === 0 ? time : time - adjasentTaxonomies[ level - 1 ].slotDuration;
let endTime = level === 0 ? time + adjasentTaxonomies[ 0 ].slotDuration : time;
return {
start: startTime,
end: endTime,
available: false,
duration: adjasentTaxonomies[ 0 ].slotDuration,
};
} | function checkAdjacentSlot( adjasentTaxonomies, prevSlot, level, gcd, treshold ) {
let time = prevSlot.end;
let adjasentStart = prevSlot.adjasentStart || [];
let slot;
adjasentTaxonomies[ level ].slots.forEach( ( resSlots ) => {
if ( slot ) {
return false;
}
if ( !treshold && ( !gcd || gcd == adjasentTaxonomies[ level ].slotDuration ) ) {
slot = (resSlots || []).find( function ( s ) {
return s.start === time && s.available;
} );
} else {
slot = findAvailableSlot( resSlots, adjasentTaxonomies, level, time, gcd, treshold );
}
} );
if ( slot ) {
slot.adjasentStart = adjasentStart || [];
slot.adjasentStart.push( slot.start );
if ( adjasentTaxonomies.length === ( level + 1 ) ) {
return slot;
} else {
return checkAdjacentSlot( adjasentTaxonomies, slot, level + 1, gcd, treshold );
}
}
// if slot for some taxonomy was disabled we should skip duration of first taxonomy
let startTime = level === 0 ? time : time - adjasentTaxonomies[ level - 1 ].slotDuration;
let endTime = level === 0 ? time + adjasentTaxonomies[ 0 ].slotDuration : time;
return {
start: startTime,
end: endTime,
available: false,
duration: adjasentTaxonomies[ 0 ].slotDuration,
};
} |
JavaScript | function resourceTaxonomyDuration(businessWorker, businessTaxonomy) {
var duration = businessTaxonomy.duration;
if (businessWorker.taxonomyLevels && businessWorker.taxonomyLevels.length > 0) {
var taxonomyLevel = _.find(businessWorker.taxonomyLevels, { id: businessTaxonomy.id });
if (taxonomyLevel) {
var additionalDuration = _.find(businessTaxonomy.additionalDurations, { level: taxonomyLevel.level });
if (additionalDuration && additionalDuration.duration) {
duration = additionalDuration.duration;
}
}
}
return duration;
} | function resourceTaxonomyDuration(businessWorker, businessTaxonomy) {
var duration = businessTaxonomy.duration;
if (businessWorker.taxonomyLevels && businessWorker.taxonomyLevels.length > 0) {
var taxonomyLevel = _.find(businessWorker.taxonomyLevels, { id: businessTaxonomy.id });
if (taxonomyLevel) {
var additionalDuration = _.find(businessTaxonomy.additionalDurations, { level: taxonomyLevel.level });
if (additionalDuration && additionalDuration.duration) {
duration = additionalDuration.duration;
}
}
}
return duration;
} |
JavaScript | function calcResourceSlots(resourceVector) {
var resourceSlots = [];
for (var i = 0; i< resourceVector.length ; i++){
if (resourceVector[i]){
resourceSlots.push({ time: i*SLOT_SIZE, duration: SLOT_SIZE , space_left: 1 ,discount:10});
}
}
return resourceSlots;
} | function calcResourceSlots(resourceVector) {
var resourceSlots = [];
for (var i = 0; i< resourceVector.length ; i++){
if (resourceVector[i]){
resourceSlots.push({ time: i*SLOT_SIZE, duration: SLOT_SIZE , space_left: 1 ,discount:10});
}
}
return resourceSlots;
} |
JavaScript | function calExcludedResource(resources,excludedHash) {
var excludedResources = [];
resources.forEach(function(rId){
if (!excludedHash[rId]){
excludedResources.push(rId)
}
})
return excludedResources;
} | function calExcludedResource(resources,excludedHash) {
var excludedResources = [];
resources.forEach(function(rId){
if (!excludedHash[rId]){
excludedResources.push(rId)
}
})
return excludedResources;
} |
JavaScript | function initFreeVector() {
var set = [];
for (var i = 0; i < VECTOR_SIZE; i++) {
set[i] = 1;
}
return set;
} | function initFreeVector() {
var set = [];
for (var i = 0; i < VECTOR_SIZE; i++) {
set[i] = 1;
}
return set;
} |
JavaScript | function initBusyVector() {
var set = [];
for (var i = 0; i < VECTOR_SIZE; i++) {
set[i] = 0;
}
return set;
} | function initBusyVector() {
var set = [];
for (var i = 0; i < VECTOR_SIZE; i++) {
set[i] = 0;
}
return set;
} |
JavaScript | function toBusySlots(cracSlots, business, taxonomyIDs, resourceIds = []) {
const businessTimetable = business.general_info.timetable;
const daysOff = [];
const excludedResources = [];
const excludedResourcesCountMap = {};
let maxSlotDuration = -1;
const resourceTimetables = [];
const resourceEvenOddTimeTable = [];
const timetableType = business.backoffice_configuration && business.backoffice_configuration.resourceTimetableType ? business.backoffice_configuration.resourceTimetableType : 'DEFAULT';
business.resources.forEach(rr => {
if (resourceIds.indexOf(rr.id) < 0) {
return;
}
if (timetableType == 'EVENODD'){
resourceEvenOddTimeTable.push(rr.evenOddTimetable);
} else {
resourceTimetables.push(rr.timetable && rr.timetable.active === true ? rr.timetable : businessTimetable);
}
});
if (resourceTimetables.length < 1) {
resourceTimetables.push(businessTimetable);
}
if (taxonomyIDs && taxonomyIDs.length) {
const taxonomies = _.filter(
business.taxonomies,
(tt) => taxonomyIDs.indexOf(String(tt.id)) >= 0
);
const maxTaxonomyDuration = _.max(taxonomies, 'duration');
if (maxTaxonomyDuration) {
maxSlotDuration = maxTaxonomyDuration.duration;
}
}
// const now = moment();
function excludedResource(resource_id, date) {
excludedResourcesCountMap[resource_id] = (excludedResourcesCountMap[resource_id] || 0) + 1;
daysOff.push({ date, resource_id });
}
const busySlotsResponse = {
taxonomyId: taxonomyIDs && taxonomyIDs[0],
slots_size: maxSlotDuration > 0 ? maxSlotDuration : 0,
maxSlotCapacity: 1,
daysOff,
excludedResources,
days: _.map(cracSlots, function(cracSlot) {
const { date } = cracSlot;
var dayBounds;
//dayBounds = getDayBoundsFromAllTimetables(date, resourceTimetables,resourceEvenOddTimeTable,timetableType);
dayBounds = getDayBoundsFromCracSlot(date,cracSlot,business.general_info);
if (!dayBounds) {
const dayOffDate = isoDateForDayOff(date);
business.resources.forEach((rr) => excludedResource(rr.id, dayOffDate));
return {
date,
slots: {
busy: [],
available: false
}
};
} else {
let dayStart = dayBounds.start;
let startTime = dayBounds.start_time;
const dayEnd = dayBounds.end;
const slots = getCrunchSlotsFromCrac(cracSlot, date, dayStart, dayEnd, maxSlotDuration);
if (cracSlot.excludedResources) {
const dayOffDate = isoDateForDayOff(date);
cracSlot.excludedResources.forEach((rid) => excludedResource(rid, dayOffDate));
}
return {
date,
start_time: slots.start_time || startTime,
end_time: slots.end_time || dayBounds.end_time,
slots,
};
}
}),
};
// Post processing of excludedResources
const daysCount = busySlotsResponse.days.length;
for (const resourceId in excludedResourcesCountMap) {
if (Object.prototype.hasOwnProperty.call(excludedResourcesCountMap, resourceId)) {
if (excludedResourcesCountMap[resourceId] >= daysCount) {
excludedResources.push(resourceId);
}
}
}
return busySlotsResponse;
} | function toBusySlots(cracSlots, business, taxonomyIDs, resourceIds = []) {
const businessTimetable = business.general_info.timetable;
const daysOff = [];
const excludedResources = [];
const excludedResourcesCountMap = {};
let maxSlotDuration = -1;
const resourceTimetables = [];
const resourceEvenOddTimeTable = [];
const timetableType = business.backoffice_configuration && business.backoffice_configuration.resourceTimetableType ? business.backoffice_configuration.resourceTimetableType : 'DEFAULT';
business.resources.forEach(rr => {
if (resourceIds.indexOf(rr.id) < 0) {
return;
}
if (timetableType == 'EVENODD'){
resourceEvenOddTimeTable.push(rr.evenOddTimetable);
} else {
resourceTimetables.push(rr.timetable && rr.timetable.active === true ? rr.timetable : businessTimetable);
}
});
if (resourceTimetables.length < 1) {
resourceTimetables.push(businessTimetable);
}
if (taxonomyIDs && taxonomyIDs.length) {
const taxonomies = _.filter(
business.taxonomies,
(tt) => taxonomyIDs.indexOf(String(tt.id)) >= 0
);
const maxTaxonomyDuration = _.max(taxonomies, 'duration');
if (maxTaxonomyDuration) {
maxSlotDuration = maxTaxonomyDuration.duration;
}
}
// const now = moment();
function excludedResource(resource_id, date) {
excludedResourcesCountMap[resource_id] = (excludedResourcesCountMap[resource_id] || 0) + 1;
daysOff.push({ date, resource_id });
}
const busySlotsResponse = {
taxonomyId: taxonomyIDs && taxonomyIDs[0],
slots_size: maxSlotDuration > 0 ? maxSlotDuration : 0,
maxSlotCapacity: 1,
daysOff,
excludedResources,
days: _.map(cracSlots, function(cracSlot) {
const { date } = cracSlot;
var dayBounds;
//dayBounds = getDayBoundsFromAllTimetables(date, resourceTimetables,resourceEvenOddTimeTable,timetableType);
dayBounds = getDayBoundsFromCracSlot(date,cracSlot,business.general_info);
if (!dayBounds) {
const dayOffDate = isoDateForDayOff(date);
business.resources.forEach((rr) => excludedResource(rr.id, dayOffDate));
return {
date,
slots: {
busy: [],
available: false
}
};
} else {
let dayStart = dayBounds.start;
let startTime = dayBounds.start_time;
const dayEnd = dayBounds.end;
const slots = getCrunchSlotsFromCrac(cracSlot, date, dayStart, dayEnd, maxSlotDuration);
if (cracSlot.excludedResources) {
const dayOffDate = isoDateForDayOff(date);
cracSlot.excludedResources.forEach((rid) => excludedResource(rid, dayOffDate));
}
return {
date,
start_time: slots.start_time || startTime,
end_time: slots.end_time || dayBounds.end_time,
slots,
};
}
}),
};
// Post processing of excludedResources
const daysCount = busySlotsResponse.days.length;
for (const resourceId in excludedResourcesCountMap) {
if (Object.prototype.hasOwnProperty.call(excludedResourcesCountMap, resourceId)) {
if (excludedResourcesCountMap[resourceId] >= daysCount) {
excludedResources.push(resourceId);
}
}
}
return busySlotsResponse;
} |
JavaScript | function paginationModel(parent) {
var self = this;
// Var's
self.nrPages = ko.observable(0);
self.currentPage = ko.observable(1);
self.currentStart = ko.observable(0);
self.allpages = ko.observableArray([]).extend({ rateLimit: 50 });
// Has pagination
self.hasPagination = ko.pureComputed(function() {
return self.nrPages() > 1;
})
// Subscribe to number of items
parent.totalItems.subscribe(function() {
// Update
self.updatePages();
})
// Subscribe to changes of pagination limit
parent.paginationLimit.subscribe(function(newValue) {
self.updatePages();
self.moveToPage(self.currentPage());
})
// Easy handler for adding a page-link
self.addPaginationPageLink = function(pageNr) {
// Return object for adding
return {
page: pageNr,
isCurrent: pageNr == self.currentPage(),
isDots: false,
onclick: function(data) {
self.moveToPage(data.page);
}
}
}
// Easy handler to add dots
self.addDots = function() {
return {
page: '...',
isCurrent: false,
isDots: true,
onclick: function() {}
}
}
self.updatePages = function() {
// Empty it
self.allpages.removeAll();
// How many pages do we need?
if(parent.totalItems() <= parent.paginationLimit()) {
// Empty it
self.nrPages(1)
self.currentStart(0);
// Are we on next page?
if(self.currentPage() > 1) {
// Force full update
parent.parent.refresh(true);
}
// Move to current page
self.currentPage(1);
// Force full update
parent.parent.refresh(true);
} else {
// Calculate number of pages needed
var newNrPages = Math.ceil(parent.totalItems() / parent.paginationLimit())
// Make sure the current page still exists
if(self.currentPage() > newNrPages) {
self.moveToPage(newNrPages);
return;
}
// All the cases
if(newNrPages > 7) {
// Do we show the first ones
if(self.currentPage() < 5) {
// Just add the first 4
$.each(new Array(5), function(index) {
self.allpages.push(self.addPaginationPageLink(index + 1))
})
// Dots
self.allpages.push(self.addDots())
// Last one
self.allpages.push(self.addPaginationPageLink(newNrPages))
} else {
// Always add the first
self.allpages.push(self.addPaginationPageLink(1))
// Dots
self.allpages.push(self.addDots())
// Are we near the end?
if((newNrPages - self.currentPage()) < 4) {
// We add the last ones
$.each(new Array(5), function(index) {
self.allpages.push(self.addPaginationPageLink((index - 4) + (newNrPages)))
})
} else {
// We are in the center so display the center 3
$.each(new Array(3), function(index) {
self.allpages.push(self.addPaginationPageLink(self.currentPage() + (index - 1)))
})
// Dots
self.allpages.push(self.addDots())
// Last one
self.allpages.push(self.addPaginationPageLink(newNrPages))
}
}
} else {
// Just add them
$.each(new Array(newNrPages), function(index) {
self.allpages.push(self.addPaginationPageLink(index + 1))
})
}
// Change of number of pages?
if(newNrPages != self.nrPages()) {
// Update
self.nrPages(newNrPages);
}
}
}
// Update on click
self.moveToPage = function(page) {
// Update page and start
self.currentPage(page)
self.currentStart((page - 1) * parent.paginationLimit())
// Re-paginate
self.updatePages();
// Force full update
parent.parent.refresh(true);
}
} | function paginationModel(parent) {
var self = this;
// Var's
self.nrPages = ko.observable(0);
self.currentPage = ko.observable(1);
self.currentStart = ko.observable(0);
self.allpages = ko.observableArray([]).extend({ rateLimit: 50 });
// Has pagination
self.hasPagination = ko.pureComputed(function() {
return self.nrPages() > 1;
})
// Subscribe to number of items
parent.totalItems.subscribe(function() {
// Update
self.updatePages();
})
// Subscribe to changes of pagination limit
parent.paginationLimit.subscribe(function(newValue) {
self.updatePages();
self.moveToPage(self.currentPage());
})
// Easy handler for adding a page-link
self.addPaginationPageLink = function(pageNr) {
// Return object for adding
return {
page: pageNr,
isCurrent: pageNr == self.currentPage(),
isDots: false,
onclick: function(data) {
self.moveToPage(data.page);
}
}
}
// Easy handler to add dots
self.addDots = function() {
return {
page: '...',
isCurrent: false,
isDots: true,
onclick: function() {}
}
}
self.updatePages = function() {
// Empty it
self.allpages.removeAll();
// How many pages do we need?
if(parent.totalItems() <= parent.paginationLimit()) {
// Empty it
self.nrPages(1)
self.currentStart(0);
// Are we on next page?
if(self.currentPage() > 1) {
// Force full update
parent.parent.refresh(true);
}
// Move to current page
self.currentPage(1);
// Force full update
parent.parent.refresh(true);
} else {
// Calculate number of pages needed
var newNrPages = Math.ceil(parent.totalItems() / parent.paginationLimit())
// Make sure the current page still exists
if(self.currentPage() > newNrPages) {
self.moveToPage(newNrPages);
return;
}
// All the cases
if(newNrPages > 7) {
// Do we show the first ones
if(self.currentPage() < 5) {
// Just add the first 4
$.each(new Array(5), function(index) {
self.allpages.push(self.addPaginationPageLink(index + 1))
})
// Dots
self.allpages.push(self.addDots())
// Last one
self.allpages.push(self.addPaginationPageLink(newNrPages))
} else {
// Always add the first
self.allpages.push(self.addPaginationPageLink(1))
// Dots
self.allpages.push(self.addDots())
// Are we near the end?
if((newNrPages - self.currentPage()) < 4) {
// We add the last ones
$.each(new Array(5), function(index) {
self.allpages.push(self.addPaginationPageLink((index - 4) + (newNrPages)))
})
} else {
// We are in the center so display the center 3
$.each(new Array(3), function(index) {
self.allpages.push(self.addPaginationPageLink(self.currentPage() + (index - 1)))
})
// Dots
self.allpages.push(self.addDots())
// Last one
self.allpages.push(self.addPaginationPageLink(newNrPages))
}
}
} else {
// Just add them
$.each(new Array(newNrPages), function(index) {
self.allpages.push(self.addPaginationPageLink(index + 1))
})
}
// Change of number of pages?
if(newNrPages != self.nrPages()) {
// Update
self.nrPages(newNrPages);
}
}
}
// Update on click
self.moveToPage = function(page) {
// Update page and start
self.currentPage(page)
self.currentStart((page - 1) * parent.paginationLimit())
// Re-paginate
self.updatePages();
// Force full update
parent.parent.refresh(true);
}
} |
JavaScript | function checkShiftRange(strCheckboxes) {
// Get them all
var arrAllChecks = $(strCheckboxes);
// Get index of the first and last
var startCheck = arrAllChecks.index($(strCheckboxes + ':checked:first'));
var endCheck = arrAllChecks.index($(strCheckboxes + ':checked:last'));
// Everything in between click it to trigger addMultiEdit
arrAllChecks.slice(startCheck, endCheck).filter(':not(:checked)').trigger('click')
} | function checkShiftRange(strCheckboxes) {
// Get them all
var arrAllChecks = $(strCheckboxes);
// Get index of the first and last
var startCheck = arrAllChecks.index($(strCheckboxes + ':checked:first'));
var endCheck = arrAllChecks.index($(strCheckboxes + ':checked:last'));
// Everything in between click it to trigger addMultiEdit
arrAllChecks.slice(startCheck, endCheck).filter(':not(:checked)').trigger('click')
} |
JavaScript | function hideCompletedFiles() {
if($('#filelist-showcompleted').hasClass('hover-button')) {
// Hide all
$('.item-files-table tr.files-done').hide();
$('#filelist-showcompleted').removeClass('hover-button')
// Set storage
localStorageSetItem('showCompletedFiles', 'No')
} else {
// show all
$('.item-files-table tr.files-done').show();
$('#filelist-showcompleted').addClass('hover-button')
// Set storage
localStorageSetItem('showCompletedFiles', 'Yes')
}
} | function hideCompletedFiles() {
if($('#filelist-showcompleted').hasClass('hover-button')) {
// Hide all
$('.item-files-table tr.files-done').hide();
$('#filelist-showcompleted').removeClass('hover-button')
// Set storage
localStorageSetItem('showCompletedFiles', 'No')
} else {
// show all
$('.item-files-table tr.files-done').show();
$('#filelist-showcompleted').addClass('hover-button')
// Set storage
localStorageSetItem('showCompletedFiles', 'Yes')
}
} |
JavaScript | function ModelViewerEdit(runtime, element) {
function validateColor(element, colorNumber, field){
var _this = $(field);
var el = $('.xblock-editor-error-message', element);
var tinput = _this.val();
if(tinput.match(/#[0-9a-f]{6}/ig)!== null && tinput.length <= 7)
{
el.html('').hide();
}
else
{
el.html('<p class="error" style="color:red;">Error: format for background color ' + colorNumber + '</p>')
.show();
}
}
function validateSize(element, sideName, field){
var _this = $(field);
var el = $('.xblock-editor-error-message', element);
var tinput1 = _this.val();
if( isNaN( tinput1 ) || tinput1 =="" )
{
_this.val(400);
el.html('<p class="error" style="color:red;">Error: format for ' + sideName + ' of viewer</p>').show();
}
else
{
if(tinput1 > 750)
{
el.html('<p class="error" style="color:red;">Error: size exceeds recommended limit (750)</p>').show();
}
else
{
el.html('').hide();
}
}
}
/*Function for submiting input elements in edit mode*/
$(element).on('click', '.save-button', function() {
var handlerUrl = runtime.handlerUrl(element, 'studio_submit');
var el = $(element);
var data = {
word: el.find('input[name=word]').val(),
location: el.find('input[id=loc]').val(),
backgnd: el.find('input[id=bg1]').val(),
backgnd1: el.find('input[id=bg2]').val(),
height: el.find('input[id=vheight]').val(),
width: el.find('input[id=vwidth]').val()
};
$.post(handlerUrl, JSON.stringify(data)).done(function(response) {
window.location.reload(false);
});
});
/*Functions for validation of input for background color 1 and 2*/
$(element).on('keyup','input#bg1',function(){
validateColor(element, '1', this);
});
$(element).on('keyup','input#bg2',function(){
validateColor(element, '2', this);
});
/*Functions for validation of input for height and width*/
$(element).on('keyup','input#vheight',function(){
validateSize(element, 'height', this);
});
$(element).on('keyup','input#vwidth',function(){
validateSize(element, 'width', this);
});
/* Function for canceling */
$(element).on('click', '.cancel-button', function() {
runtime.notify('cancel', {});
});
} | function ModelViewerEdit(runtime, element) {
function validateColor(element, colorNumber, field){
var _this = $(field);
var el = $('.xblock-editor-error-message', element);
var tinput = _this.val();
if(tinput.match(/#[0-9a-f]{6}/ig)!== null && tinput.length <= 7)
{
el.html('').hide();
}
else
{
el.html('<p class="error" style="color:red;">Error: format for background color ' + colorNumber + '</p>')
.show();
}
}
function validateSize(element, sideName, field){
var _this = $(field);
var el = $('.xblock-editor-error-message', element);
var tinput1 = _this.val();
if( isNaN( tinput1 ) || tinput1 =="" )
{
_this.val(400);
el.html('<p class="error" style="color:red;">Error: format for ' + sideName + ' of viewer</p>').show();
}
else
{
if(tinput1 > 750)
{
el.html('<p class="error" style="color:red;">Error: size exceeds recommended limit (750)</p>').show();
}
else
{
el.html('').hide();
}
}
}
/*Function for submiting input elements in edit mode*/
$(element).on('click', '.save-button', function() {
var handlerUrl = runtime.handlerUrl(element, 'studio_submit');
var el = $(element);
var data = {
word: el.find('input[name=word]').val(),
location: el.find('input[id=loc]').val(),
backgnd: el.find('input[id=bg1]').val(),
backgnd1: el.find('input[id=bg2]').val(),
height: el.find('input[id=vheight]').val(),
width: el.find('input[id=vwidth]').val()
};
$.post(handlerUrl, JSON.stringify(data)).done(function(response) {
window.location.reload(false);
});
});
/*Functions for validation of input for background color 1 and 2*/
$(element).on('keyup','input#bg1',function(){
validateColor(element, '1', this);
});
$(element).on('keyup','input#bg2',function(){
validateColor(element, '2', this);
});
/*Functions for validation of input for height and width*/
$(element).on('keyup','input#vheight',function(){
validateSize(element, 'height', this);
});
$(element).on('keyup','input#vwidth',function(){
validateSize(element, 'width', this);
});
/* Function for canceling */
$(element).on('click', '.cancel-button', function() {
runtime.notify('cancel', {});
});
} |
JavaScript | function nameOfKind(id) {
// From https://github.com/TypeStrong/typedoc/blob/master/src/lib/models/reflections/kind.ts
return {
0x1: 'Project',
0x2: 'Module',
0x4: 'Namespace',
0x8: 'Enum',
0x10: 'EnumMember',
0x20: 'Variable',
0x40: 'Function',
0x80: 'Class',
0x100: 'Interface',
0x200: 'Constructor',
0x400: 'Property',
0x800: 'Method',
0x1000: 'CallSignature',
0x2000: 'IndexSignature',
0x4000: 'ConstructorSignature',
0x8000: 'Parameter',
0x10000: 'TypeLiteral',
0x20000: 'TypeParameter',
0x40000: 'Accessor',
0x80000: 'GetSignature',
0x100000: 'SetSignature',
0x200000: 'ObjectLiteral',
0x400000: 'TypeAlias',
0x800000: 'Event',
0x1000000: 'Reference',
}[id]
} | function nameOfKind(id) {
// From https://github.com/TypeStrong/typedoc/blob/master/src/lib/models/reflections/kind.ts
return {
0x1: 'Project',
0x2: 'Module',
0x4: 'Namespace',
0x8: 'Enum',
0x10: 'EnumMember',
0x20: 'Variable',
0x40: 'Function',
0x80: 'Class',
0x100: 'Interface',
0x200: 'Constructor',
0x400: 'Property',
0x800: 'Method',
0x1000: 'CallSignature',
0x2000: 'IndexSignature',
0x4000: 'ConstructorSignature',
0x8000: 'Parameter',
0x10000: 'TypeLiteral',
0x20000: 'TypeParameter',
0x40000: 'Accessor',
0x80000: 'GetSignature',
0x100000: 'SetSignature',
0x200000: 'ObjectLiteral',
0x400000: 'TypeAlias',
0x800000: 'Event',
0x1000000: 'Reference',
}[id]
} |
JavaScript | function classOfKindName(name) {
return {
'Project': 'tsd-kind-project',
'Module': 'tsd-kind-module',
'Namespace': 'tsd-kind-namespace',
'Enum': 'tsd-kind-enum',
'EnumMember': 'tsd-kind-enum-member',
'Variable': 'tsd-kind-variable',
'Function': 'tsd-kind-function',
'Class': 'tsd-kind-class',
'Interface': 'tsd-kind-interface',
'Constructor': 'tsd-kind-constructor',
'Property': 'tsd-kind-property',
'Method': 'tsd-kind-method',
'CallSignature': 'tsd-kind-call-signature',
'IndexSignature': 'tsd-kind-index-signature',
'ConstructorSignature': 'tsd-kind-constructors-ignature',
'Parameter': 'tsd-kind-parameter',
'TypeLiteral': 'tsd-kind-type-literal',
'TypeParameter': 'tsd-kind-type-parameter',
'Accessor': 'tsd-kind-accessor',
'GetSignature': 'tsd-kind-get-signature',
'SetSignature': 'tsd-kind-set-signature',
'ObjectLiteral': 'tsd-kind-object-literal',
'TypeAlias': 'tsd-kind-type-alias',
'Event': 'tsd-kind-event',
'Reference': 'tsd-kind-reference',
}[name]
} | function classOfKindName(name) {
return {
'Project': 'tsd-kind-project',
'Module': 'tsd-kind-module',
'Namespace': 'tsd-kind-namespace',
'Enum': 'tsd-kind-enum',
'EnumMember': 'tsd-kind-enum-member',
'Variable': 'tsd-kind-variable',
'Function': 'tsd-kind-function',
'Class': 'tsd-kind-class',
'Interface': 'tsd-kind-interface',
'Constructor': 'tsd-kind-constructor',
'Property': 'tsd-kind-property',
'Method': 'tsd-kind-method',
'CallSignature': 'tsd-kind-call-signature',
'IndexSignature': 'tsd-kind-index-signature',
'ConstructorSignature': 'tsd-kind-constructors-ignature',
'Parameter': 'tsd-kind-parameter',
'TypeLiteral': 'tsd-kind-type-literal',
'TypeParameter': 'tsd-kind-type-parameter',
'Accessor': 'tsd-kind-accessor',
'GetSignature': 'tsd-kind-get-signature',
'SetSignature': 'tsd-kind-set-signature',
'ObjectLiteral': 'tsd-kind-object-literal',
'TypeAlias': 'tsd-kind-type-alias',
'Event': 'tsd-kind-event',
'Reference': 'tsd-kind-reference',
}[name]
} |
JavaScript | function dirOfKindName(name) {
return {
'Class': 'classes',
'Enum': 'enums'
}[name]
} | function dirOfKindName(name) {
return {
'Class': 'classes',
'Enum': 'enums'
}[name]
} |
JavaScript | function dump(reflection, prefix = '') {
if (!DEBUG) return
const keys = DEBUG_KEYS ? '[' + Object.keys(reflection).join(' ') + ']' : ''
console.log(prefix, `${nameOfKind(reflection.kind)}:`, reflection.name, keys);
if (DEBUG_COMMENT && reflection.comment) {
Object.keys(reflection.comment).forEach(k => {
console.log(prefix, '|', k, reflection.comment[k]);
})
}
if (reflection.children) {
for (const child of reflection.children) {
dump(child, prefix + ' ')
}
}
if (DEBUG_TYPES && sreflection.type) {
// More details https://github.com/TypeStrong/typedoc/blob/master/src/lib/models/types.ts
const { type, name } = reflection.type
console.log(prefix, ' ', type, name || '');
}
} | function dump(reflection, prefix = '') {
if (!DEBUG) return
const keys = DEBUG_KEYS ? '[' + Object.keys(reflection).join(' ') + ']' : ''
console.log(prefix, `${nameOfKind(reflection.kind)}:`, reflection.name, keys);
if (DEBUG_COMMENT && reflection.comment) {
Object.keys(reflection.comment).forEach(k => {
console.log(prefix, '|', k, reflection.comment[k]);
})
}
if (reflection.children) {
for (const child of reflection.children) {
dump(child, prefix + ' ')
}
}
if (DEBUG_TYPES && sreflection.type) {
// More details https://github.com/TypeStrong/typedoc/blob/master/src/lib/models/types.ts
const { type, name } = reflection.type
console.log(prefix, ' ', type, name || '');
}
} |
JavaScript | index(project) {
const collect = (ref) => {
let ret = []
const kind = nameOfKind(ref.kind)
if (kind === undefined) {
throw new Error(`Canont recognize kind code ${ref.kind}.`)
}
switch (kind) {
case 'Enum':
case 'Event':
case 'TypeAlias':
case 'Interface':
case 'Function':
case 'Variable':
case 'Class':
case 'Namespace':
ret.push({
name: ref.name,
kind,
parent: ref.parent.name
})
break
}
if (ref.children) {
for (const c of ref.children) {
ret = ret.concat(collect(c))
}
}
return ret
}
const index = collect(project).sort((a, b) => {
a = a.name.toUpperCase()
b = b.name.toUpperCase()
return a === b ? 0 : (a < b ? -1 : 1)
})
return index
} | index(project) {
const collect = (ref) => {
let ret = []
const kind = nameOfKind(ref.kind)
if (kind === undefined) {
throw new Error(`Canont recognize kind code ${ref.kind}.`)
}
switch (kind) {
case 'Enum':
case 'Event':
case 'TypeAlias':
case 'Interface':
case 'Function':
case 'Variable':
case 'Class':
case 'Namespace':
ret.push({
name: ref.name,
kind,
parent: ref.parent.name
})
break
}
if (ref.children) {
for (const c of ref.children) {
ret = ret.concat(collect(c))
}
}
return ret
}
const index = collect(project).sort((a, b) => {
a = a.name.toUpperCase()
b = b.name.toUpperCase()
return a === b ? 0 : (a < b ? -1 : 1)
})
return index
} |
JavaScript | function arrayIncludesElementsIncluding(array, searchKey) {
if (!array) {
return null
}
let result = [];
for (let item of array) {
if (item.toLowerCase().includes(searchKey)) {
result.push(item);
}
}
return result;
} | function arrayIncludesElementsIncluding(array, searchKey) {
if (!array) {
return null
}
let result = [];
for (let item of array) {
if (item.toLowerCase().includes(searchKey)) {
result.push(item);
}
}
return result;
} |
JavaScript | function SchedulePlan(element) {
this.element = element;
this.timeline = this.element.find('.timeline');
this.timelineItems = this.timeline.find('li');
this.timelineItemsNumber = this.timelineItems.length;
this.timelineStart = getScheduleTimestamp(this.timelineItems.eq(0).text());
//need to store delta (in our case half hour) timestamp
this.timelineUnitDuration = getScheduleTimestamp(this.timelineItems.eq(1).text()) - getScheduleTimestamp(this.timelineItems.eq(0).text());
this.eventsWrapper = this.element.find('.events');
this.eventsGroup = this.eventsWrapper.find('.events-group');
this.singleEvents = this.eventsGroup.find('.single-event');
this.eventSlotHeight = this.eventsGroup.eq(0).children('.top-info').outerHeight();
this.modal = this.element.find('.event-modal');
this.modalHeader = this.modal.find('.header');
this.modalHeaderBg = this.modal.find('.header-bg');
this.modalBody = this.modal.find('.body');
this.modalBodyBg = this.modal.find('.body-bg');
this.modalMaxWidth = 800;
this.modalMaxHeight = 480;
this.animating = false;
this.initSchedule();
} | function SchedulePlan(element) {
this.element = element;
this.timeline = this.element.find('.timeline');
this.timelineItems = this.timeline.find('li');
this.timelineItemsNumber = this.timelineItems.length;
this.timelineStart = getScheduleTimestamp(this.timelineItems.eq(0).text());
//need to store delta (in our case half hour) timestamp
this.timelineUnitDuration = getScheduleTimestamp(this.timelineItems.eq(1).text()) - getScheduleTimestamp(this.timelineItems.eq(0).text());
this.eventsWrapper = this.element.find('.events');
this.eventsGroup = this.eventsWrapper.find('.events-group');
this.singleEvents = this.eventsGroup.find('.single-event');
this.eventSlotHeight = this.eventsGroup.eq(0).children('.top-info').outerHeight();
this.modal = this.element.find('.event-modal');
this.modalHeader = this.modal.find('.header');
this.modalHeaderBg = this.modal.find('.header-bg');
this.modalBody = this.modal.find('.body');
this.modalBodyBg = this.modal.find('.body-bg');
this.modalMaxWidth = 800;
this.modalMaxHeight = 480;
this.animating = false;
this.initSchedule();
} |
JavaScript | function SchedulePlan(element, data) {
this.element = element;
this.timeline = this.element.find('.timeline');
this.timelineItems = this.timeline.find('li');
this.timelineItemsNumber = this.timelineItems.length;
this.timelineStart = getScheduleTimestamp(this.timelineItems.eq(0).text());
// need to store delta (in our case half hour) timestamp
this.timelineUnitDuration = getScheduleTimestamp(this.timelineItems.eq(1).text()) - getScheduleTimestamp(this.timelineItems.eq(0).text());
this.eventsWrapper = this.element.find('.events');
this.eventsGroup = this.eventsWrapper.find('.events-group');
this.singleEvents = this.eventsGroup.find('.single-event');
this.eventSlotHeight = this.eventsGroup.eq(0).children('.top-info').outerHeight();
this.modal = this.element.find('.event-modal');
this.modalHeader = this.modal.find('.header');
this.modalHeaderBg = this.modal.find('.header-bg');
this.modalBody = this.modal.find('.body');
this.modalBodyBg = this.modal.find('.body-bg');
this.modalMaxWidth = 800;
this.modalMaxHeight = 480;
this.animating = false;
this.data = data;
this.initSchedule();
} | function SchedulePlan(element, data) {
this.element = element;
this.timeline = this.element.find('.timeline');
this.timelineItems = this.timeline.find('li');
this.timelineItemsNumber = this.timelineItems.length;
this.timelineStart = getScheduleTimestamp(this.timelineItems.eq(0).text());
// need to store delta (in our case half hour) timestamp
this.timelineUnitDuration = getScheduleTimestamp(this.timelineItems.eq(1).text()) - getScheduleTimestamp(this.timelineItems.eq(0).text());
this.eventsWrapper = this.element.find('.events');
this.eventsGroup = this.eventsWrapper.find('.events-group');
this.singleEvents = this.eventsGroup.find('.single-event');
this.eventSlotHeight = this.eventsGroup.eq(0).children('.top-info').outerHeight();
this.modal = this.element.find('.event-modal');
this.modalHeader = this.modal.find('.header');
this.modalHeaderBg = this.modal.find('.header-bg');
this.modalBody = this.modal.find('.body');
this.modalBodyBg = this.modal.find('.body-bg');
this.modalMaxWidth = 800;
this.modalMaxHeight = 480;
this.animating = false;
this.data = data;
this.initSchedule();
} |
JavaScript | function initializePage() {
$("#testjs").click(function(e) {
$('.jumbotron h1').text("Javascript is connected");
$(this).text("Experience Chan! It's not a lot of questions.\nToo many questions is the Chan disease.\nThe best way is just to observe the noise of the world.\nThe answer to your questions?\nAsk your own heart. ");
$(".jumbotron p").toggleClass("active");
});
// Add any additional listeners here
// example: $("#div-id").click(functionToCall);
} | function initializePage() {
$("#testjs").click(function(e) {
$('.jumbotron h1').text("Javascript is connected");
$(this).text("Experience Chan! It's not a lot of questions.\nToo many questions is the Chan disease.\nThe best way is just to observe the noise of the world.\nThe answer to your questions?\nAsk your own heart. ");
$(".jumbotron p").toggleClass("active");
});
// Add any additional listeners here
// example: $("#div-id").click(functionToCall);
} |
JavaScript | function unifiedServer(req, res) {
const parsedUrl = new URL(req.url, `http://${req.headers.host}`);
const path = parsedUrl.pathname;
const trimmedPath = path.replace(/^\/+|\/$/g, '');
const method = req.method;
const requestQuery = parsedUrl.searchParams;
const headers = req.headers;
// decoder for decoding buffers
const decoder = new StringDecoder('utf8');
let buffer = '';
// called only for requests with body to handle incomming chunks from the stream
req.on('data', (chunk) => {
buffer += decoder.write(chunk); // decode each chunk and append to the earlier received chunks
});
// called for all requests regardless if they contain a body
req.on('end', () => {
buffer += decoder.end();
// check if request path is among the available routes
const selectedCallback = handlers[trimmedPath] || handlers.notFound
// construct data to be sent to all handlers
const data = {
'path': trimmedPath,
'method': method,
'query': requestQuery,
headers,
'payload': buffer
}
selectedCallback(data, function(statusCode = 200, payload = {}) {
const responseData = JSON.stringify(payload);
res.setHeader('Content-Type', 'application/json')
res.writeHead(statusCode);
res.end(responseData);
})
})
} | function unifiedServer(req, res) {
const parsedUrl = new URL(req.url, `http://${req.headers.host}`);
const path = parsedUrl.pathname;
const trimmedPath = path.replace(/^\/+|\/$/g, '');
const method = req.method;
const requestQuery = parsedUrl.searchParams;
const headers = req.headers;
// decoder for decoding buffers
const decoder = new StringDecoder('utf8');
let buffer = '';
// called only for requests with body to handle incomming chunks from the stream
req.on('data', (chunk) => {
buffer += decoder.write(chunk); // decode each chunk and append to the earlier received chunks
});
// called for all requests regardless if they contain a body
req.on('end', () => {
buffer += decoder.end();
// check if request path is among the available routes
const selectedCallback = handlers[trimmedPath] || handlers.notFound
// construct data to be sent to all handlers
const data = {
'path': trimmedPath,
'method': method,
'query': requestQuery,
headers,
'payload': buffer
}
selectedCallback(data, function(statusCode = 200, payload = {}) {
const responseData = JSON.stringify(payload);
res.setHeader('Content-Type', 'application/json')
res.writeHead(statusCode);
res.end(responseData);
})
})
} |
JavaScript | function handleViewDocuments(e, id, type) {
switch (type) {
case 'RC_FRONT':
{
let singleVehicleInfo = viewData.filter((data) => data.vehicle_id == id)
console.log(viewData)
console.log(singleVehicleInfo[0].rc_copy_front)
setDocumentSrc(singleVehicleInfo[0].rc_copy_front)
setRCCopyFront(true)
}
break
case 'RC_BACK':
{
let singleVehicleInfo = viewData.filter((data) => data.vehicle_id == id)
setDocumentSrc(singleVehicleInfo[0].rc_copy_back)
setRCCopyBack(true)
}
break
case 'INSURANCE_FRONT':
{
let singleVehicleInfo = viewData.filter((data) => data.vehicle_id == id)
setDocumentSrc(singleVehicleInfo[0].insurance_copy_front)
setInsuranceCopyFront(true)
}
break
case 'INSURANCE_BACK':
{
let singleVehicleInfo = viewData.filter((data) => data.vehicle_id == id)
setDocumentSrc(singleVehicleInfo[0].insurance_copy_back)
setInsuranceCopyBack(true)
}
break
default:return 0
}
} | function handleViewDocuments(e, id, type) {
switch (type) {
case 'RC_FRONT':
{
let singleVehicleInfo = viewData.filter((data) => data.vehicle_id == id)
console.log(viewData)
console.log(singleVehicleInfo[0].rc_copy_front)
setDocumentSrc(singleVehicleInfo[0].rc_copy_front)
setRCCopyFront(true)
}
break
case 'RC_BACK':
{
let singleVehicleInfo = viewData.filter((data) => data.vehicle_id == id)
setDocumentSrc(singleVehicleInfo[0].rc_copy_back)
setRCCopyBack(true)
}
break
case 'INSURANCE_FRONT':
{
let singleVehicleInfo = viewData.filter((data) => data.vehicle_id == id)
setDocumentSrc(singleVehicleInfo[0].insurance_copy_front)
setInsuranceCopyFront(true)
}
break
case 'INSURANCE_BACK':
{
let singleVehicleInfo = viewData.filter((data) => data.vehicle_id == id)
setDocumentSrc(singleVehicleInfo[0].insurance_copy_back)
setInsuranceCopyBack(true)
}
break
default:return 0
}
} |
JavaScript | function logout()
{
AuthService.logout().then((res)=>{
if(res.status==204)
{
LocalStorageService.clear()
window.location.href="/login";
}
})
} | function logout()
{
AuthService.logout().then((res)=>{
if(res.status==204)
{
LocalStorageService.clear()
window.location.href="/login";
}
})
} |
JavaScript | videoSearch(term){
YTSearch(
{key :API_KEY, term: term},
(videos) => {this.setState(
{
videos: videos,
selectedVideo: videos[0]
});
});
} | videoSearch(term){
YTSearch(
{key :API_KEY, term: term},
(videos) => {this.setState(
{
videos: videos,
selectedVideo: videos[0]
});
});
} |
JavaScript | function calculateRectPosition(imgProps, rawBoxCoords) {
var left = Math.min(
rawBoxCoords.startX,
rawBoxCoords.currX
);
var top = Math.min(
rawBoxCoords.startY,
rawBoxCoords.currY
);
var right = Math.max(
rawBoxCoords.startX,
rawBoxCoords.currX
);
var bottom = Math.max(
rawBoxCoords.startY,
rawBoxCoords.currY
);
// width of div border
const DIV_BORDER = 4
const width = imgProps.width - DIV_BORDER;
const height = imgProps.height - DIV_BORDER;
// limit rectangles to the size of the image
// so user can't draw rectangle that spill out of image
left = Math.max(imgProps.offsetX, left);
top = Math.max(imgProps.offsetY, top);
right = Math.min(width + imgProps.offsetX, right);
bottom = Math.min(height + imgProps.offsetY, bottom);
return {
left: left - imgProps.offsetX,
top: top - imgProps.offsetY,
width: right - left,
height: bottom - top
};
} | function calculateRectPosition(imgProps, rawBoxCoords) {
var left = Math.min(
rawBoxCoords.startX,
rawBoxCoords.currX
);
var top = Math.min(
rawBoxCoords.startY,
rawBoxCoords.currY
);
var right = Math.max(
rawBoxCoords.startX,
rawBoxCoords.currX
);
var bottom = Math.max(
rawBoxCoords.startY,
rawBoxCoords.currY
);
// width of div border
const DIV_BORDER = 4
const width = imgProps.width - DIV_BORDER;
const height = imgProps.height - DIV_BORDER;
// limit rectangles to the size of the image
// so user can't draw rectangle that spill out of image
left = Math.max(imgProps.offsetX, left);
top = Math.max(imgProps.offsetY, top);
right = Math.min(width + imgProps.offsetX, right);
bottom = Math.min(height + imgProps.offsetY, bottom);
return {
left: left - imgProps.offsetX,
top: top - imgProps.offsetY,
width: right - left,
height: bottom - top
};
} |
JavaScript | function readFormula(nomeArquivoCnf){
const fileSystem = require('fs');
let texto = fileSystem.readFileSync(nomeArquivoCnf, 'utf8'); //lendo arquivo e armazenando texto
let partesDoTexto = getPartesDoTexto(texto); //armazenando stringClausulas e stringProblema
let arrayClausulas = getClausulas(partesDoTexto.stringClausulas); //armazenando arrayClausulas
let arrayVariaveis = getVariaveis(partesDoTexto.stringClausulas);
//console.log(getVariaveis(partesDoTexto.stringClausulas)); //imprime arrayVariaveis (getVariaveis)
//console.log(arrayClausulas); //imprime arrayClausulas (getClausulas)
//console.log(partesDoTexto.stringClausulas); //imprime stringClausulas (getPartesDoTexto.stringClausulas)
let objeto = {
clausulas: arrayClausulas,
variaveis: arrayVariaveis
};
globalProblema = partesDoTexto.stringProblema; //retorna a linha do problema por referencia
return objeto; //retorna a formula com 2 arrays
} | function readFormula(nomeArquivoCnf){
const fileSystem = require('fs');
let texto = fileSystem.readFileSync(nomeArquivoCnf, 'utf8'); //lendo arquivo e armazenando texto
let partesDoTexto = getPartesDoTexto(texto); //armazenando stringClausulas e stringProblema
let arrayClausulas = getClausulas(partesDoTexto.stringClausulas); //armazenando arrayClausulas
let arrayVariaveis = getVariaveis(partesDoTexto.stringClausulas);
//console.log(getVariaveis(partesDoTexto.stringClausulas)); //imprime arrayVariaveis (getVariaveis)
//console.log(arrayClausulas); //imprime arrayClausulas (getClausulas)
//console.log(partesDoTexto.stringClausulas); //imprime stringClausulas (getPartesDoTexto.stringClausulas)
let objeto = {
clausulas: arrayClausulas,
variaveis: arrayVariaveis
};
globalProblema = partesDoTexto.stringProblema; //retorna a linha do problema por referencia
return objeto; //retorna a formula com 2 arrays
} |
JavaScript | function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
if (cropper) {
cropper.destroy();
}
$('#cropping-modal').modal('show');
console.log("executing");
file = reader.result;
};
reader.readAsDataURL(input.files[0]);
}
} //cada vez que cambia el archivo subido llama a readURL | function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
if (cropper) {
cropper.destroy();
}
$('#cropping-modal').modal('show');
console.log("executing");
file = reader.result;
};
reader.readAsDataURL(input.files[0]);
}
} //cada vez que cambia el archivo subido llama a readURL |
JavaScript | function modify(geometry) {
var vertices = [];
for (var i = 0, il = geometry.faces.length; i < il; i++) {
var n = vertices.length;
var face = geometry.faces[i];
var a = face.a;
var b = face.b;
var c = face.c;
var va = geometry.vertices[a];
var vb = geometry.vertices[b];
var vc = geometry.vertices[c];
vertices.push(va.clone());
vertices.push(vb.clone());
vertices.push(vc.clone());
face.a = n;
face.b = n + 1;
face.c = n + 2;
}
geometry.vertices = vertices;
} | function modify(geometry) {
var vertices = [];
for (var i = 0, il = geometry.faces.length; i < il; i++) {
var n = vertices.length;
var face = geometry.faces[i];
var a = face.a;
var b = face.b;
var c = face.c;
var va = geometry.vertices[a];
var vb = geometry.vertices[b];
var vc = geometry.vertices[c];
vertices.push(va.clone());
vertices.push(vb.clone());
vertices.push(vc.clone());
face.a = n;
face.b = n + 1;
face.c = n + 2;
}
geometry.vertices = vertices;
} |
JavaScript | createDataTexture() {
const tex = this.gpu.createTexture();
let posCount = 0;
const data = tex.image.data;
for (let i = 0; i < this.count; i++) {
data[i * 4 + 0] = 0;
data[i * 4 + 1] = 0;
data[i * 4 + 2] = 0;
data[i * 4 + 3] = i / this.count;
}
return tex;
} | createDataTexture() {
const tex = this.gpu.createTexture();
let posCount = 0;
const data = tex.image.data;
for (let i = 0; i < this.count; i++) {
data[i * 4 + 0] = 0;
data[i * 4 + 1] = 0;
data[i * 4 + 2] = 0;
data[i * 4 + 3] = i / this.count;
}
return tex;
} |
JavaScript | function isChildUnwrappableOptionalChain(node, child) {
if (isChainExpression(child) &&
// (x?.y).z is semantically different, and as such .z is no longer optional
node.expression.kind !== ts.SyntaxKind.ParenthesizedExpression) {
return true;
}
return false;
} | function isChildUnwrappableOptionalChain(node, child) {
if (isChainExpression(child) &&
// (x?.y).z is semantically different, and as such .z is no longer optional
node.expression.kind !== ts.SyntaxKind.ParenthesizedExpression) {
return true;
}
return false;
} |
JavaScript | function createError(ast, start, message) {
const loc = ast.getLineAndCharacterOfPosition(start);
return {
index: start,
lineNumber: loc.line + 1,
column: loc.character,
message,
};
} | function createError(ast, start, message) {
const loc = ast.getLineAndCharacterOfPosition(start);
return {
index: start,
lineNumber: loc.line + 1,
column: loc.character,
message,
};
} |
JavaScript | function nodeHasTokens(n, ast) {
// If we have a token or node that has a non-zero width, it must have tokens.
// Note: getWidth() does not take trivia into account.
return n.kind === SyntaxKind.EndOfFileToken
? // eslint-disable-next-line @typescript-eslint/no-explicit-any
!!n.jsDoc
: n.getWidth(ast) !== 0;
} | function nodeHasTokens(n, ast) {
// If we have a token or node that has a non-zero width, it must have tokens.
// Note: getWidth() does not take trivia into account.
return n.kind === SyntaxKind.EndOfFileToken
? // eslint-disable-next-line @typescript-eslint/no-explicit-any
!!n.jsDoc
: n.getWidth(ast) !== 0;
} |
JavaScript | function asyncReducer (
[request, receive, error = null]
) {
const res = {
[request]: (draft, { meta }) => {
draft.updateAt = meta.createdAt
draft.inProgress = true
},
[receive]: (draft, { meta }) => {
draft.updateAt = meta.createdAt
draft.inProgress = false
draft.invalid = false
}
}
if (error) {
res[error] = (draft, { meta, payload }) => {
draft.updateAt = meta.createdAt
draft.error = payload.error
draft.inProgress = false
draft.invalid = false
}
}
return res
} | function asyncReducer (
[request, receive, error = null]
) {
const res = {
[request]: (draft, { meta }) => {
draft.updateAt = meta.createdAt
draft.inProgress = true
},
[receive]: (draft, { meta }) => {
draft.updateAt = meta.createdAt
draft.inProgress = false
draft.invalid = false
}
}
if (error) {
res[error] = (draft, { meta, payload }) => {
draft.updateAt = meta.createdAt
draft.error = payload.error
draft.inProgress = false
draft.invalid = false
}
}
return res
} |
JavaScript | function createSelectorPrecise (...funcs) {
return (areArgumentsEqual) => {
function scepticalMemoize (func, globalState = true) {
// memoize is called twice in createSelectorCreator
// 1) when compare global state (won't be passed custom options - globalState)
// 2) when compare local parameters (will be passed custom options - globalState)
// because Precise selector creator target to compare local parameters
// we redirect global compare to default memorize
if (globalState) {
return defaultMemoize(func)
}
let lastArgs = null
let lastResult = null
// we reference arguments instead of spreading them for performance reasons
return function (...args) {
if (lastArgs === null || args === null || lastArgs.length !== args.length || !areArgumentsEqual(lastArgs, args)) {
// apply arguments instead of spreading for performance
lastResult = func.apply(null, args)
}
lastArgs = args
return lastResult
}
}
return createSelectorCreator(scepticalMemoize, false)(...funcs)
}
} | function createSelectorPrecise (...funcs) {
return (areArgumentsEqual) => {
function scepticalMemoize (func, globalState = true) {
// memoize is called twice in createSelectorCreator
// 1) when compare global state (won't be passed custom options - globalState)
// 2) when compare local parameters (will be passed custom options - globalState)
// because Precise selector creator target to compare local parameters
// we redirect global compare to default memorize
if (globalState) {
return defaultMemoize(func)
}
let lastArgs = null
let lastResult = null
// we reference arguments instead of spreading them for performance reasons
return function (...args) {
if (lastArgs === null || args === null || lastArgs.length !== args.length || !areArgumentsEqual(lastArgs, args)) {
// apply arguments instead of spreading for performance
lastResult = func.apply(null, args)
}
lastArgs = args
return lastResult
}
}
return createSelectorCreator(scepticalMemoize, false)(...funcs)
}
} |
JavaScript | function binarySearchOfCallback (comparator, valuesLength) {
let minIdx = 0
let maxIdx = valuesLength
let cycles = 0
while (minIdx < maxIdx) {
let idx = (maxIdx + minIdx) >> 1
let diff = comparator(idx)
// console.log('cycles', cycles, { idx, minIdx, maxIdx, diff })
if (diff > 0) {
maxIdx = Math.max(0, idx, minIdx)
} else if (diff < 0) {
minIdx = Math.min(idx + 1, maxIdx)
} else {
return idx
}
// console.log('new', { minIdx, maxIdx })
if (++cycles > valuesLength) {
console.log('diff:', _.range(valuesLength).map(idx => ({ idx, diff: comparator(idx) })))
throw new Error('search too long', { idx, minIdx, maxIdx, diff })
}
}
return minIdx
} | function binarySearchOfCallback (comparator, valuesLength) {
let minIdx = 0
let maxIdx = valuesLength
let cycles = 0
while (minIdx < maxIdx) {
let idx = (maxIdx + minIdx) >> 1
let diff = comparator(idx)
// console.log('cycles', cycles, { idx, minIdx, maxIdx, diff })
if (diff > 0) {
maxIdx = Math.max(0, idx, minIdx)
} else if (diff < 0) {
minIdx = Math.min(idx + 1, maxIdx)
} else {
return idx
}
// console.log('new', { minIdx, maxIdx })
if (++cycles > valuesLength) {
console.log('diff:', _.range(valuesLength).map(idx => ({ idx, diff: comparator(idx) })))
throw new Error('search too long', { idx, minIdx, maxIdx, diff })
}
}
return minIdx
} |
JavaScript | _sendMessages () {
while (!this._queue.isEmpty() && this._connection.isConnected()) {
this._connection.send(this._queue.pop())
}
} | _sendMessages () {
while (!this._queue.isEmpty() && this._connection.isConnected()) {
this._connection.send(this._queue.pop())
}
} |
JavaScript | function handleScroll (event) {
// IE doesn't support "scrollingElement" but who cares ;)
// if we would really need it
// we can use polyfill
// https://github.com/yangg/scrolling-element
const currentScrollPos = event.srcElement.scrollingElement.scrollTop
if (previousScrollTop > currentScrollPos) {
setVisibility(true)
} else {
setVisibility(false)
}
previousScrollTop = currentScrollPos
} | function handleScroll (event) {
// IE doesn't support "scrollingElement" but who cares ;)
// if we would really need it
// we can use polyfill
// https://github.com/yangg/scrolling-element
const currentScrollPos = event.srcElement.scrollingElement.scrollTop
if (previousScrollTop > currentScrollPos) {
setVisibility(true)
} else {
setVisibility(false)
}
previousScrollTop = currentScrollPos
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.