id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
37,400 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/fullcalendar.js
|
isSlotSegCollision
|
function isSlotSegCollision(seg1, seg2) {
return seg1.end > seg2.start && seg1.start < seg2.end;
}
|
javascript
|
function isSlotSegCollision(seg1, seg2) {
return seg1.end > seg2.start && seg1.start < seg2.end;
}
|
[
"function",
"isSlotSegCollision",
"(",
"seg1",
",",
"seg2",
")",
"{",
"return",
"seg1",
".",
"end",
">",
"seg2",
".",
"start",
"&&",
"seg1",
".",
"start",
"<",
"seg2",
".",
"end",
";",
"}"
] |
Do these segments occupy the same vertical space?
|
[
"Do",
"these",
"segments",
"occupy",
"the",
"same",
"vertical",
"space?"
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L4512-L4514
|
37,401 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/fullcalendar.js
|
compareForwardSlotSegs
|
function compareForwardSlotSegs(seg1, seg2) {
// put higher-pressure first
return seg2.forwardPressure - seg1.forwardPressure ||
// put segments that are closer to initial edge first (and favor ones with no coords yet)
(seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) ||
// do normal sorting...
compareSlotSegs(seg1, seg2);
}
|
javascript
|
function compareForwardSlotSegs(seg1, seg2) {
// put higher-pressure first
return seg2.forwardPressure - seg1.forwardPressure ||
// put segments that are closer to initial edge first (and favor ones with no coords yet)
(seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) ||
// do normal sorting...
compareSlotSegs(seg1, seg2);
}
|
[
"function",
"compareForwardSlotSegs",
"(",
"seg1",
",",
"seg2",
")",
"{",
"// put higher-pressure first",
"return",
"seg2",
".",
"forwardPressure",
"-",
"seg1",
".",
"forwardPressure",
"||",
"// put segments that are closer to initial edge first (and favor ones with no coords yet)",
"(",
"seg1",
".",
"backwardCoord",
"||",
"0",
")",
"-",
"(",
"seg2",
".",
"backwardCoord",
"||",
"0",
")",
"||",
"// do normal sorting...",
"compareSlotSegs",
"(",
"seg1",
",",
"seg2",
")",
";",
"}"
] |
A cmp function for determining which forward segment to rely on more when computing coordinates.
|
[
"A",
"cmp",
"function",
"for",
"determining",
"which",
"forward",
"segment",
"to",
"rely",
"on",
"more",
"when",
"computing",
"coordinates",
"."
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L4518-L4525
|
37,402 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/fullcalendar.js
|
eventElementHandlers
|
function eventElementHandlers(event, eventElement) {
eventElement
.click(function(ev) {
if (!eventElement.hasClass('ui-draggable-dragging') &&
!eventElement.hasClass('ui-resizable-resizing')) {
return trigger('eventClick', this, event, ev);
}
})
.hover(
function(ev) {
trigger('eventMouseover', this, event, ev);
},
function(ev) {
trigger('eventMouseout', this, event, ev);
}
);
// TODO: don't fire eventMouseover/eventMouseout *while* dragging is occuring (on subject element)
// TODO: same for resizing
}
|
javascript
|
function eventElementHandlers(event, eventElement) {
eventElement
.click(function(ev) {
if (!eventElement.hasClass('ui-draggable-dragging') &&
!eventElement.hasClass('ui-resizable-resizing')) {
return trigger('eventClick', this, event, ev);
}
})
.hover(
function(ev) {
trigger('eventMouseover', this, event, ev);
},
function(ev) {
trigger('eventMouseout', this, event, ev);
}
);
// TODO: don't fire eventMouseover/eventMouseout *while* dragging is occuring (on subject element)
// TODO: same for resizing
}
|
[
"function",
"eventElementHandlers",
"(",
"event",
",",
"eventElement",
")",
"{",
"eventElement",
".",
"click",
"(",
"function",
"(",
"ev",
")",
"{",
"if",
"(",
"!",
"eventElement",
".",
"hasClass",
"(",
"'ui-draggable-dragging'",
")",
"&&",
"!",
"eventElement",
".",
"hasClass",
"(",
"'ui-resizable-resizing'",
")",
")",
"{",
"return",
"trigger",
"(",
"'eventClick'",
",",
"this",
",",
"event",
",",
"ev",
")",
";",
"}",
"}",
")",
".",
"hover",
"(",
"function",
"(",
"ev",
")",
"{",
"trigger",
"(",
"'eventMouseover'",
",",
"this",
",",
"event",
",",
"ev",
")",
";",
"}",
",",
"function",
"(",
"ev",
")",
"{",
"trigger",
"(",
"'eventMouseout'",
",",
"this",
",",
"event",
",",
"ev",
")",
";",
"}",
")",
";",
"// TODO: don't fire eventMouseover/eventMouseout *while* dragging is occuring (on subject element)",
"// TODO: same for resizing",
"}"
] |
attaches eventClick, eventMouseover, eventMouseout
|
[
"attaches",
"eventClick",
"eventMouseover",
"eventMouseout"
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L4687-L4705
|
37,403 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/fullcalendar.js
|
cellOffsetToDayOffset
|
function cellOffsetToDayOffset(cellOffset) {
var day0 = t.visStart.getDay(); // first date's day of week
cellOffset += dayToCellMap[day0]; // normlize cellOffset to beginning-of-week
return Math.floor(cellOffset / cellsPerWeek) * 7 // # of days from full weeks
+ cellToDayMap[ // # of days from partial last week
(cellOffset % cellsPerWeek + cellsPerWeek) % cellsPerWeek // crazy math to handle negative cellOffsets
]
- day0; // adjustment for beginning-of-week normalization
}
|
javascript
|
function cellOffsetToDayOffset(cellOffset) {
var day0 = t.visStart.getDay(); // first date's day of week
cellOffset += dayToCellMap[day0]; // normlize cellOffset to beginning-of-week
return Math.floor(cellOffset / cellsPerWeek) * 7 // # of days from full weeks
+ cellToDayMap[ // # of days from partial last week
(cellOffset % cellsPerWeek + cellsPerWeek) % cellsPerWeek // crazy math to handle negative cellOffsets
]
- day0; // adjustment for beginning-of-week normalization
}
|
[
"function",
"cellOffsetToDayOffset",
"(",
"cellOffset",
")",
"{",
"var",
"day0",
"=",
"t",
".",
"visStart",
".",
"getDay",
"(",
")",
";",
"// first date's day of week",
"cellOffset",
"+=",
"dayToCellMap",
"[",
"day0",
"]",
";",
"// normlize cellOffset to beginning-of-week",
"return",
"Math",
".",
"floor",
"(",
"cellOffset",
"/",
"cellsPerWeek",
")",
"*",
"7",
"// # of days from full weeks",
"+",
"cellToDayMap",
"[",
"// # of days from partial last week",
"(",
"cellOffset",
"%",
"cellsPerWeek",
"+",
"cellsPerWeek",
")",
"%",
"cellsPerWeek",
"// crazy math to handle negative cellOffsets",
"]",
"-",
"day0",
";",
"// adjustment for beginning-of-week normalization",
"}"
] |
cell offset -> day offset
|
[
"cell",
"offset",
"-",
">",
"day",
"offset"
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L4949-L4957
|
37,404 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/fullcalendar.js
|
dayOffsetToCellOffset
|
function dayOffsetToCellOffset(dayOffset) {
var day0 = t.visStart.getDay(); // first date's day of week
dayOffset += day0; // normalize dayOffset to beginning-of-week
return Math.floor(dayOffset / 7) * cellsPerWeek // # of cells from full weeks
+ dayToCellMap[ // # of cells from partial last week
(dayOffset % 7 + 7) % 7 // crazy math to handle negative dayOffsets
]
- dayToCellMap[day0]; // adjustment for beginning-of-week normalization
}
|
javascript
|
function dayOffsetToCellOffset(dayOffset) {
var day0 = t.visStart.getDay(); // first date's day of week
dayOffset += day0; // normalize dayOffset to beginning-of-week
return Math.floor(dayOffset / 7) * cellsPerWeek // # of cells from full weeks
+ dayToCellMap[ // # of cells from partial last week
(dayOffset % 7 + 7) % 7 // crazy math to handle negative dayOffsets
]
- dayToCellMap[day0]; // adjustment for beginning-of-week normalization
}
|
[
"function",
"dayOffsetToCellOffset",
"(",
"dayOffset",
")",
"{",
"var",
"day0",
"=",
"t",
".",
"visStart",
".",
"getDay",
"(",
")",
";",
"// first date's day of week",
"dayOffset",
"+=",
"day0",
";",
"// normalize dayOffset to beginning-of-week",
"return",
"Math",
".",
"floor",
"(",
"dayOffset",
"/",
"7",
")",
"*",
"cellsPerWeek",
"// # of cells from full weeks",
"+",
"dayToCellMap",
"[",
"// # of cells from partial last week",
"(",
"dayOffset",
"%",
"7",
"+",
"7",
")",
"%",
"7",
"// crazy math to handle negative dayOffsets",
"]",
"-",
"dayToCellMap",
"[",
"day0",
"]",
";",
"// adjustment for beginning-of-week normalization",
"}"
] |
day offset -> cell offset
|
[
"day",
"offset",
"-",
">",
"cell",
"offset"
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L4985-L4993
|
37,405 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/fullcalendar.js
|
renderTempDayEvent
|
function renderTempDayEvent(event, adjustRow, adjustTop) {
// actually render the event. `true` for appending element to container.
// Recieve the intermediate "segment" data structures.
var segments = _renderDayEvents(
[ event ],
true, // append event elements
false // don't set the heights of the rows
);
var elements = [];
// Adjust certain elements' top coordinates
segmentElementEach(segments, function(segment, element) {
if (segment.row === adjustRow) {
element.css('top', adjustTop);
}
elements.push(element[0]); // accumulate DOM nodes
});
return elements;
}
|
javascript
|
function renderTempDayEvent(event, adjustRow, adjustTop) {
// actually render the event. `true` for appending element to container.
// Recieve the intermediate "segment" data structures.
var segments = _renderDayEvents(
[ event ],
true, // append event elements
false // don't set the heights of the rows
);
var elements = [];
// Adjust certain elements' top coordinates
segmentElementEach(segments, function(segment, element) {
if (segment.row === adjustRow) {
element.css('top', adjustTop);
}
elements.push(element[0]); // accumulate DOM nodes
});
return elements;
}
|
[
"function",
"renderTempDayEvent",
"(",
"event",
",",
"adjustRow",
",",
"adjustTop",
")",
"{",
"// actually render the event. `true` for appending element to container.",
"// Recieve the intermediate \"segment\" data structures.",
"var",
"segments",
"=",
"_renderDayEvents",
"(",
"[",
"event",
"]",
",",
"true",
",",
"// append event elements",
"false",
"// don't set the heights of the rows",
")",
";",
"var",
"elements",
"=",
"[",
"]",
";",
"// Adjust certain elements' top coordinates",
"segmentElementEach",
"(",
"segments",
",",
"function",
"(",
"segment",
",",
"element",
")",
"{",
"if",
"(",
"segment",
".",
"row",
"===",
"adjustRow",
")",
"{",
"element",
".",
"css",
"(",
"'top'",
",",
"adjustTop",
")",
";",
"}",
"elements",
".",
"push",
"(",
"element",
"[",
"0",
"]",
")",
";",
"// accumulate DOM nodes",
"}",
")",
";",
"return",
"elements",
";",
"}"
] |
Render an event on the calendar, but don't report them anywhere, and don't attach mouse handlers. Append this event element to the event container, which might already be populated with events. If an event's segment will have row equal to `adjustRow`, then explicitly set its top coordinate to `adjustTop`. This hack is used to maintain continuity when user is manually resizing an event. Returns an array of DOM elements for the event.
|
[
"Render",
"an",
"event",
"on",
"the",
"calendar",
"but",
"don",
"t",
"report",
"them",
"anywhere",
"and",
"don",
"t",
"attach",
"mouse",
"handlers",
".",
"Append",
"this",
"event",
"element",
"to",
"the",
"event",
"container",
"which",
"might",
"already",
"be",
"populated",
"with",
"events",
".",
"If",
"an",
"event",
"s",
"segment",
"will",
"have",
"row",
"equal",
"to",
"adjustRow",
"then",
"explicitly",
"set",
"its",
"top",
"coordinate",
"to",
"adjustTop",
".",
"This",
"hack",
"is",
"used",
"to",
"maintain",
"continuity",
"when",
"user",
"is",
"manually",
"resizing",
"an",
"event",
".",
"Returns",
"an",
"array",
"of",
"DOM",
"elements",
"for",
"the",
"event",
"."
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5158-L5179
|
37,406 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/fullcalendar.js
|
_renderDayEvents
|
function _renderDayEvents(events, doAppend, doRowHeights) {
// where the DOM nodes will eventually end up
var finalContainer = getDaySegmentContainer();
// the container where the initial HTML will be rendered.
// If `doAppend`==true, uses a temporary container.
var renderContainer = doAppend ? $("<div/>") : finalContainer;
var segments = buildSegments(events);
var html;
var elements;
// calculate the desired `left` and `width` properties on each segment object
calculateHorizontals(segments);
// build the HTML string. relies on `left` property
html = buildHTML(segments);
// render the HTML. innerHTML is considerably faster than jQuery's .html()
renderContainer[0].innerHTML = html;
// retrieve the individual elements
elements = renderContainer.children();
// if we were appending, and thus using a temporary container,
// re-attach elements to the real container.
if (doAppend) {
finalContainer.append(elements);
}
// assigns each element to `segment.event`, after filtering them through user callbacks
resolveElements(segments, elements);
// Calculate the left and right padding+margin for each element.
// We need this for setting each element's desired outer width, because of the W3C box model.
// It's important we do this in a separate pass from acually setting the width on the DOM elements
// because alternating reading/writing dimensions causes reflow for every iteration.
segmentElementEach(segments, function(segment, element) {
segment.hsides = hsides(element, true); // include margins = `true`
});
// Set the width of each element
segmentElementEach(segments, function(segment, element) {
element.width(
Math.max(0, segment.outerWidth - segment.hsides)
);
});
// Grab each element's outerHeight (setVerticals uses this).
// To get an accurate reading, it's important to have each element's width explicitly set already.
segmentElementEach(segments, function(segment, element) {
segment.outerHeight = element.outerHeight(true); // include margins = `true`
});
// Set the top coordinate on each element (requires segment.outerHeight)
setVerticals(segments, doRowHeights);
return segments;
}
|
javascript
|
function _renderDayEvents(events, doAppend, doRowHeights) {
// where the DOM nodes will eventually end up
var finalContainer = getDaySegmentContainer();
// the container where the initial HTML will be rendered.
// If `doAppend`==true, uses a temporary container.
var renderContainer = doAppend ? $("<div/>") : finalContainer;
var segments = buildSegments(events);
var html;
var elements;
// calculate the desired `left` and `width` properties on each segment object
calculateHorizontals(segments);
// build the HTML string. relies on `left` property
html = buildHTML(segments);
// render the HTML. innerHTML is considerably faster than jQuery's .html()
renderContainer[0].innerHTML = html;
// retrieve the individual elements
elements = renderContainer.children();
// if we were appending, and thus using a temporary container,
// re-attach elements to the real container.
if (doAppend) {
finalContainer.append(elements);
}
// assigns each element to `segment.event`, after filtering them through user callbacks
resolveElements(segments, elements);
// Calculate the left and right padding+margin for each element.
// We need this for setting each element's desired outer width, because of the W3C box model.
// It's important we do this in a separate pass from acually setting the width on the DOM elements
// because alternating reading/writing dimensions causes reflow for every iteration.
segmentElementEach(segments, function(segment, element) {
segment.hsides = hsides(element, true); // include margins = `true`
});
// Set the width of each element
segmentElementEach(segments, function(segment, element) {
element.width(
Math.max(0, segment.outerWidth - segment.hsides)
);
});
// Grab each element's outerHeight (setVerticals uses this).
// To get an accurate reading, it's important to have each element's width explicitly set already.
segmentElementEach(segments, function(segment, element) {
segment.outerHeight = element.outerHeight(true); // include margins = `true`
});
// Set the top coordinate on each element (requires segment.outerHeight)
setVerticals(segments, doRowHeights);
return segments;
}
|
[
"function",
"_renderDayEvents",
"(",
"events",
",",
"doAppend",
",",
"doRowHeights",
")",
"{",
"// where the DOM nodes will eventually end up",
"var",
"finalContainer",
"=",
"getDaySegmentContainer",
"(",
")",
";",
"// the container where the initial HTML will be rendered.",
"// If `doAppend`==true, uses a temporary container.",
"var",
"renderContainer",
"=",
"doAppend",
"?",
"$",
"(",
"\"<div/>\"",
")",
":",
"finalContainer",
";",
"var",
"segments",
"=",
"buildSegments",
"(",
"events",
")",
";",
"var",
"html",
";",
"var",
"elements",
";",
"// calculate the desired `left` and `width` properties on each segment object",
"calculateHorizontals",
"(",
"segments",
")",
";",
"// build the HTML string. relies on `left` property",
"html",
"=",
"buildHTML",
"(",
"segments",
")",
";",
"// render the HTML. innerHTML is considerably faster than jQuery's .html()",
"renderContainer",
"[",
"0",
"]",
".",
"innerHTML",
"=",
"html",
";",
"// retrieve the individual elements",
"elements",
"=",
"renderContainer",
".",
"children",
"(",
")",
";",
"// if we were appending, and thus using a temporary container,",
"// re-attach elements to the real container.",
"if",
"(",
"doAppend",
")",
"{",
"finalContainer",
".",
"append",
"(",
"elements",
")",
";",
"}",
"// assigns each element to `segment.event`, after filtering them through user callbacks",
"resolveElements",
"(",
"segments",
",",
"elements",
")",
";",
"// Calculate the left and right padding+margin for each element.",
"// We need this for setting each element's desired outer width, because of the W3C box model.",
"// It's important we do this in a separate pass from acually setting the width on the DOM elements",
"// because alternating reading/writing dimensions causes reflow for every iteration.",
"segmentElementEach",
"(",
"segments",
",",
"function",
"(",
"segment",
",",
"element",
")",
"{",
"segment",
".",
"hsides",
"=",
"hsides",
"(",
"element",
",",
"true",
")",
";",
"// include margins = `true`",
"}",
")",
";",
"// Set the width of each element",
"segmentElementEach",
"(",
"segments",
",",
"function",
"(",
"segment",
",",
"element",
")",
"{",
"element",
".",
"width",
"(",
"Math",
".",
"max",
"(",
"0",
",",
"segment",
".",
"outerWidth",
"-",
"segment",
".",
"hsides",
")",
")",
";",
"}",
")",
";",
"// Grab each element's outerHeight (setVerticals uses this).",
"// To get an accurate reading, it's important to have each element's width explicitly set already.",
"segmentElementEach",
"(",
"segments",
",",
"function",
"(",
"segment",
",",
"element",
")",
"{",
"segment",
".",
"outerHeight",
"=",
"element",
".",
"outerHeight",
"(",
"true",
")",
";",
"// include margins = `true`",
"}",
")",
";",
"// Set the top coordinate on each element (requires segment.outerHeight)",
"setVerticals",
"(",
"segments",
",",
"doRowHeights",
")",
";",
"return",
"segments",
";",
"}"
] |
Render events onto the calendar. Only responsible for the VISUAL aspect. Not responsible for attaching handlers or calling callbacks. Set `doAppend` to `true` for rendering elements without clearing the existing container. Set `doRowHeights` to allow setting the height of each row, to compensate for vertical event overflow.
|
[
"Render",
"events",
"onto",
"the",
"calendar",
".",
"Only",
"responsible",
"for",
"the",
"VISUAL",
"aspect",
".",
"Not",
"responsible",
"for",
"attaching",
"handlers",
"or",
"calling",
"callbacks",
".",
"Set",
"doAppend",
"to",
"true",
"for",
"rendering",
"elements",
"without",
"clearing",
"the",
"existing",
"container",
".",
"Set",
"doRowHeights",
"to",
"allow",
"setting",
"the",
"height",
"of",
"each",
"row",
"to",
"compensate",
"for",
"vertical",
"event",
"overflow",
"."
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5186-L5245
|
37,407 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/fullcalendar.js
|
buildSegments
|
function buildSegments(events) {
var segments = [];
for (var i=0; i<events.length; i++) {
var eventSegments = buildSegmentsForEvent(events[i]);
segments.push.apply(segments, eventSegments); // append an array to an array
}
return segments;
}
|
javascript
|
function buildSegments(events) {
var segments = [];
for (var i=0; i<events.length; i++) {
var eventSegments = buildSegmentsForEvent(events[i]);
segments.push.apply(segments, eventSegments); // append an array to an array
}
return segments;
}
|
[
"function",
"buildSegments",
"(",
"events",
")",
"{",
"var",
"segments",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"events",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"eventSegments",
"=",
"buildSegmentsForEvent",
"(",
"events",
"[",
"i",
"]",
")",
";",
"segments",
".",
"push",
".",
"apply",
"(",
"segments",
",",
"eventSegments",
")",
";",
"// append an array to an array",
"}",
"return",
"segments",
";",
"}"
] |
Generate an array of "segments" for all events.
|
[
"Generate",
"an",
"array",
"of",
"segments",
"for",
"all",
"events",
"."
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5249-L5256
|
37,408 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/fullcalendar.js
|
buildSegmentsForEvent
|
function buildSegmentsForEvent(event) {
var startDate = event.start;
var endDate = exclEndDay(event);
var segments = rangeToSegments(startDate, endDate);
for (var i=0; i<segments.length; i++) {
segments[i].event = event;
}
return segments;
}
|
javascript
|
function buildSegmentsForEvent(event) {
var startDate = event.start;
var endDate = exclEndDay(event);
var segments = rangeToSegments(startDate, endDate);
for (var i=0; i<segments.length; i++) {
segments[i].event = event;
}
return segments;
}
|
[
"function",
"buildSegmentsForEvent",
"(",
"event",
")",
"{",
"var",
"startDate",
"=",
"event",
".",
"start",
";",
"var",
"endDate",
"=",
"exclEndDay",
"(",
"event",
")",
";",
"var",
"segments",
"=",
"rangeToSegments",
"(",
"startDate",
",",
"endDate",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"segments",
".",
"length",
";",
"i",
"++",
")",
"{",
"segments",
"[",
"i",
"]",
".",
"event",
"=",
"event",
";",
"}",
"return",
"segments",
";",
"}"
] |
Generate an array of segments for a single event. A "segment" is the same data structure that View.rangeToSegments produces, with the addition of the `event` property being set to reference the original event.
|
[
"Generate",
"an",
"array",
"of",
"segments",
"for",
"a",
"single",
"event",
".",
"A",
"segment",
"is",
"the",
"same",
"data",
"structure",
"that",
"View",
".",
"rangeToSegments",
"produces",
"with",
"the",
"addition",
"of",
"the",
"event",
"property",
"being",
"set",
"to",
"reference",
"the",
"original",
"event",
"."
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5262-L5270
|
37,409 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/fullcalendar.js
|
calculateHorizontals
|
function calculateHorizontals(segments) {
var isRTL = opt('isRTL');
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
// Determine functions used for calulating the elements left/right coordinates,
// depending on whether the view is RTL or not.
// NOTE:
// colLeft/colRight returns the coordinate butting up the edge of the cell.
// colContentLeft/colContentRight is indented a little bit from the edge.
var leftFunc = (isRTL ? segment.isEnd : segment.isStart) ? colContentLeft : colLeft;
var rightFunc = (isRTL ? segment.isStart : segment.isEnd) ? colContentRight : colRight;
var left = leftFunc(segment.leftCol);
var right = rightFunc(segment.rightCol);
segment.left = left;
segment.outerWidth = right - left;
}
}
|
javascript
|
function calculateHorizontals(segments) {
var isRTL = opt('isRTL');
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
// Determine functions used for calulating the elements left/right coordinates,
// depending on whether the view is RTL or not.
// NOTE:
// colLeft/colRight returns the coordinate butting up the edge of the cell.
// colContentLeft/colContentRight is indented a little bit from the edge.
var leftFunc = (isRTL ? segment.isEnd : segment.isStart) ? colContentLeft : colLeft;
var rightFunc = (isRTL ? segment.isStart : segment.isEnd) ? colContentRight : colRight;
var left = leftFunc(segment.leftCol);
var right = rightFunc(segment.rightCol);
segment.left = left;
segment.outerWidth = right - left;
}
}
|
[
"function",
"calculateHorizontals",
"(",
"segments",
")",
"{",
"var",
"isRTL",
"=",
"opt",
"(",
"'isRTL'",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"segments",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"segment",
"=",
"segments",
"[",
"i",
"]",
";",
"// Determine functions used for calulating the elements left/right coordinates,",
"// depending on whether the view is RTL or not.",
"// NOTE:",
"// colLeft/colRight returns the coordinate butting up the edge of the cell.",
"// colContentLeft/colContentRight is indented a little bit from the edge.",
"var",
"leftFunc",
"=",
"(",
"isRTL",
"?",
"segment",
".",
"isEnd",
":",
"segment",
".",
"isStart",
")",
"?",
"colContentLeft",
":",
"colLeft",
";",
"var",
"rightFunc",
"=",
"(",
"isRTL",
"?",
"segment",
".",
"isStart",
":",
"segment",
".",
"isEnd",
")",
"?",
"colContentRight",
":",
"colRight",
";",
"var",
"left",
"=",
"leftFunc",
"(",
"segment",
".",
"leftCol",
")",
";",
"var",
"right",
"=",
"rightFunc",
"(",
"segment",
".",
"rightCol",
")",
";",
"segment",
".",
"left",
"=",
"left",
";",
"segment",
".",
"outerWidth",
"=",
"right",
"-",
"left",
";",
"}",
"}"
] |
Sets the `left` and `outerWidth` property of each segment. These values are the desired dimensions for the eventual DOM elements.
|
[
"Sets",
"the",
"left",
"and",
"outerWidth",
"property",
"of",
"each",
"segment",
".",
"These",
"values",
"are",
"the",
"desired",
"dimensions",
"for",
"the",
"eventual",
"DOM",
"elements",
"."
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5275-L5293
|
37,410 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/fullcalendar.js
|
buildHTML
|
function buildHTML(segments) {
var html = '';
for (var i=0; i<segments.length; i++) {
html += buildHTMLForSegment(segments[i]);
}
return html;
}
|
javascript
|
function buildHTML(segments) {
var html = '';
for (var i=0; i<segments.length; i++) {
html += buildHTMLForSegment(segments[i]);
}
return html;
}
|
[
"function",
"buildHTML",
"(",
"segments",
")",
"{",
"var",
"html",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"segments",
".",
"length",
";",
"i",
"++",
")",
"{",
"html",
"+=",
"buildHTMLForSegment",
"(",
"segments",
"[",
"i",
"]",
")",
";",
"}",
"return",
"html",
";",
"}"
] |
Build a concatenated HTML string for an array of segments
|
[
"Build",
"a",
"concatenated",
"HTML",
"string",
"for",
"an",
"array",
"of",
"segments"
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5297-L5303
|
37,411 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/fullcalendar.js
|
setVerticals
|
function setVerticals(segments, doRowHeights) {
var rowContentHeights = calculateVerticals(segments); // also sets segment.top
var rowContentElements = getRowContentElements(); // returns 1 inner div per row
var rowContentTops = [];
// Set each row's height by setting height of first inner div
if (doRowHeights) {
for (var i=0; i<rowContentElements.length; i++) {
rowContentElements[i].height(rowContentHeights[i]);
}
}
// Get each row's top, relative to the views's origin.
// Important to do this after setting each row's height.
for (var i=0; i<rowContentElements.length; i++) {
rowContentTops.push(
rowContentElements[i].position().top
);
}
// Set each segment element's CSS "top" property.
// Each segment object has a "top" property, which is relative to the row's top, but...
segmentElementEach(segments, function(segment, element) {
element.css(
'top',
rowContentTops[segment.row] + segment.top // ...now, relative to views's origin
);
});
}
|
javascript
|
function setVerticals(segments, doRowHeights) {
var rowContentHeights = calculateVerticals(segments); // also sets segment.top
var rowContentElements = getRowContentElements(); // returns 1 inner div per row
var rowContentTops = [];
// Set each row's height by setting height of first inner div
if (doRowHeights) {
for (var i=0; i<rowContentElements.length; i++) {
rowContentElements[i].height(rowContentHeights[i]);
}
}
// Get each row's top, relative to the views's origin.
// Important to do this after setting each row's height.
for (var i=0; i<rowContentElements.length; i++) {
rowContentTops.push(
rowContentElements[i].position().top
);
}
// Set each segment element's CSS "top" property.
// Each segment object has a "top" property, which is relative to the row's top, but...
segmentElementEach(segments, function(segment, element) {
element.css(
'top',
rowContentTops[segment.row] + segment.top // ...now, relative to views's origin
);
});
}
|
[
"function",
"setVerticals",
"(",
"segments",
",",
"doRowHeights",
")",
"{",
"var",
"rowContentHeights",
"=",
"calculateVerticals",
"(",
"segments",
")",
";",
"// also sets segment.top",
"var",
"rowContentElements",
"=",
"getRowContentElements",
"(",
")",
";",
"// returns 1 inner div per row",
"var",
"rowContentTops",
"=",
"[",
"]",
";",
"// Set each row's height by setting height of first inner div",
"if",
"(",
"doRowHeights",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"rowContentElements",
".",
"length",
";",
"i",
"++",
")",
"{",
"rowContentElements",
"[",
"i",
"]",
".",
"height",
"(",
"rowContentHeights",
"[",
"i",
"]",
")",
";",
"}",
"}",
"// Get each row's top, relative to the views's origin.",
"// Important to do this after setting each row's height.",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"rowContentElements",
".",
"length",
";",
"i",
"++",
")",
"{",
"rowContentTops",
".",
"push",
"(",
"rowContentElements",
"[",
"i",
"]",
".",
"position",
"(",
")",
".",
"top",
")",
";",
"}",
"// Set each segment element's CSS \"top\" property.",
"// Each segment object has a \"top\" property, which is relative to the row's top, but...",
"segmentElementEach",
"(",
"segments",
",",
"function",
"(",
"segment",
",",
"element",
")",
"{",
"element",
".",
"css",
"(",
"'top'",
",",
"rowContentTops",
"[",
"segment",
".",
"row",
"]",
"+",
"segment",
".",
"top",
"// ...now, relative to views's origin",
")",
";",
"}",
")",
";",
"}"
] |
Sets the "top" CSS property for each element. If `doRowHeights` is `true`, also sets each row's first cell to an explicit height, so that if elements vertically overflow, the cell expands vertically to compensate.
|
[
"Sets",
"the",
"top",
"CSS",
"property",
"for",
"each",
"element",
".",
"If",
"doRowHeights",
"is",
"true",
"also",
"sets",
"each",
"row",
"s",
"first",
"cell",
"to",
"an",
"explicit",
"height",
"so",
"that",
"if",
"elements",
"vertically",
"overflow",
"the",
"cell",
"expands",
"vertically",
"to",
"compensate",
"."
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5430-L5458
|
37,412 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/fullcalendar.js
|
buildSegmentRows
|
function buildSegmentRows(segments) {
var rowCnt = getRowCnt();
var segmentRows = [];
var segmentI;
var segment;
var rowI;
// group segments by row
for (segmentI=0; segmentI<segments.length; segmentI++) {
segment = segments[segmentI];
rowI = segment.row;
if (segment.element) { // was rendered?
if (segmentRows[rowI]) {
// already other segments. append to array
segmentRows[rowI].push(segment);
}
else {
// first segment in row. create new array
segmentRows[rowI] = [ segment ];
}
}
}
// sort each row
for (rowI=0; rowI<rowCnt; rowI++) {
segmentRows[rowI] = sortSegmentRow(
segmentRows[rowI] || [] // guarantee an array, even if no segments
);
}
return segmentRows;
}
|
javascript
|
function buildSegmentRows(segments) {
var rowCnt = getRowCnt();
var segmentRows = [];
var segmentI;
var segment;
var rowI;
// group segments by row
for (segmentI=0; segmentI<segments.length; segmentI++) {
segment = segments[segmentI];
rowI = segment.row;
if (segment.element) { // was rendered?
if (segmentRows[rowI]) {
// already other segments. append to array
segmentRows[rowI].push(segment);
}
else {
// first segment in row. create new array
segmentRows[rowI] = [ segment ];
}
}
}
// sort each row
for (rowI=0; rowI<rowCnt; rowI++) {
segmentRows[rowI] = sortSegmentRow(
segmentRows[rowI] || [] // guarantee an array, even if no segments
);
}
return segmentRows;
}
|
[
"function",
"buildSegmentRows",
"(",
"segments",
")",
"{",
"var",
"rowCnt",
"=",
"getRowCnt",
"(",
")",
";",
"var",
"segmentRows",
"=",
"[",
"]",
";",
"var",
"segmentI",
";",
"var",
"segment",
";",
"var",
"rowI",
";",
"// group segments by row",
"for",
"(",
"segmentI",
"=",
"0",
";",
"segmentI",
"<",
"segments",
".",
"length",
";",
"segmentI",
"++",
")",
"{",
"segment",
"=",
"segments",
"[",
"segmentI",
"]",
";",
"rowI",
"=",
"segment",
".",
"row",
";",
"if",
"(",
"segment",
".",
"element",
")",
"{",
"// was rendered?",
"if",
"(",
"segmentRows",
"[",
"rowI",
"]",
")",
"{",
"// already other segments. append to array",
"segmentRows",
"[",
"rowI",
"]",
".",
"push",
"(",
"segment",
")",
";",
"}",
"else",
"{",
"// first segment in row. create new array",
"segmentRows",
"[",
"rowI",
"]",
"=",
"[",
"segment",
"]",
";",
"}",
"}",
"}",
"// sort each row",
"for",
"(",
"rowI",
"=",
"0",
";",
"rowI",
"<",
"rowCnt",
";",
"rowI",
"++",
")",
"{",
"segmentRows",
"[",
"rowI",
"]",
"=",
"sortSegmentRow",
"(",
"segmentRows",
"[",
"rowI",
"]",
"||",
"[",
"]",
"// guarantee an array, even if no segments",
")",
";",
"}",
"return",
"segmentRows",
";",
"}"
] |
Build an array of segment arrays, each representing the segments that will be in a row of the grid, sorted by which event should be closest to the top.
|
[
"Build",
"an",
"array",
"of",
"segment",
"arrays",
"each",
"representing",
"the",
"segments",
"that",
"will",
"be",
"in",
"a",
"row",
"of",
"the",
"grid",
"sorted",
"by",
"which",
"event",
"should",
"be",
"closest",
"to",
"the",
"top",
"."
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5510-L5541
|
37,413 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/fullcalendar.js
|
sortSegmentRow
|
function sortSegmentRow(segments) {
var sortedSegments = [];
// build the subrow array
var subrows = buildSegmentSubrows(segments);
// flatten it
for (var i=0; i<subrows.length; i++) {
sortedSegments.push.apply(sortedSegments, subrows[i]); // append an array to an array
}
return sortedSegments;
}
|
javascript
|
function sortSegmentRow(segments) {
var sortedSegments = [];
// build the subrow array
var subrows = buildSegmentSubrows(segments);
// flatten it
for (var i=0; i<subrows.length; i++) {
sortedSegments.push.apply(sortedSegments, subrows[i]); // append an array to an array
}
return sortedSegments;
}
|
[
"function",
"sortSegmentRow",
"(",
"segments",
")",
"{",
"var",
"sortedSegments",
"=",
"[",
"]",
";",
"// build the subrow array",
"var",
"subrows",
"=",
"buildSegmentSubrows",
"(",
"segments",
")",
";",
"// flatten it",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"subrows",
".",
"length",
";",
"i",
"++",
")",
"{",
"sortedSegments",
".",
"push",
".",
"apply",
"(",
"sortedSegments",
",",
"subrows",
"[",
"i",
"]",
")",
";",
"// append an array to an array",
"}",
"return",
"sortedSegments",
";",
"}"
] |
Sort an array of segments according to which segment should appear closest to the top
|
[
"Sort",
"an",
"array",
"of",
"segments",
"according",
"to",
"which",
"segment",
"should",
"appear",
"closest",
"to",
"the",
"top"
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5545-L5557
|
37,414 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/fullcalendar.js
|
buildSegmentSubrows
|
function buildSegmentSubrows(segments) {
// Give preference to elements with certain criteria, so they have
// a chance to be closer to the top.
segments.sort(compareDaySegments);
var subrows = [];
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
// loop through subrows, starting with the topmost, until the segment
// doesn't collide with other segments.
for (var j=0; j<subrows.length; j++) {
if (!isDaySegmentCollision(segment, subrows[j])) {
break;
}
}
// `j` now holds the desired subrow index
if (subrows[j]) {
subrows[j].push(segment);
}
else {
subrows[j] = [ segment ];
}
}
return subrows;
}
|
javascript
|
function buildSegmentSubrows(segments) {
// Give preference to elements with certain criteria, so they have
// a chance to be closer to the top.
segments.sort(compareDaySegments);
var subrows = [];
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
// loop through subrows, starting with the topmost, until the segment
// doesn't collide with other segments.
for (var j=0; j<subrows.length; j++) {
if (!isDaySegmentCollision(segment, subrows[j])) {
break;
}
}
// `j` now holds the desired subrow index
if (subrows[j]) {
subrows[j].push(segment);
}
else {
subrows[j] = [ segment ];
}
}
return subrows;
}
|
[
"function",
"buildSegmentSubrows",
"(",
"segments",
")",
"{",
"// Give preference to elements with certain criteria, so they have",
"// a chance to be closer to the top.",
"segments",
".",
"sort",
"(",
"compareDaySegments",
")",
";",
"var",
"subrows",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"segments",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"segment",
"=",
"segments",
"[",
"i",
"]",
";",
"// loop through subrows, starting with the topmost, until the segment",
"// doesn't collide with other segments.",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"subrows",
".",
"length",
";",
"j",
"++",
")",
"{",
"if",
"(",
"!",
"isDaySegmentCollision",
"(",
"segment",
",",
"subrows",
"[",
"j",
"]",
")",
")",
"{",
"break",
";",
"}",
"}",
"// `j` now holds the desired subrow index",
"if",
"(",
"subrows",
"[",
"j",
"]",
")",
"{",
"subrows",
"[",
"j",
"]",
".",
"push",
"(",
"segment",
")",
";",
"}",
"else",
"{",
"subrows",
"[",
"j",
"]",
"=",
"[",
"segment",
"]",
";",
"}",
"}",
"return",
"subrows",
";",
"}"
] |
Take an array of segments, which are all assumed to be in the same row, and sort into subrows.
|
[
"Take",
"an",
"array",
"of",
"segments",
"which",
"are",
"all",
"assumed",
"to",
"be",
"in",
"the",
"same",
"row",
"and",
"sort",
"into",
"subrows",
"."
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5562-L5589
|
37,415 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/fullcalendar.js
|
getRowContentElements
|
function getRowContentElements() {
var i;
var rowCnt = getRowCnt();
var rowDivs = [];
for (i=0; i<rowCnt; i++) {
rowDivs[i] = allDayRow(i)
.find('div.fc-day-content > div');
}
return rowDivs;
}
|
javascript
|
function getRowContentElements() {
var i;
var rowCnt = getRowCnt();
var rowDivs = [];
for (i=0; i<rowCnt; i++) {
rowDivs[i] = allDayRow(i)
.find('div.fc-day-content > div');
}
return rowDivs;
}
|
[
"function",
"getRowContentElements",
"(",
")",
"{",
"var",
"i",
";",
"var",
"rowCnt",
"=",
"getRowCnt",
"(",
")",
";",
"var",
"rowDivs",
"=",
"[",
"]",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"rowCnt",
";",
"i",
"++",
")",
"{",
"rowDivs",
"[",
"i",
"]",
"=",
"allDayRow",
"(",
"i",
")",
".",
"find",
"(",
"'div.fc-day-content > div'",
")",
";",
"}",
"return",
"rowDivs",
";",
"}"
] |
Return an array of jQuery objects for the placeholder content containers of each row. The content containers don't actually contain anything, but their dimensions should match the events that are overlaid on top.
|
[
"Return",
"an",
"array",
"of",
"jQuery",
"objects",
"for",
"the",
"placeholder",
"content",
"containers",
"of",
"each",
"row",
".",
"The",
"content",
"containers",
"don",
"t",
"actually",
"contain",
"anything",
"but",
"their",
"dimensions",
"should",
"match",
"the",
"events",
"that",
"are",
"overlaid",
"on",
"top",
"."
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5595-L5604
|
37,416 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/fullcalendar.js
|
compareDaySegments
|
function compareDaySegments(a, b) {
return (b.rightCol - b.leftCol) - (a.rightCol - a.leftCol) || // put wider events first
b.event.allDay - a.event.allDay || // if tie, put all-day events first (booleans cast to 0/1)
a.event.start - b.event.start || // if a tie, sort by event start date
(a.event.title || '').localeCompare(b.event.title) // if a tie, sort by event title
}
|
javascript
|
function compareDaySegments(a, b) {
return (b.rightCol - b.leftCol) - (a.rightCol - a.leftCol) || // put wider events first
b.event.allDay - a.event.allDay || // if tie, put all-day events first (booleans cast to 0/1)
a.event.start - b.event.start || // if a tie, sort by event start date
(a.event.title || '').localeCompare(b.event.title) // if a tie, sort by event title
}
|
[
"function",
"compareDaySegments",
"(",
"a",
",",
"b",
")",
"{",
"return",
"(",
"b",
".",
"rightCol",
"-",
"b",
".",
"leftCol",
")",
"-",
"(",
"a",
".",
"rightCol",
"-",
"a",
".",
"leftCol",
")",
"||",
"// put wider events first",
"b",
".",
"event",
".",
"allDay",
"-",
"a",
".",
"event",
".",
"allDay",
"||",
"// if tie, put all-day events first (booleans cast to 0/1)",
"a",
".",
"event",
".",
"start",
"-",
"b",
".",
"event",
".",
"start",
"||",
"// if a tie, sort by event start date",
"(",
"a",
".",
"event",
".",
"title",
"||",
"''",
")",
".",
"localeCompare",
"(",
"b",
".",
"event",
".",
"title",
")",
"// if a tie, sort by event title",
"}"
] |
A cmp function for determining which segments should appear higher up
|
[
"A",
"cmp",
"function",
"for",
"determining",
"which",
"segments",
"should",
"appear",
"higher",
"up"
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5824-L5829
|
37,417 |
carsdotcom/windshieldjs
|
lib/buildTemplateData.composer.js
|
composer
|
function composer(componentMap) {
return buildTemplateData;
/**
* Accepts a Hapi request object (containing Windshield config information) and
* resolves everything Hapi/Vision needs to render an HTML page.
*
* @callback {buildTemplateData}
* @param {Request} request - Hapi request object
* @returns {Promise.<TemplateData>}
*/
async function buildTemplateData(request) {
const filterFn = composePageFilter(request);
const pageContext = await resolvePageContext(request);
const renderer = componentMap.composeFactory(pageContext, request);
const renderedComponentCollection = await renderComponentSchema(pageContext.associations, renderer);
// we only need the data to be in this intermediary format to support
// the filtering logic. We should streamline this out but that would
// be a breaking change.
const rawPageObject = {
attributes: pageContext.attributes,
assoc: renderedComponentCollection,
layout: pageContext.layout,
exported: renderedComponentCollection.exportedData
};
if (process.env.WINDSHIELD_DEBUG) {
request.server.log('info', JSON.stringify(rawPageObject, null, 4));
}
const {assoc, attributes, layout} = await filterFn(rawPageObject);
const template = path.join('layouts', layout);
return {
template,
data: {
attributes,
assoc: assoc.markup,
exported: assoc.exported
}
};
}
}
|
javascript
|
function composer(componentMap) {
return buildTemplateData;
/**
* Accepts a Hapi request object (containing Windshield config information) and
* resolves everything Hapi/Vision needs to render an HTML page.
*
* @callback {buildTemplateData}
* @param {Request} request - Hapi request object
* @returns {Promise.<TemplateData>}
*/
async function buildTemplateData(request) {
const filterFn = composePageFilter(request);
const pageContext = await resolvePageContext(request);
const renderer = componentMap.composeFactory(pageContext, request);
const renderedComponentCollection = await renderComponentSchema(pageContext.associations, renderer);
// we only need the data to be in this intermediary format to support
// the filtering logic. We should streamline this out but that would
// be a breaking change.
const rawPageObject = {
attributes: pageContext.attributes,
assoc: renderedComponentCollection,
layout: pageContext.layout,
exported: renderedComponentCollection.exportedData
};
if (process.env.WINDSHIELD_DEBUG) {
request.server.log('info', JSON.stringify(rawPageObject, null, 4));
}
const {assoc, attributes, layout} = await filterFn(rawPageObject);
const template = path.join('layouts', layout);
return {
template,
data: {
attributes,
assoc: assoc.markup,
exported: assoc.exported
}
};
}
}
|
[
"function",
"composer",
"(",
"componentMap",
")",
"{",
"return",
"buildTemplateData",
";",
"/**\n * Accepts a Hapi request object (containing Windshield config information) and\n * resolves everything Hapi/Vision needs to render an HTML page.\n *\n * @callback {buildTemplateData}\n * @param {Request} request - Hapi request object\n * @returns {Promise.<TemplateData>}\n */",
"async",
"function",
"buildTemplateData",
"(",
"request",
")",
"{",
"const",
"filterFn",
"=",
"composePageFilter",
"(",
"request",
")",
";",
"const",
"pageContext",
"=",
"await",
"resolvePageContext",
"(",
"request",
")",
";",
"const",
"renderer",
"=",
"componentMap",
".",
"composeFactory",
"(",
"pageContext",
",",
"request",
")",
";",
"const",
"renderedComponentCollection",
"=",
"await",
"renderComponentSchema",
"(",
"pageContext",
".",
"associations",
",",
"renderer",
")",
";",
"// we only need the data to be in this intermediary format to support",
"// the filtering logic. We should streamline this out but that would",
"// be a breaking change.",
"const",
"rawPageObject",
"=",
"{",
"attributes",
":",
"pageContext",
".",
"attributes",
",",
"assoc",
":",
"renderedComponentCollection",
",",
"layout",
":",
"pageContext",
".",
"layout",
",",
"exported",
":",
"renderedComponentCollection",
".",
"exportedData",
"}",
";",
"if",
"(",
"process",
".",
"env",
".",
"WINDSHIELD_DEBUG",
")",
"{",
"request",
".",
"server",
".",
"log",
"(",
"'info'",
",",
"JSON",
".",
"stringify",
"(",
"rawPageObject",
",",
"null",
",",
"4",
")",
")",
";",
"}",
"const",
"{",
"assoc",
",",
"attributes",
",",
"layout",
"}",
"=",
"await",
"filterFn",
"(",
"rawPageObject",
")",
";",
"const",
"template",
"=",
"path",
".",
"join",
"(",
"'layouts'",
",",
"layout",
")",
";",
"return",
"{",
"template",
",",
"data",
":",
"{",
"attributes",
",",
"assoc",
":",
"assoc",
".",
"markup",
",",
"exported",
":",
"assoc",
".",
"exported",
"}",
"}",
";",
"}",
"}"
] |
An object describing a template file and data that can be used to compile the template
@typedef {Object} TemplateData
@property {string} template - The path to a Handlebars template file
@property {object} data - The data that will be used to compile the template into HTML
@property {object} data.attributes
@property {object} data.exported
@property {Object.<string, string>} data.assoc - Hashmap of association names and HTML markup
Composes a function that processes a Hapi request using Windshield adapters and context.
We can't define the function we need at run-time, so this function will build it for
us when we're ready.
@param {ComponentMap} componentMap - Description of all available Windshield components
@returns {buildTemplateData}
|
[
"An",
"object",
"describing",
"a",
"template",
"file",
"and",
"data",
"that",
"can",
"be",
"used",
"to",
"compile",
"the",
"template"
] |
fddd841c5d9e09251437c9a30cc39700e5e4a1f6
|
https://github.com/carsdotcom/windshieldjs/blob/fddd841c5d9e09251437c9a30cc39700e5e4a1f6/lib/buildTemplateData.composer.js#L33-L77
|
37,418 |
carsdotcom/windshieldjs
|
lib/associationProcessorService.js
|
renderComponentSchema
|
async function renderComponentSchema(definitionMap, renderComponent) {
/**
* Renders a single Windshield component definition into a rendered
* component object
*
* @param {string} definitionGroupName - Name of the association that contains the component
* @param {ComponentDefinition} definition - Config for a Windshield Component
*
* @return {Promise.<RenderedComponent>}
*/
async function renderOneComponent(definitionGroupName, definition) {
const childDefinitionMap = definition.associations;
// replacing child definitions with rendered child components
definition.associations = await renderAssociationMap(childDefinitionMap);
// we can try to use the group name as a layout
definition.layout = definition.layout || definitionGroupName;
return renderComponent(definition);
}
/**
* Renders an array of component definitions by aggregating them
* into a single rendered component object
*
* @param {string} definitionGroupName - They key where the definitions are found in their parent component's associations
* @param {ComponentDefinition[]} definitionGroup - Array of configs for Windshield Components
* @returns {Promise.<RenderedComponent>}
*/
async function renderComponentFromArray(definitionGroupName, definitionGroup) {
const promises = definitionGroup.map((definintion) => renderOneComponent(definitionGroupName, definintion));
const renderedComponents = await Promise.all(promises);
const markup = [];
const exported = {};
renderedComponents.forEach(function (component) {
merge(exported, component.exported || {});
markup.push(component.markup);
});
const renderedComponentData = { markup: {}, exported};
renderedComponentData.markup[definitionGroupName] = markup.join("\n");
return renderedComponentData;
}
/**
* Iterates through the associations to produce a rendered component collection object
*
* @param {Object.<string, ComponentDefinition[]>} definitionMap - hashmap of arrays of component definitions
* @returns {Promise.<RenderedComponentCollection>}
*/
async function renderAssociationMap(definitionMap) {
if (!definitionMap) {
return {};
}
const definitionEntries = Object.entries(definitionMap);
const promises = definitionEntries.map(([groupName, definitionGroup]) => {
return renderComponentFromArray(groupName, definitionGroup);
});
const results = await Promise.all(promises);
const associationResults = {exported: {}, markup: {}};
return results.reduce(merge, associationResults);
}
return renderAssociationMap(definitionMap);
}
|
javascript
|
async function renderComponentSchema(definitionMap, renderComponent) {
/**
* Renders a single Windshield component definition into a rendered
* component object
*
* @param {string} definitionGroupName - Name of the association that contains the component
* @param {ComponentDefinition} definition - Config for a Windshield Component
*
* @return {Promise.<RenderedComponent>}
*/
async function renderOneComponent(definitionGroupName, definition) {
const childDefinitionMap = definition.associations;
// replacing child definitions with rendered child components
definition.associations = await renderAssociationMap(childDefinitionMap);
// we can try to use the group name as a layout
definition.layout = definition.layout || definitionGroupName;
return renderComponent(definition);
}
/**
* Renders an array of component definitions by aggregating them
* into a single rendered component object
*
* @param {string} definitionGroupName - They key where the definitions are found in their parent component's associations
* @param {ComponentDefinition[]} definitionGroup - Array of configs for Windshield Components
* @returns {Promise.<RenderedComponent>}
*/
async function renderComponentFromArray(definitionGroupName, definitionGroup) {
const promises = definitionGroup.map((definintion) => renderOneComponent(definitionGroupName, definintion));
const renderedComponents = await Promise.all(promises);
const markup = [];
const exported = {};
renderedComponents.forEach(function (component) {
merge(exported, component.exported || {});
markup.push(component.markup);
});
const renderedComponentData = { markup: {}, exported};
renderedComponentData.markup[definitionGroupName] = markup.join("\n");
return renderedComponentData;
}
/**
* Iterates through the associations to produce a rendered component collection object
*
* @param {Object.<string, ComponentDefinition[]>} definitionMap - hashmap of arrays of component definitions
* @returns {Promise.<RenderedComponentCollection>}
*/
async function renderAssociationMap(definitionMap) {
if (!definitionMap) {
return {};
}
const definitionEntries = Object.entries(definitionMap);
const promises = definitionEntries.map(([groupName, definitionGroup]) => {
return renderComponentFromArray(groupName, definitionGroup);
});
const results = await Promise.all(promises);
const associationResults = {exported: {}, markup: {}};
return results.reduce(merge, associationResults);
}
return renderAssociationMap(definitionMap);
}
|
[
"async",
"function",
"renderComponentSchema",
"(",
"definitionMap",
",",
"renderComponent",
")",
"{",
"/**\n * Renders a single Windshield component definition into a rendered\n * component object\n *\n * @param {string} definitionGroupName - Name of the association that contains the component\n * @param {ComponentDefinition} definition - Config for a Windshield Component\n *\n * @return {Promise.<RenderedComponent>}\n */",
"async",
"function",
"renderOneComponent",
"(",
"definitionGroupName",
",",
"definition",
")",
"{",
"const",
"childDefinitionMap",
"=",
"definition",
".",
"associations",
";",
"// replacing child definitions with rendered child components",
"definition",
".",
"associations",
"=",
"await",
"renderAssociationMap",
"(",
"childDefinitionMap",
")",
";",
"// we can try to use the group name as a layout",
"definition",
".",
"layout",
"=",
"definition",
".",
"layout",
"||",
"definitionGroupName",
";",
"return",
"renderComponent",
"(",
"definition",
")",
";",
"}",
"/**\n * Renders an array of component definitions by aggregating them\n * into a single rendered component object\n *\n * @param {string} definitionGroupName - They key where the definitions are found in their parent component's associations\n * @param {ComponentDefinition[]} definitionGroup - Array of configs for Windshield Components\n * @returns {Promise.<RenderedComponent>}\n */",
"async",
"function",
"renderComponentFromArray",
"(",
"definitionGroupName",
",",
"definitionGroup",
")",
"{",
"const",
"promises",
"=",
"definitionGroup",
".",
"map",
"(",
"(",
"definintion",
")",
"=>",
"renderOneComponent",
"(",
"definitionGroupName",
",",
"definintion",
")",
")",
";",
"const",
"renderedComponents",
"=",
"await",
"Promise",
".",
"all",
"(",
"promises",
")",
";",
"const",
"markup",
"=",
"[",
"]",
";",
"const",
"exported",
"=",
"{",
"}",
";",
"renderedComponents",
".",
"forEach",
"(",
"function",
"(",
"component",
")",
"{",
"merge",
"(",
"exported",
",",
"component",
".",
"exported",
"||",
"{",
"}",
")",
";",
"markup",
".",
"push",
"(",
"component",
".",
"markup",
")",
";",
"}",
")",
";",
"const",
"renderedComponentData",
"=",
"{",
"markup",
":",
"{",
"}",
",",
"exported",
"}",
";",
"renderedComponentData",
".",
"markup",
"[",
"definitionGroupName",
"]",
"=",
"markup",
".",
"join",
"(",
"\"\\n\"",
")",
";",
"return",
"renderedComponentData",
";",
"}",
"/**\n * Iterates through the associations to produce a rendered component collection object\n *\n * @param {Object.<string, ComponentDefinition[]>} definitionMap - hashmap of arrays of component definitions\n * @returns {Promise.<RenderedComponentCollection>}\n */",
"async",
"function",
"renderAssociationMap",
"(",
"definitionMap",
")",
"{",
"if",
"(",
"!",
"definitionMap",
")",
"{",
"return",
"{",
"}",
";",
"}",
"const",
"definitionEntries",
"=",
"Object",
".",
"entries",
"(",
"definitionMap",
")",
";",
"const",
"promises",
"=",
"definitionEntries",
".",
"map",
"(",
"(",
"[",
"groupName",
",",
"definitionGroup",
"]",
")",
"=>",
"{",
"return",
"renderComponentFromArray",
"(",
"groupName",
",",
"definitionGroup",
")",
";",
"}",
")",
";",
"const",
"results",
"=",
"await",
"Promise",
".",
"all",
"(",
"promises",
")",
";",
"const",
"associationResults",
"=",
"{",
"exported",
":",
"{",
"}",
",",
"markup",
":",
"{",
"}",
"}",
";",
"return",
"results",
".",
"reduce",
"(",
"merge",
",",
"associationResults",
")",
";",
"}",
"return",
"renderAssociationMap",
"(",
"definitionMap",
")",
";",
"}"
] |
Renders a schema of Windshield component definitions into a schema of
rendered Windshield components.
This method traverses the scheme, processing each component definition using
the same rendering method. A component definition may contain an associations
property, whose value is a hashmap containing arrays of child definitions.
@param {Object.<string, ComponentDefinition[]>} definitionMap - hashmap of arrays of component definitions
@param {componentFactory} renderComponent - The renderer function that will be used to render every component.
@returns {Promise.<RenderedComponentCollection>}
|
[
"Renders",
"a",
"schema",
"of",
"Windshield",
"component",
"definitions",
"into",
"a",
"schema",
"of",
"rendered",
"Windshield",
"components",
"."
] |
fddd841c5d9e09251437c9a30cc39700e5e4a1f6
|
https://github.com/carsdotcom/windshieldjs/blob/fddd841c5d9e09251437c9a30cc39700e5e4a1f6/lib/associationProcessorService.js#L17-L90
|
37,419 |
carsdotcom/windshieldjs
|
lib/associationProcessorService.js
|
renderOneComponent
|
async function renderOneComponent(definitionGroupName, definition) {
const childDefinitionMap = definition.associations;
// replacing child definitions with rendered child components
definition.associations = await renderAssociationMap(childDefinitionMap);
// we can try to use the group name as a layout
definition.layout = definition.layout || definitionGroupName;
return renderComponent(definition);
}
|
javascript
|
async function renderOneComponent(definitionGroupName, definition) {
const childDefinitionMap = definition.associations;
// replacing child definitions with rendered child components
definition.associations = await renderAssociationMap(childDefinitionMap);
// we can try to use the group name as a layout
definition.layout = definition.layout || definitionGroupName;
return renderComponent(definition);
}
|
[
"async",
"function",
"renderOneComponent",
"(",
"definitionGroupName",
",",
"definition",
")",
"{",
"const",
"childDefinitionMap",
"=",
"definition",
".",
"associations",
";",
"// replacing child definitions with rendered child components",
"definition",
".",
"associations",
"=",
"await",
"renderAssociationMap",
"(",
"childDefinitionMap",
")",
";",
"// we can try to use the group name as a layout",
"definition",
".",
"layout",
"=",
"definition",
".",
"layout",
"||",
"definitionGroupName",
";",
"return",
"renderComponent",
"(",
"definition",
")",
";",
"}"
] |
Renders a single Windshield component definition into a rendered
component object
@param {string} definitionGroupName - Name of the association that contains the component
@param {ComponentDefinition} definition - Config for a Windshield Component
@return {Promise.<RenderedComponent>}
|
[
"Renders",
"a",
"single",
"Windshield",
"component",
"definition",
"into",
"a",
"rendered",
"component",
"object"
] |
fddd841c5d9e09251437c9a30cc39700e5e4a1f6
|
https://github.com/carsdotcom/windshieldjs/blob/fddd841c5d9e09251437c9a30cc39700e5e4a1f6/lib/associationProcessorService.js#L27-L37
|
37,420 |
carsdotcom/windshieldjs
|
lib/associationProcessorService.js
|
renderComponentFromArray
|
async function renderComponentFromArray(definitionGroupName, definitionGroup) {
const promises = definitionGroup.map((definintion) => renderOneComponent(definitionGroupName, definintion));
const renderedComponents = await Promise.all(promises);
const markup = [];
const exported = {};
renderedComponents.forEach(function (component) {
merge(exported, component.exported || {});
markup.push(component.markup);
});
const renderedComponentData = { markup: {}, exported};
renderedComponentData.markup[definitionGroupName] = markup.join("\n");
return renderedComponentData;
}
|
javascript
|
async function renderComponentFromArray(definitionGroupName, definitionGroup) {
const promises = definitionGroup.map((definintion) => renderOneComponent(definitionGroupName, definintion));
const renderedComponents = await Promise.all(promises);
const markup = [];
const exported = {};
renderedComponents.forEach(function (component) {
merge(exported, component.exported || {});
markup.push(component.markup);
});
const renderedComponentData = { markup: {}, exported};
renderedComponentData.markup[definitionGroupName] = markup.join("\n");
return renderedComponentData;
}
|
[
"async",
"function",
"renderComponentFromArray",
"(",
"definitionGroupName",
",",
"definitionGroup",
")",
"{",
"const",
"promises",
"=",
"definitionGroup",
".",
"map",
"(",
"(",
"definintion",
")",
"=>",
"renderOneComponent",
"(",
"definitionGroupName",
",",
"definintion",
")",
")",
";",
"const",
"renderedComponents",
"=",
"await",
"Promise",
".",
"all",
"(",
"promises",
")",
";",
"const",
"markup",
"=",
"[",
"]",
";",
"const",
"exported",
"=",
"{",
"}",
";",
"renderedComponents",
".",
"forEach",
"(",
"function",
"(",
"component",
")",
"{",
"merge",
"(",
"exported",
",",
"component",
".",
"exported",
"||",
"{",
"}",
")",
";",
"markup",
".",
"push",
"(",
"component",
".",
"markup",
")",
";",
"}",
")",
";",
"const",
"renderedComponentData",
"=",
"{",
"markup",
":",
"{",
"}",
",",
"exported",
"}",
";",
"renderedComponentData",
".",
"markup",
"[",
"definitionGroupName",
"]",
"=",
"markup",
".",
"join",
"(",
"\"\\n\"",
")",
";",
"return",
"renderedComponentData",
";",
"}"
] |
Renders an array of component definitions by aggregating them
into a single rendered component object
@param {string} definitionGroupName - They key where the definitions are found in their parent component's associations
@param {ComponentDefinition[]} definitionGroup - Array of configs for Windshield Components
@returns {Promise.<RenderedComponent>}
|
[
"Renders",
"an",
"array",
"of",
"component",
"definitions",
"by",
"aggregating",
"them",
"into",
"a",
"single",
"rendered",
"component",
"object"
] |
fddd841c5d9e09251437c9a30cc39700e5e4a1f6
|
https://github.com/carsdotcom/windshieldjs/blob/fddd841c5d9e09251437c9a30cc39700e5e4a1f6/lib/associationProcessorService.js#L47-L64
|
37,421 |
carsdotcom/windshieldjs
|
lib/associationProcessorService.js
|
renderAssociationMap
|
async function renderAssociationMap(definitionMap) {
if (!definitionMap) {
return {};
}
const definitionEntries = Object.entries(definitionMap);
const promises = definitionEntries.map(([groupName, definitionGroup]) => {
return renderComponentFromArray(groupName, definitionGroup);
});
const results = await Promise.all(promises);
const associationResults = {exported: {}, markup: {}};
return results.reduce(merge, associationResults);
}
|
javascript
|
async function renderAssociationMap(definitionMap) {
if (!definitionMap) {
return {};
}
const definitionEntries = Object.entries(definitionMap);
const promises = definitionEntries.map(([groupName, definitionGroup]) => {
return renderComponentFromArray(groupName, definitionGroup);
});
const results = await Promise.all(promises);
const associationResults = {exported: {}, markup: {}};
return results.reduce(merge, associationResults);
}
|
[
"async",
"function",
"renderAssociationMap",
"(",
"definitionMap",
")",
"{",
"if",
"(",
"!",
"definitionMap",
")",
"{",
"return",
"{",
"}",
";",
"}",
"const",
"definitionEntries",
"=",
"Object",
".",
"entries",
"(",
"definitionMap",
")",
";",
"const",
"promises",
"=",
"definitionEntries",
".",
"map",
"(",
"(",
"[",
"groupName",
",",
"definitionGroup",
"]",
")",
"=>",
"{",
"return",
"renderComponentFromArray",
"(",
"groupName",
",",
"definitionGroup",
")",
";",
"}",
")",
";",
"const",
"results",
"=",
"await",
"Promise",
".",
"all",
"(",
"promises",
")",
";",
"const",
"associationResults",
"=",
"{",
"exported",
":",
"{",
"}",
",",
"markup",
":",
"{",
"}",
"}",
";",
"return",
"results",
".",
"reduce",
"(",
"merge",
",",
"associationResults",
")",
";",
"}"
] |
Iterates through the associations to produce a rendered component collection object
@param {Object.<string, ComponentDefinition[]>} definitionMap - hashmap of arrays of component definitions
@returns {Promise.<RenderedComponentCollection>}
|
[
"Iterates",
"through",
"the",
"associations",
"to",
"produce",
"a",
"rendered",
"component",
"collection",
"object"
] |
fddd841c5d9e09251437c9a30cc39700e5e4a1f6
|
https://github.com/carsdotcom/windshieldjs/blob/fddd841c5d9e09251437c9a30cc39700e5e4a1f6/lib/associationProcessorService.js#L72-L86
|
37,422 |
BohemiaInteractive/bi-service
|
lib/moduleLoader.js
|
fileIterator
|
function fileIterator(paths, options, callback) {
var filePacks = [];
if (typeof options === 'function') {
callback = options;
options = {};
}
if (typeof paths === 'string') {
paths = [paths];
} else if (paths instanceof Array) {
paths = [].concat(paths);
} else {
throw new Error('Invalid first argument `paths`. Expected type of string or array');
}
options = options || {};
var except = [];
//normalize paths
(options.except || []).forEach(function(p) {
except.push(path.resolve(p));
});
paths.forEach(function(p, index) {
if (fs.lstatSync(p).isDirectory()) {
filePacks.push(fs.readdirSync(p));
} else {
//explicit file paths are already complete,
filePacks.push([path.basename(p)]);
paths.splice(index, 1, path.dirname(p));
}
});
filePacks.forEach(function(files, index) {
files.forEach(function(file) {
var pth = path.join(paths[index], file);
var isDir = fs.lstatSync(pth).isDirectory();
//skip paths defined in options.except array
if (except.indexOf(pth) !== -1) {
return;
}
if (isDir) {
fileIterator([pth], options, callback);
} else {
callback(file, paths[index]);
}
});
});
}
|
javascript
|
function fileIterator(paths, options, callback) {
var filePacks = [];
if (typeof options === 'function') {
callback = options;
options = {};
}
if (typeof paths === 'string') {
paths = [paths];
} else if (paths instanceof Array) {
paths = [].concat(paths);
} else {
throw new Error('Invalid first argument `paths`. Expected type of string or array');
}
options = options || {};
var except = [];
//normalize paths
(options.except || []).forEach(function(p) {
except.push(path.resolve(p));
});
paths.forEach(function(p, index) {
if (fs.lstatSync(p).isDirectory()) {
filePacks.push(fs.readdirSync(p));
} else {
//explicit file paths are already complete,
filePacks.push([path.basename(p)]);
paths.splice(index, 1, path.dirname(p));
}
});
filePacks.forEach(function(files, index) {
files.forEach(function(file) {
var pth = path.join(paths[index], file);
var isDir = fs.lstatSync(pth).isDirectory();
//skip paths defined in options.except array
if (except.indexOf(pth) !== -1) {
return;
}
if (isDir) {
fileIterator([pth], options, callback);
} else {
callback(file, paths[index]);
}
});
});
}
|
[
"function",
"fileIterator",
"(",
"paths",
",",
"options",
",",
"callback",
")",
"{",
"var",
"filePacks",
"=",
"[",
"]",
";",
"if",
"(",
"typeof",
"options",
"===",
"'function'",
")",
"{",
"callback",
"=",
"options",
";",
"options",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"typeof",
"paths",
"===",
"'string'",
")",
"{",
"paths",
"=",
"[",
"paths",
"]",
";",
"}",
"else",
"if",
"(",
"paths",
"instanceof",
"Array",
")",
"{",
"paths",
"=",
"[",
"]",
".",
"concat",
"(",
"paths",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid first argument `paths`. Expected type of string or array'",
")",
";",
"}",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"except",
"=",
"[",
"]",
";",
"//normalize paths",
"(",
"options",
".",
"except",
"||",
"[",
"]",
")",
".",
"forEach",
"(",
"function",
"(",
"p",
")",
"{",
"except",
".",
"push",
"(",
"path",
".",
"resolve",
"(",
"p",
")",
")",
";",
"}",
")",
";",
"paths",
".",
"forEach",
"(",
"function",
"(",
"p",
",",
"index",
")",
"{",
"if",
"(",
"fs",
".",
"lstatSync",
"(",
"p",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"filePacks",
".",
"push",
"(",
"fs",
".",
"readdirSync",
"(",
"p",
")",
")",
";",
"}",
"else",
"{",
"//explicit file paths are already complete,",
"filePacks",
".",
"push",
"(",
"[",
"path",
".",
"basename",
"(",
"p",
")",
"]",
")",
";",
"paths",
".",
"splice",
"(",
"index",
",",
"1",
",",
"path",
".",
"dirname",
"(",
"p",
")",
")",
";",
"}",
"}",
")",
";",
"filePacks",
".",
"forEach",
"(",
"function",
"(",
"files",
",",
"index",
")",
"{",
"files",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"pth",
"=",
"path",
".",
"join",
"(",
"paths",
"[",
"index",
"]",
",",
"file",
")",
";",
"var",
"isDir",
"=",
"fs",
".",
"lstatSync",
"(",
"pth",
")",
".",
"isDirectory",
"(",
")",
";",
"//skip paths defined in options.except array",
"if",
"(",
"except",
".",
"indexOf",
"(",
"pth",
")",
"!==",
"-",
"1",
")",
"{",
"return",
";",
"}",
"if",
"(",
"isDir",
")",
"{",
"fileIterator",
"(",
"[",
"pth",
"]",
",",
"options",
",",
"callback",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"file",
",",
"paths",
"[",
"index",
"]",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] |
synchronous helper function
@function fileIterator
@memberof ModuleLoader
@static
@example
require('bi-service').moduleLoader.fileIterator
@param {Array|String} paths - file as well as directory paths
@param {Object} [options]
@param {Array} [options.except] - collection of files/directories that should be excluded
@param {Function} callback is provided with file (string), dirPath (string) arguments
@return {undefined}
|
[
"synchronous",
"helper",
"function"
] |
89e76f2e93714a3150ce7f59f16f646e4bdbbce1
|
https://github.com/BohemiaInteractive/bi-service/blob/89e76f2e93714a3150ce7f59f16f646e4bdbbce1/lib/moduleLoader.js#L70-L120
|
37,423 |
JsCommunity/hashy
|
index.js
|
getInfo
|
function getInfo(hash) {
const info = getHashInfo(hash);
const algo = getAlgorithmFromId(info.id);
info.algorithm = algo.name;
info.options = algo.getOptions(hash, info);
return info;
}
|
javascript
|
function getInfo(hash) {
const info = getHashInfo(hash);
const algo = getAlgorithmFromId(info.id);
info.algorithm = algo.name;
info.options = algo.getOptions(hash, info);
return info;
}
|
[
"function",
"getInfo",
"(",
"hash",
")",
"{",
"const",
"info",
"=",
"getHashInfo",
"(",
"hash",
")",
";",
"const",
"algo",
"=",
"getAlgorithmFromId",
"(",
"info",
".",
"id",
")",
";",
"info",
".",
"algorithm",
"=",
"algo",
".",
"name",
";",
"info",
".",
"options",
"=",
"algo",
".",
"getOptions",
"(",
"hash",
",",
"info",
")",
";",
"return",
"info",
";",
"}"
] |
Returns information about a hash.
@param {string} hash The hash you want to get information from.
@return {object} Object containing information about the given
hash: “algorithm”: the algorithm used, “options” the options
used.
|
[
"Returns",
"information",
"about",
"a",
"hash",
"."
] |
971c662e8ed11dcdaef3a176510552ec1e618a8b
|
https://github.com/JsCommunity/hashy/blob/971c662e8ed11dcdaef3a176510552ec1e618a8b/index.js#L232-L239
|
37,424 |
JsCommunity/hashy
|
index.js
|
needsRehash
|
function needsRehash(hash, algo, options) {
const info = getInfo(hash);
if (info.algorithm !== (algo || DEFAULT_ALGO)) {
return true;
}
const algoNeedsRehash = getAlgorithmFromId(info.id).needsRehash;
const result = algoNeedsRehash && algoNeedsRehash(hash, info);
if (typeof result === "boolean") {
return result;
}
const expected = Object.assign(
Object.create(null),
globalOptions[info.algorithm],
options
);
const actual = info.options;
for (const prop in actual) {
const value = actual[prop];
if (typeof value === "number" && value < expected[prop]) {
return true;
}
}
return false;
}
|
javascript
|
function needsRehash(hash, algo, options) {
const info = getInfo(hash);
if (info.algorithm !== (algo || DEFAULT_ALGO)) {
return true;
}
const algoNeedsRehash = getAlgorithmFromId(info.id).needsRehash;
const result = algoNeedsRehash && algoNeedsRehash(hash, info);
if (typeof result === "boolean") {
return result;
}
const expected = Object.assign(
Object.create(null),
globalOptions[info.algorithm],
options
);
const actual = info.options;
for (const prop in actual) {
const value = actual[prop];
if (typeof value === "number" && value < expected[prop]) {
return true;
}
}
return false;
}
|
[
"function",
"needsRehash",
"(",
"hash",
",",
"algo",
",",
"options",
")",
"{",
"const",
"info",
"=",
"getInfo",
"(",
"hash",
")",
";",
"if",
"(",
"info",
".",
"algorithm",
"!==",
"(",
"algo",
"||",
"DEFAULT_ALGO",
")",
")",
"{",
"return",
"true",
";",
"}",
"const",
"algoNeedsRehash",
"=",
"getAlgorithmFromId",
"(",
"info",
".",
"id",
")",
".",
"needsRehash",
";",
"const",
"result",
"=",
"algoNeedsRehash",
"&&",
"algoNeedsRehash",
"(",
"hash",
",",
"info",
")",
";",
"if",
"(",
"typeof",
"result",
"===",
"\"boolean\"",
")",
"{",
"return",
"result",
";",
"}",
"const",
"expected",
"=",
"Object",
".",
"assign",
"(",
"Object",
".",
"create",
"(",
"null",
")",
",",
"globalOptions",
"[",
"info",
".",
"algorithm",
"]",
",",
"options",
")",
";",
"const",
"actual",
"=",
"info",
".",
"options",
";",
"for",
"(",
"const",
"prop",
"in",
"actual",
")",
"{",
"const",
"value",
"=",
"actual",
"[",
"prop",
"]",
";",
"if",
"(",
"typeof",
"value",
"===",
"\"number\"",
"&&",
"value",
"<",
"expected",
"[",
"prop",
"]",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Checks whether the hash needs to be recomputed.
The hash should be recomputed if it does not use the given
algorithm and options.
@param {string} hash The hash to analyse.
@param {integer} algo The algorithm to use.
@param {options} options The options to use.
@return {boolean} Whether the hash needs to be recomputed.
|
[
"Checks",
"whether",
"the",
"hash",
"needs",
"to",
"be",
"recomputed",
"."
] |
971c662e8ed11dcdaef3a176510552ec1e618a8b
|
https://github.com/JsCommunity/hashy/blob/971c662e8ed11dcdaef3a176510552ec1e618a8b/index.js#L254-L282
|
37,425 |
youpinyao/angular-datepicker
|
app/scripts/datePickerUtils.js
|
function (targetIDs, pickerID) {
function matches(id) {
if (id instanceof RegExp) {
return id.test(pickerID);
}
return id === pickerID;
}
if (angular.isArray(targetIDs)) {
return targetIDs.some(matches);
}
return matches(targetIDs);
}
|
javascript
|
function (targetIDs, pickerID) {
function matches(id) {
if (id instanceof RegExp) {
return id.test(pickerID);
}
return id === pickerID;
}
if (angular.isArray(targetIDs)) {
return targetIDs.some(matches);
}
return matches(targetIDs);
}
|
[
"function",
"(",
"targetIDs",
",",
"pickerID",
")",
"{",
"function",
"matches",
"(",
"id",
")",
"{",
"if",
"(",
"id",
"instanceof",
"RegExp",
")",
"{",
"return",
"id",
".",
"test",
"(",
"pickerID",
")",
";",
"}",
"return",
"id",
"===",
"pickerID",
";",
"}",
"if",
"(",
"angular",
".",
"isArray",
"(",
"targetIDs",
")",
")",
"{",
"return",
"targetIDs",
".",
"some",
"(",
"matches",
")",
";",
"}",
"return",
"matches",
"(",
"targetIDs",
")",
";",
"}"
] |
Checks if an event targeted at a specific picker, via either a string name, or an array of strings.
|
[
"Checks",
"if",
"an",
"event",
"targeted",
"at",
"a",
"specific",
"picker",
"via",
"either",
"a",
"string",
"name",
"or",
"an",
"array",
"of",
"strings",
"."
] |
440489d5ecf6f64b6bc14fce78979206755e84fc
|
https://github.com/youpinyao/angular-datepicker/blob/440489d5ecf6f64b6bc14fce78979206755e84fc/app/scripts/datePickerUtils.js#L225-L237
|
|
37,426 |
joshfire/woodman
|
lib/filters/regexloggernamefilter.js
|
function (config) {
Filter.call(this);
config = config || {};
this.regex = config.regex || '';
if (utils.isString(this.regex)) {
this.regex = new RegExp(this.regex);
}
this.onMatch = config.match || config.onMatch || 'neutral';
this.onMismatch = config.mismatch || config.onMismatch || 'deny';
}
|
javascript
|
function (config) {
Filter.call(this);
config = config || {};
this.regex = config.regex || '';
if (utils.isString(this.regex)) {
this.regex = new RegExp(this.regex);
}
this.onMatch = config.match || config.onMatch || 'neutral';
this.onMismatch = config.mismatch || config.onMismatch || 'deny';
}
|
[
"function",
"(",
"config",
")",
"{",
"Filter",
".",
"call",
"(",
"this",
")",
";",
"config",
"=",
"config",
"||",
"{",
"}",
";",
"this",
".",
"regex",
"=",
"config",
".",
"regex",
"||",
"''",
";",
"if",
"(",
"utils",
".",
"isString",
"(",
"this",
".",
"regex",
")",
")",
"{",
"this",
".",
"regex",
"=",
"new",
"RegExp",
"(",
"this",
".",
"regex",
")",
";",
"}",
"this",
".",
"onMatch",
"=",
"config",
".",
"match",
"||",
"config",
".",
"onMatch",
"||",
"'neutral'",
";",
"this",
".",
"onMismatch",
"=",
"config",
".",
"mismatch",
"||",
"config",
".",
"onMismatch",
"||",
"'deny'",
";",
"}"
] |
Definition of the RegexFilter class.
@constructor
@param {Object} config Filter configuration. Possible configuration keys:
- regex: The regular expression to use. String or RegExp. Required.
- match: Decision to take when the event matches the regexp. String.
Default value is "accept".
- mismatch: Decision to take when the event does not match the regexp.
String. Default value is "neutral".
|
[
"Definition",
"of",
"the",
"RegexFilter",
"class",
"."
] |
fdc05de2124388780924980e6f27bf4483056d18
|
https://github.com/joshfire/woodman/blob/fdc05de2124388780924980e6f27bf4483056d18/lib/filters/regexloggernamefilter.js#L35-L46
|
|
37,427 |
neurosnap/gen-readlines
|
index.js
|
_concat
|
function _concat(buffOne, buffTwo) {
if (!buffOne) return buffTwo;
if (!buffTwo) return buffOne;
let newLength = buffOne.length + buffTwo.length;
return Buffer.concat([buffOne, buffTwo], newLength);
}
|
javascript
|
function _concat(buffOne, buffTwo) {
if (!buffOne) return buffTwo;
if (!buffTwo) return buffOne;
let newLength = buffOne.length + buffTwo.length;
return Buffer.concat([buffOne, buffTwo], newLength);
}
|
[
"function",
"_concat",
"(",
"buffOne",
",",
"buffTwo",
")",
"{",
"if",
"(",
"!",
"buffOne",
")",
"return",
"buffTwo",
";",
"if",
"(",
"!",
"buffTwo",
")",
"return",
"buffOne",
";",
"let",
"newLength",
"=",
"buffOne",
".",
"length",
"+",
"buffTwo",
".",
"length",
";",
"return",
"Buffer",
".",
"concat",
"(",
"[",
"buffOne",
",",
"buffTwo",
"]",
",",
"newLength",
")",
";",
"}"
] |
Combines two buffers
@param {Object} [buffOne] First buffer object
@param {Object} [buffTwo] Second buffer object
@return {Object} Combined buffer object
|
[
"Combines",
"two",
"buffers"
] |
2229978004eea584d0a5cdb7986ad642956c0960
|
https://github.com/neurosnap/gen-readlines/blob/2229978004eea584d0a5cdb7986ad642956c0960/index.js#L71-L77
|
37,428 |
atomantic/undermore
|
gulp/utils.js
|
function () {
var pkg = require(process.cwd() + '/package.json');
var licenses = [];
pkg.licenses.forEach(function (license) {
licenses.push(license.type);
});
return '/*! ' + pkg.name + ' - v' + pkg.version + ' - ' + gutil.date("yyyy-mm-dd") + "\n" +
(pkg.homepage ? "* " + pkg.homepage + "\n" : "") +
'* Copyright (c) ' + gutil.date("yyyy") + ' ' + pkg.author.name +
'; Licensed ' + licenses.join(', ') + ' */\n';
}
|
javascript
|
function () {
var pkg = require(process.cwd() + '/package.json');
var licenses = [];
pkg.licenses.forEach(function (license) {
licenses.push(license.type);
});
return '/*! ' + pkg.name + ' - v' + pkg.version + ' - ' + gutil.date("yyyy-mm-dd") + "\n" +
(pkg.homepage ? "* " + pkg.homepage + "\n" : "") +
'* Copyright (c) ' + gutil.date("yyyy") + ' ' + pkg.author.name +
'; Licensed ' + licenses.join(', ') + ' */\n';
}
|
[
"function",
"(",
")",
"{",
"var",
"pkg",
"=",
"require",
"(",
"process",
".",
"cwd",
"(",
")",
"+",
"'/package.json'",
")",
";",
"var",
"licenses",
"=",
"[",
"]",
";",
"pkg",
".",
"licenses",
".",
"forEach",
"(",
"function",
"(",
"license",
")",
"{",
"licenses",
".",
"push",
"(",
"license",
".",
"type",
")",
";",
"}",
")",
";",
"return",
"'/*! '",
"+",
"pkg",
".",
"name",
"+",
"' - v'",
"+",
"pkg",
".",
"version",
"+",
"' - '",
"+",
"gutil",
".",
"date",
"(",
"\"yyyy-mm-dd\"",
")",
"+",
"\"\\n\"",
"+",
"(",
"pkg",
".",
"homepage",
"?",
"\"* \"",
"+",
"pkg",
".",
"homepage",
"+",
"\"\\n\"",
":",
"\"\"",
")",
"+",
"'* Copyright (c) '",
"+",
"gutil",
".",
"date",
"(",
"\"yyyy\"",
")",
"+",
"' '",
"+",
"pkg",
".",
"author",
".",
"name",
"+",
"'; Licensed '",
"+",
"licenses",
".",
"join",
"(",
"', '",
")",
"+",
"' */\\n'",
";",
"}"
] |
This method builds our license string for embedding into the compiled file
|
[
"This",
"method",
"builds",
"our",
"license",
"string",
"for",
"embedding",
"into",
"the",
"compiled",
"file"
] |
6c6d995460c25c1df087b465fdc4d21035b4c7b2
|
https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/gulp/utils.js#L8-L19
|
|
37,429 |
bigcompany/big
|
apps/voice-recognition/public/speech.js
|
function(commands, resetCommands) {
// resetCommands defaults to true
if (resetCommands === undefined) {
resetCommands = true;
} else {
resetCommands = !!resetCommands;
}
// Abort previous instances of recognition already running
if (recognition && recognition.abort) {
recognition.abort();
}
// initiate SpeechRecognition
recognition = new SpeechRecognition();
// Set the max number of alternative transcripts to try and match with a command
recognition.maxAlternatives = 5;
// In HTTPS, turn off continuous mode for faster results.
// In HTTP, turn on continuous mode for much slower results, but no repeating security notices
recognition.continuous = root.location.protocol === 'http:';
// Sets the language to the default 'en-US'. This can be changed with annyang.setLanguage()
recognition.lang = 'en-US';
recognition.onstart = function() { invokeCallbacks(callbacks.start); };
recognition.onerror = function(event) {
invokeCallbacks(callbacks.error);
switch (event.error) {
case 'network':
invokeCallbacks(callbacks.errorNetwork);
break;
case 'not-allowed':
case 'service-not-allowed':
// if permission to use the mic is denied, turn off auto-restart
autoRestart = false;
// determine if permission was denied by user or automatically.
if (new Date().getTime()-lastStartedAt < 200) {
invokeCallbacks(callbacks.errorPermissionBlocked);
} else {
invokeCallbacks(callbacks.errorPermissionDenied);
}
break;
}
};
recognition.onend = function() {
invokeCallbacks(callbacks.end);
// annyang will auto restart if it is closed automatically and not by user action.
if (autoRestart) {
// play nicely with the browser, and never restart annyang automatically more than once per second
var timeSinceLastStart = new Date().getTime()-lastStartedAt;
if (timeSinceLastStart < 1000) {
setTimeout(root.annyang.start, 1000-timeSinceLastStart);
} else {
root.annyang.start();
}
}
};
recognition.onresult = function(event) {
invokeCallbacks(callbacks.result);
var results = event.results[event.resultIndex];
var commandText;
// go over each of the 5 results and alternative results received (we've set maxAlternatives to 5 above)
for (var i = 0; i<results.length; i++) {
// the text recognized
commandText = results[i].transcript.trim();
// do stuff
$('#speechActivity').html('<h2>Last voice command: ' + commandText + '</h2>');
if (debugState) {
// document.getElementById('speechActivity').innerHTML = commandText;
root.console.log('Speech recognized: %c'+commandText, debugStyle);
}
// try and match recognized text to one of the commands on the list
for (var j = 0, l = commandsList.length; j < l; j++) {
var result = commandsList[j].command.exec(commandText);
if (result) {
var parameters = result.slice(1);
if (debugState) {
root.console.log('command matched: %c'+commandsList[j].originalPhrase, debugStyle);
if (parameters.length) {
root.console.log('with parameters', parameters);
}
}
// execute the matched command
commandsList[j].callback.apply(this, parameters);
invokeCallbacks(callbacks.resultMatch);
return true;
}
}
}
invokeCallbacks(callbacks.resultNoMatch);
return false;
};
// build commands list
if (resetCommands) {
commandsList = [];
}
if (commands.length) {
this.addCommands(commands);
}
}
|
javascript
|
function(commands, resetCommands) {
// resetCommands defaults to true
if (resetCommands === undefined) {
resetCommands = true;
} else {
resetCommands = !!resetCommands;
}
// Abort previous instances of recognition already running
if (recognition && recognition.abort) {
recognition.abort();
}
// initiate SpeechRecognition
recognition = new SpeechRecognition();
// Set the max number of alternative transcripts to try and match with a command
recognition.maxAlternatives = 5;
// In HTTPS, turn off continuous mode for faster results.
// In HTTP, turn on continuous mode for much slower results, but no repeating security notices
recognition.continuous = root.location.protocol === 'http:';
// Sets the language to the default 'en-US'. This can be changed with annyang.setLanguage()
recognition.lang = 'en-US';
recognition.onstart = function() { invokeCallbacks(callbacks.start); };
recognition.onerror = function(event) {
invokeCallbacks(callbacks.error);
switch (event.error) {
case 'network':
invokeCallbacks(callbacks.errorNetwork);
break;
case 'not-allowed':
case 'service-not-allowed':
// if permission to use the mic is denied, turn off auto-restart
autoRestart = false;
// determine if permission was denied by user or automatically.
if (new Date().getTime()-lastStartedAt < 200) {
invokeCallbacks(callbacks.errorPermissionBlocked);
} else {
invokeCallbacks(callbacks.errorPermissionDenied);
}
break;
}
};
recognition.onend = function() {
invokeCallbacks(callbacks.end);
// annyang will auto restart if it is closed automatically and not by user action.
if (autoRestart) {
// play nicely with the browser, and never restart annyang automatically more than once per second
var timeSinceLastStart = new Date().getTime()-lastStartedAt;
if (timeSinceLastStart < 1000) {
setTimeout(root.annyang.start, 1000-timeSinceLastStart);
} else {
root.annyang.start();
}
}
};
recognition.onresult = function(event) {
invokeCallbacks(callbacks.result);
var results = event.results[event.resultIndex];
var commandText;
// go over each of the 5 results and alternative results received (we've set maxAlternatives to 5 above)
for (var i = 0; i<results.length; i++) {
// the text recognized
commandText = results[i].transcript.trim();
// do stuff
$('#speechActivity').html('<h2>Last voice command: ' + commandText + '</h2>');
if (debugState) {
// document.getElementById('speechActivity').innerHTML = commandText;
root.console.log('Speech recognized: %c'+commandText, debugStyle);
}
// try and match recognized text to one of the commands on the list
for (var j = 0, l = commandsList.length; j < l; j++) {
var result = commandsList[j].command.exec(commandText);
if (result) {
var parameters = result.slice(1);
if (debugState) {
root.console.log('command matched: %c'+commandsList[j].originalPhrase, debugStyle);
if (parameters.length) {
root.console.log('with parameters', parameters);
}
}
// execute the matched command
commandsList[j].callback.apply(this, parameters);
invokeCallbacks(callbacks.resultMatch);
return true;
}
}
}
invokeCallbacks(callbacks.resultNoMatch);
return false;
};
// build commands list
if (resetCommands) {
commandsList = [];
}
if (commands.length) {
this.addCommands(commands);
}
}
|
[
"function",
"(",
"commands",
",",
"resetCommands",
")",
"{",
"// resetCommands defaults to true",
"if",
"(",
"resetCommands",
"===",
"undefined",
")",
"{",
"resetCommands",
"=",
"true",
";",
"}",
"else",
"{",
"resetCommands",
"=",
"!",
"!",
"resetCommands",
";",
"}",
"// Abort previous instances of recognition already running",
"if",
"(",
"recognition",
"&&",
"recognition",
".",
"abort",
")",
"{",
"recognition",
".",
"abort",
"(",
")",
";",
"}",
"// initiate SpeechRecognition",
"recognition",
"=",
"new",
"SpeechRecognition",
"(",
")",
";",
"// Set the max number of alternative transcripts to try and match with a command",
"recognition",
".",
"maxAlternatives",
"=",
"5",
";",
"// In HTTPS, turn off continuous mode for faster results.",
"// In HTTP, turn on continuous mode for much slower results, but no repeating security notices",
"recognition",
".",
"continuous",
"=",
"root",
".",
"location",
".",
"protocol",
"===",
"'http:'",
";",
"// Sets the language to the default 'en-US'. This can be changed with annyang.setLanguage()",
"recognition",
".",
"lang",
"=",
"'en-US'",
";",
"recognition",
".",
"onstart",
"=",
"function",
"(",
")",
"{",
"invokeCallbacks",
"(",
"callbacks",
".",
"start",
")",
";",
"}",
";",
"recognition",
".",
"onerror",
"=",
"function",
"(",
"event",
")",
"{",
"invokeCallbacks",
"(",
"callbacks",
".",
"error",
")",
";",
"switch",
"(",
"event",
".",
"error",
")",
"{",
"case",
"'network'",
":",
"invokeCallbacks",
"(",
"callbacks",
".",
"errorNetwork",
")",
";",
"break",
";",
"case",
"'not-allowed'",
":",
"case",
"'service-not-allowed'",
":",
"// if permission to use the mic is denied, turn off auto-restart",
"autoRestart",
"=",
"false",
";",
"// determine if permission was denied by user or automatically.",
"if",
"(",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"-",
"lastStartedAt",
"<",
"200",
")",
"{",
"invokeCallbacks",
"(",
"callbacks",
".",
"errorPermissionBlocked",
")",
";",
"}",
"else",
"{",
"invokeCallbacks",
"(",
"callbacks",
".",
"errorPermissionDenied",
")",
";",
"}",
"break",
";",
"}",
"}",
";",
"recognition",
".",
"onend",
"=",
"function",
"(",
")",
"{",
"invokeCallbacks",
"(",
"callbacks",
".",
"end",
")",
";",
"// annyang will auto restart if it is closed automatically and not by user action.",
"if",
"(",
"autoRestart",
")",
"{",
"// play nicely with the browser, and never restart annyang automatically more than once per second",
"var",
"timeSinceLastStart",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"-",
"lastStartedAt",
";",
"if",
"(",
"timeSinceLastStart",
"<",
"1000",
")",
"{",
"setTimeout",
"(",
"root",
".",
"annyang",
".",
"start",
",",
"1000",
"-",
"timeSinceLastStart",
")",
";",
"}",
"else",
"{",
"root",
".",
"annyang",
".",
"start",
"(",
")",
";",
"}",
"}",
"}",
";",
"recognition",
".",
"onresult",
"=",
"function",
"(",
"event",
")",
"{",
"invokeCallbacks",
"(",
"callbacks",
".",
"result",
")",
";",
"var",
"results",
"=",
"event",
".",
"results",
"[",
"event",
".",
"resultIndex",
"]",
";",
"var",
"commandText",
";",
"// go over each of the 5 results and alternative results received (we've set maxAlternatives to 5 above)",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"results",
".",
"length",
";",
"i",
"++",
")",
"{",
"// the text recognized",
"commandText",
"=",
"results",
"[",
"i",
"]",
".",
"transcript",
".",
"trim",
"(",
")",
";",
"// do stuff",
"$",
"(",
"'#speechActivity'",
")",
".",
"html",
"(",
"'<h2>Last voice command: '",
"+",
"commandText",
"+",
"'</h2>'",
")",
";",
"if",
"(",
"debugState",
")",
"{",
"// document.getElementById('speechActivity').innerHTML = commandText;",
"root",
".",
"console",
".",
"log",
"(",
"'Speech recognized: %c'",
"+",
"commandText",
",",
"debugStyle",
")",
";",
"}",
"// try and match recognized text to one of the commands on the list",
"for",
"(",
"var",
"j",
"=",
"0",
",",
"l",
"=",
"commandsList",
".",
"length",
";",
"j",
"<",
"l",
";",
"j",
"++",
")",
"{",
"var",
"result",
"=",
"commandsList",
"[",
"j",
"]",
".",
"command",
".",
"exec",
"(",
"commandText",
")",
";",
"if",
"(",
"result",
")",
"{",
"var",
"parameters",
"=",
"result",
".",
"slice",
"(",
"1",
")",
";",
"if",
"(",
"debugState",
")",
"{",
"root",
".",
"console",
".",
"log",
"(",
"'command matched: %c'",
"+",
"commandsList",
"[",
"j",
"]",
".",
"originalPhrase",
",",
"debugStyle",
")",
";",
"if",
"(",
"parameters",
".",
"length",
")",
"{",
"root",
".",
"console",
".",
"log",
"(",
"'with parameters'",
",",
"parameters",
")",
";",
"}",
"}",
"// execute the matched command",
"commandsList",
"[",
"j",
"]",
".",
"callback",
".",
"apply",
"(",
"this",
",",
"parameters",
")",
";",
"invokeCallbacks",
"(",
"callbacks",
".",
"resultMatch",
")",
";",
"return",
"true",
";",
"}",
"}",
"}",
"invokeCallbacks",
"(",
"callbacks",
".",
"resultNoMatch",
")",
";",
"return",
"false",
";",
"}",
";",
"// build commands list",
"if",
"(",
"resetCommands",
")",
"{",
"commandsList",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"commands",
".",
"length",
")",
"{",
"this",
".",
"addCommands",
"(",
"commands",
")",
";",
"}",
"}"
] |
Initialize annyang with a list of commands to recognize.
### Examples:
var commands = {'hello :name': helloFunction};
var commands2 = {'hi': helloFunction};
// initialize annyang, overwriting any previously added commands
annyang.init(commands, true);
// adds an additional command without removing the previous commands
annyang.init(commands2, false);
As of v1.1.0 it is no longer required to call init(). Just start() listening whenever you want, and addCommands() whenever, and as often as you like.
@param {Object} commands - Commands that annyang should listen to
@param {Boolean} [resetCommands=true] - Remove all commands before initializing?
@method init
@deprecated
@see [Commands Object](#commands-object)
|
[
"Initialize",
"annyang",
"with",
"a",
"list",
"of",
"commands",
"to",
"recognize",
"."
] |
7ab6649dbef2d79722d3b4d538c26db6a200229c
|
https://github.com/bigcompany/big/blob/7ab6649dbef2d79722d3b4d538c26db6a200229c/apps/voice-recognition/public/speech.js#L102-L211
|
|
37,430 |
bigcompany/big
|
apps/voice-recognition/public/speech.js
|
function(options) {
initIfNeeded();
options = options || {};
if (options.autoRestart !== undefined) {
autoRestart = !!options.autoRestart;
} else {
autoRestart = true;
}
lastStartedAt = new Date().getTime();
recognition.start();
}
|
javascript
|
function(options) {
initIfNeeded();
options = options || {};
if (options.autoRestart !== undefined) {
autoRestart = !!options.autoRestart;
} else {
autoRestart = true;
}
lastStartedAt = new Date().getTime();
recognition.start();
}
|
[
"function",
"(",
"options",
")",
"{",
"initIfNeeded",
"(",
")",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"if",
"(",
"options",
".",
"autoRestart",
"!==",
"undefined",
")",
"{",
"autoRestart",
"=",
"!",
"!",
"options",
".",
"autoRestart",
";",
"}",
"else",
"{",
"autoRestart",
"=",
"true",
";",
"}",
"lastStartedAt",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
";",
"recognition",
".",
"start",
"(",
")",
";",
"}"
] |
Start listening.
It's a good idea to call this after adding some commands first, but not mandatory.
Receives an optional options object which currently only supports one option:
- `autoRestart` (Boolean, default: true) Should annyang restart itself if it is closed indirectly, because of silence or window conflicts?
### Examples:
// Start listening, but don't restart automatically
annyang.start({ autoRestart: false });
@param {Object} [options] - Optional options.
@method start
|
[
"Start",
"listening",
".",
"It",
"s",
"a",
"good",
"idea",
"to",
"call",
"this",
"after",
"adding",
"some",
"commands",
"first",
"but",
"not",
"mandatory",
"."
] |
7ab6649dbef2d79722d3b4d538c26db6a200229c
|
https://github.com/bigcompany/big/blob/7ab6649dbef2d79722d3b4d538c26db6a200229c/apps/voice-recognition/public/speech.js#L227-L237
|
|
37,431 |
bigcompany/big
|
apps/voice-recognition/public/speech.js
|
function(commandsToRemove) {
if (commandsToRemove === undefined) {
commandsList = [];
return;
}
commandsToRemove = Array.isArray(commandsToRemove) ? commandsToRemove : [commandsToRemove];
commandsList = commandsList.filter(function(command) {
for (var i = 0; i<commandsToRemove.length; i++) {
if (commandsToRemove[i] === command.originalPhrase) {
return false;
}
}
return true;
});
}
|
javascript
|
function(commandsToRemove) {
if (commandsToRemove === undefined) {
commandsList = [];
return;
}
commandsToRemove = Array.isArray(commandsToRemove) ? commandsToRemove : [commandsToRemove];
commandsList = commandsList.filter(function(command) {
for (var i = 0; i<commandsToRemove.length; i++) {
if (commandsToRemove[i] === command.originalPhrase) {
return false;
}
}
return true;
});
}
|
[
"function",
"(",
"commandsToRemove",
")",
"{",
"if",
"(",
"commandsToRemove",
"===",
"undefined",
")",
"{",
"commandsList",
"=",
"[",
"]",
";",
"return",
";",
"}",
"commandsToRemove",
"=",
"Array",
".",
"isArray",
"(",
"commandsToRemove",
")",
"?",
"commandsToRemove",
":",
"[",
"commandsToRemove",
"]",
";",
"commandsList",
"=",
"commandsList",
".",
"filter",
"(",
"function",
"(",
"command",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"commandsToRemove",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"commandsToRemove",
"[",
"i",
"]",
"===",
"command",
".",
"originalPhrase",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}",
")",
";",
"}"
] |
Remove existing commands. Called with a single phrase, array of phrases, or methodically. Pass no params to remove all commands.
### Examples:
var commands = {'hello': helloFunction, 'howdy': helloFunction, 'hi': helloFunction};
// Remove all existing commands
annyang.removeCommands();
// Add some commands
annyang.addCommands(commands);
// Don't respond to hello
annyang.removeCommands('hello');
// Don't respond to howdy or hi
annyang.removeCommands(['howdy', 'hi']);
@param {String|Array|Undefined} [commandsToRemove] - Commands to remove
@method removeCommands
|
[
"Remove",
"existing",
"commands",
".",
"Called",
"with",
"a",
"single",
"phrase",
"array",
"of",
"phrases",
"or",
"methodically",
".",
"Pass",
"no",
"params",
"to",
"remove",
"all",
"commands",
"."
] |
7ab6649dbef2d79722d3b4d538c26db6a200229c
|
https://github.com/bigcompany/big/blob/7ab6649dbef2d79722d3b4d538c26db6a200229c/apps/voice-recognition/public/speech.js#L339-L353
|
|
37,432 |
magemello/license-check
|
index.js
|
start
|
function start(config) {
if (!isConfigurationParametersDefinedCorrectly(config)) {
throw new Error('license-check - Configuration error');
}
var folders = [];
if (config.src) {
folders = getFoldersToCheck(config.src);
}
if (folders.length === 0) {
gutil.log('license-check', gutil.colors.red('{src} not defined or empty, the plugin will run with the default configuration: **/*'));
folders = getDefaultFolders();
}
var src = vfs.src(folders);
src.pipe(license(config));
return src;
}
|
javascript
|
function start(config) {
if (!isConfigurationParametersDefinedCorrectly(config)) {
throw new Error('license-check - Configuration error');
}
var folders = [];
if (config.src) {
folders = getFoldersToCheck(config.src);
}
if (folders.length === 0) {
gutil.log('license-check', gutil.colors.red('{src} not defined or empty, the plugin will run with the default configuration: **/*'));
folders = getDefaultFolders();
}
var src = vfs.src(folders);
src.pipe(license(config));
return src;
}
|
[
"function",
"start",
"(",
"config",
")",
"{",
"if",
"(",
"!",
"isConfigurationParametersDefinedCorrectly",
"(",
"config",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'license-check - Configuration error'",
")",
";",
"}",
"var",
"folders",
"=",
"[",
"]",
";",
"if",
"(",
"config",
".",
"src",
")",
"{",
"folders",
"=",
"getFoldersToCheck",
"(",
"config",
".",
"src",
")",
";",
"}",
"if",
"(",
"folders",
".",
"length",
"===",
"0",
")",
"{",
"gutil",
".",
"log",
"(",
"'license-check'",
",",
"gutil",
".",
"colors",
".",
"red",
"(",
"'{src} not defined or empty, the plugin will run with the default configuration: **/*'",
")",
")",
";",
"folders",
"=",
"getDefaultFolders",
"(",
")",
";",
"}",
"var",
"src",
"=",
"vfs",
".",
"src",
"(",
"folders",
")",
";",
"src",
".",
"pipe",
"(",
"license",
"(",
"config",
")",
")",
";",
"return",
"src",
";",
"}"
] |
Main execution function
@returns {object} return the stream to make possible append pipe or listen on channel such on('data') on('error) .
|
[
"Main",
"execution",
"function"
] |
a53ec538e1958ef64923fd3afc9747330e1235b7
|
https://github.com/magemello/license-check/blob/a53ec538e1958ef64923fd3afc9747330e1235b7/index.js#L32-L50
|
37,433 |
magemello/license-check
|
index.js
|
getFoldersToCheck
|
function getFoldersToCheck(src) {
var folders = [];
src.forEach(function (entry) {
if (entry.charAt(0) === '!') {
folders.push(path.join('!' + mainFolder, entry.substring(1, entry.length)));
} else {
if (entry.charAt(0) === '/') {
folders.push(entry);
} else {
folders.push(path.join(mainFolder, entry));
}
}
});
return folders;
}
|
javascript
|
function getFoldersToCheck(src) {
var folders = [];
src.forEach(function (entry) {
if (entry.charAt(0) === '!') {
folders.push(path.join('!' + mainFolder, entry.substring(1, entry.length)));
} else {
if (entry.charAt(0) === '/') {
folders.push(entry);
} else {
folders.push(path.join(mainFolder, entry));
}
}
});
return folders;
}
|
[
"function",
"getFoldersToCheck",
"(",
"src",
")",
"{",
"var",
"folders",
"=",
"[",
"]",
";",
"src",
".",
"forEach",
"(",
"function",
"(",
"entry",
")",
"{",
"if",
"(",
"entry",
".",
"charAt",
"(",
"0",
")",
"===",
"'!'",
")",
"{",
"folders",
".",
"push",
"(",
"path",
".",
"join",
"(",
"'!'",
"+",
"mainFolder",
",",
"entry",
".",
"substring",
"(",
"1",
",",
"entry",
".",
"length",
")",
")",
")",
";",
"}",
"else",
"{",
"if",
"(",
"entry",
".",
"charAt",
"(",
"0",
")",
"===",
"'/'",
")",
"{",
"folders",
".",
"push",
"(",
"entry",
")",
";",
"}",
"else",
"{",
"folders",
".",
"push",
"(",
"path",
".",
"join",
"(",
"mainFolder",
",",
"entry",
")",
")",
";",
"}",
"}",
"}",
")",
";",
"return",
"folders",
";",
"}"
] |
Return all the folders that the plugin have to check. Because the plugin is inside the node_modules
folder, we prepended to all the path the absolute path of the main context of execution.
@param {object} src - Path of the files you want to be checked by the plugin.
@returns {string[]} Path of the files you want to be checked by the plugin with the absolute path of the context prepended.
|
[
"Return",
"all",
"the",
"folders",
"that",
"the",
"plugin",
"have",
"to",
"check",
".",
"Because",
"the",
"plugin",
"is",
"inside",
"the",
"node_modules",
"folder",
"we",
"prepended",
"to",
"all",
"the",
"path",
"the",
"absolute",
"path",
"of",
"the",
"main",
"context",
"of",
"execution",
"."
] |
a53ec538e1958ef64923fd3afc9747330e1235b7
|
https://github.com/magemello/license-check/blob/a53ec538e1958ef64923fd3afc9747330e1235b7/index.js#L60-L75
|
37,434 |
magemello/license-check
|
index.js
|
isConfigurationParametersDefinedCorrectly
|
function isConfigurationParametersDefinedCorrectly(config) {
if (!config) {
gutil.log('license-check', gutil.colors.red('Config must be defined to run the plugin'));
return false;
}
if (!config.path) {
gutil.log('license-check', gutil.colors.red('License header property {path} must be defined to run the plugin'));
return false;
}
return true;
}
|
javascript
|
function isConfigurationParametersDefinedCorrectly(config) {
if (!config) {
gutil.log('license-check', gutil.colors.red('Config must be defined to run the plugin'));
return false;
}
if (!config.path) {
gutil.log('license-check', gutil.colors.red('License header property {path} must be defined to run the plugin'));
return false;
}
return true;
}
|
[
"function",
"isConfigurationParametersDefinedCorrectly",
"(",
"config",
")",
"{",
"if",
"(",
"!",
"config",
")",
"{",
"gutil",
".",
"log",
"(",
"'license-check'",
",",
"gutil",
".",
"colors",
".",
"red",
"(",
"'Config must be defined to run the plugin'",
")",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"config",
".",
"path",
")",
"{",
"gutil",
".",
"log",
"(",
"'license-check'",
",",
"gutil",
".",
"colors",
".",
"red",
"(",
"'License header property {path} must be defined to run the plugin'",
")",
")",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] |
Check that the configuration parameter are setted correctly.
@param {object} config - plugin configurations.
@returns {boolean} return true if the parameters are set correctly.
|
[
"Check",
"that",
"the",
"configuration",
"parameter",
"are",
"setted",
"correctly",
"."
] |
a53ec538e1958ef64923fd3afc9747330e1235b7
|
https://github.com/magemello/license-check/blob/a53ec538e1958ef64923fd3afc9747330e1235b7/index.js#L96-L108
|
37,435 |
infrabel/themes-gnap
|
raw/angular-datatables/angular-datatables.js
|
function (obj) {
this.obj = obj;
/**
* Check if the wrapped object is defined
* @returns true if the wrapped object is defined, false otherwise
*/
this.isPresent = function () {
return angular.isDefined(this.obj) && this.obj !== null;
};
/**
* Return the wrapped object or an empty object
* @returns the wrapped objector an empty object
*/
this.orEmptyObj = function () {
if (this.isPresent()) {
return this.obj;
}
return {};
};
/**
* Return the wrapped object or the given second choice
* @returns the wrapped object or the given second choice
*/
this.or = function (secondChoice) {
if (this.isPresent()) {
return this.obj;
}
return secondChoice;
};
}
|
javascript
|
function (obj) {
this.obj = obj;
/**
* Check if the wrapped object is defined
* @returns true if the wrapped object is defined, false otherwise
*/
this.isPresent = function () {
return angular.isDefined(this.obj) && this.obj !== null;
};
/**
* Return the wrapped object or an empty object
* @returns the wrapped objector an empty object
*/
this.orEmptyObj = function () {
if (this.isPresent()) {
return this.obj;
}
return {};
};
/**
* Return the wrapped object or the given second choice
* @returns the wrapped object or the given second choice
*/
this.or = function (secondChoice) {
if (this.isPresent()) {
return this.obj;
}
return secondChoice;
};
}
|
[
"function",
"(",
"obj",
")",
"{",
"this",
".",
"obj",
"=",
"obj",
";",
"/**\n * Check if the wrapped object is defined\n * @returns true if the wrapped object is defined, false otherwise\n */",
"this",
".",
"isPresent",
"=",
"function",
"(",
")",
"{",
"return",
"angular",
".",
"isDefined",
"(",
"this",
".",
"obj",
")",
"&&",
"this",
".",
"obj",
"!==",
"null",
";",
"}",
";",
"/**\n * Return the wrapped object or an empty object\n * @returns the wrapped objector an empty object\n */",
"this",
".",
"orEmptyObj",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"isPresent",
"(",
")",
")",
"{",
"return",
"this",
".",
"obj",
";",
"}",
"return",
"{",
"}",
";",
"}",
";",
"/**\n * Return the wrapped object or the given second choice\n * @returns the wrapped object or the given second choice\n */",
"this",
".",
"or",
"=",
"function",
"(",
"secondChoice",
")",
"{",
"if",
"(",
"this",
".",
"isPresent",
"(",
")",
")",
"{",
"return",
"this",
".",
"obj",
";",
"}",
"return",
"secondChoice",
";",
"}",
";",
"}"
] |
Optional class to handle undefined or null
@param obj the object to wrap
|
[
"Optional",
"class",
"to",
"handle",
"undefined",
"or",
"null"
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/angular-datatables/angular-datatables.js#L435-L464
|
|
37,436 |
infrabel/themes-gnap
|
raw/angular-datatables/angular-datatables.js
|
function (options) {
return {
options: options,
render: function ($scope, $elem) {
var _this = this, expression = $elem.find('tbody').html(),
// Find the resources from the comment <!-- ngRepeat: item in items --> displayed by angular in the DOM
// This regexp is inspired by the one used in the "ngRepeat" directive
match = expression.match(/^\s*.+\s+in\s+(\w*)\s*/), ngRepeatAttr = match[1];
if (!match) {
throw new Error('Expected expression in form of "_item_ in _collection_[ track by _id_]" but got "{0}".', expression);
}
var oTable, firstCall = true, alreadyRendered = false, parentScope = $scope.$parent;
parentScope.$watch(ngRepeatAttr, function () {
if (oTable && alreadyRendered && !_isDTOldVersion(oTable)) {
oTable.ngDestroy();
}
// This condition handles the case the array is empty
if (firstCall) {
firstCall = false;
$timeout(function () {
if (!alreadyRendered) {
oTable = _doRenderDataTable($elem, _this.options, $scope);
alreadyRendered = true;
}
}, 1000, false); // Hack I'm not proud of... Don't know how to do it otherwise...
} else {
$timeout(function () {
oTable = _doRenderDataTable($elem, _this.options, $scope);
alreadyRendered = true;
}, 0, false);
}
}, true);
}
};
}
|
javascript
|
function (options) {
return {
options: options,
render: function ($scope, $elem) {
var _this = this, expression = $elem.find('tbody').html(),
// Find the resources from the comment <!-- ngRepeat: item in items --> displayed by angular in the DOM
// This regexp is inspired by the one used in the "ngRepeat" directive
match = expression.match(/^\s*.+\s+in\s+(\w*)\s*/), ngRepeatAttr = match[1];
if (!match) {
throw new Error('Expected expression in form of "_item_ in _collection_[ track by _id_]" but got "{0}".', expression);
}
var oTable, firstCall = true, alreadyRendered = false, parentScope = $scope.$parent;
parentScope.$watch(ngRepeatAttr, function () {
if (oTable && alreadyRendered && !_isDTOldVersion(oTable)) {
oTable.ngDestroy();
}
// This condition handles the case the array is empty
if (firstCall) {
firstCall = false;
$timeout(function () {
if (!alreadyRendered) {
oTable = _doRenderDataTable($elem, _this.options, $scope);
alreadyRendered = true;
}
}, 1000, false); // Hack I'm not proud of... Don't know how to do it otherwise...
} else {
$timeout(function () {
oTable = _doRenderDataTable($elem, _this.options, $scope);
alreadyRendered = true;
}, 0, false);
}
}, true);
}
};
}
|
[
"function",
"(",
"options",
")",
"{",
"return",
"{",
"options",
":",
"options",
",",
"render",
":",
"function",
"(",
"$scope",
",",
"$elem",
")",
"{",
"var",
"_this",
"=",
"this",
",",
"expression",
"=",
"$elem",
".",
"find",
"(",
"'tbody'",
")",
".",
"html",
"(",
")",
",",
"// Find the resources from the comment <!-- ngRepeat: item in items --> displayed by angular in the DOM",
"// This regexp is inspired by the one used in the \"ngRepeat\" directive",
"match",
"=",
"expression",
".",
"match",
"(",
"/",
"^\\s*.+\\s+in\\s+(\\w*)\\s*",
"/",
")",
",",
"ngRepeatAttr",
"=",
"match",
"[",
"1",
"]",
";",
"if",
"(",
"!",
"match",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Expected expression in form of \"_item_ in _collection_[ track by _id_]\" but got \"{0}\".'",
",",
"expression",
")",
";",
"}",
"var",
"oTable",
",",
"firstCall",
"=",
"true",
",",
"alreadyRendered",
"=",
"false",
",",
"parentScope",
"=",
"$scope",
".",
"$parent",
";",
"parentScope",
".",
"$watch",
"(",
"ngRepeatAttr",
",",
"function",
"(",
")",
"{",
"if",
"(",
"oTable",
"&&",
"alreadyRendered",
"&&",
"!",
"_isDTOldVersion",
"(",
"oTable",
")",
")",
"{",
"oTable",
".",
"ngDestroy",
"(",
")",
";",
"}",
"// This condition handles the case the array is empty",
"if",
"(",
"firstCall",
")",
"{",
"firstCall",
"=",
"false",
";",
"$timeout",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"alreadyRendered",
")",
"{",
"oTable",
"=",
"_doRenderDataTable",
"(",
"$elem",
",",
"_this",
".",
"options",
",",
"$scope",
")",
";",
"alreadyRendered",
"=",
"true",
";",
"}",
"}",
",",
"1000",
",",
"false",
")",
";",
"// Hack I'm not proud of... Don't know how to do it otherwise...",
"}",
"else",
"{",
"$timeout",
"(",
"function",
"(",
")",
"{",
"oTable",
"=",
"_doRenderDataTable",
"(",
"$elem",
",",
"_this",
".",
"options",
",",
"$scope",
")",
";",
"alreadyRendered",
"=",
"true",
";",
"}",
",",
"0",
",",
"false",
")",
";",
"}",
"}",
",",
"true",
")",
";",
"}",
"}",
";",
"}"
] |
Renderer for displaying the Angular way
@param options
@returns {{options: *}} the renderer
@constructor
|
[
"Renderer",
"for",
"displaying",
"the",
"Angular",
"way"
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/angular-datatables/angular-datatables.js#L912-L946
|
|
37,437 |
infrabel/themes-gnap
|
raw/angular-datatables/angular-datatables.js
|
function (options) {
var oTable;
var _render = function (options, $elem, data, $scope) {
options.aaData = data;
// Add $timeout to be sure that angular has finished rendering before calling datatables
$timeout(function () {
_hideLoading($elem);
// Set it to true in order to be able to redraw the dataTable
options.bDestroy = true;
// Condition to refresh the dataTable
if (oTable) {
if (_isDTOldVersion(oTable)) {
oTable.fnClearTable();
oTable.fnDraw();
oTable.fnAddData(options.aaData);
} else {
oTable.clear();
oTable.rows.add(options.aaData).draw();
}
} else {
oTable = _renderDataTableAndEmitEvent($elem, options, $scope);
}
}, 0, false);
};
return {
options: options,
render: function ($scope, $elem) {
var _this = this, _loadedPromise = null, _whenLoaded = function (data) {
_render(_this.options, $elem, data, $scope);
_loadedPromise = null;
}, _startLoading = function (fnPromise) {
if (angular.isFunction(fnPromise)) {
_loadedPromise = fnPromise();
} else {
_loadedPromise = fnPromise;
}
_showLoading($elem);
_loadedPromise.then(_whenLoaded);
}, _reload = function (fnPromise) {
if (_loadedPromise) {
_loadedPromise.then(function () {
_startLoading(fnPromise);
});
} else {
_startLoading(fnPromise);
}
};
$scope.$watch('dtOptions.fnPromise', function (fnPromise) {
if (angular.isDefined(fnPromise)) {
_reload(fnPromise);
} else {
throw new Error('You must provide a promise or a function that returns a promise!');
}
});
$scope.$watch('dtOptions.reload', function (reload) {
if (reload) {
$scope.dtOptions.reload = false;
_reload($scope.dtOptions.fnPromise);
}
});
}
};
}
|
javascript
|
function (options) {
var oTable;
var _render = function (options, $elem, data, $scope) {
options.aaData = data;
// Add $timeout to be sure that angular has finished rendering before calling datatables
$timeout(function () {
_hideLoading($elem);
// Set it to true in order to be able to redraw the dataTable
options.bDestroy = true;
// Condition to refresh the dataTable
if (oTable) {
if (_isDTOldVersion(oTable)) {
oTable.fnClearTable();
oTable.fnDraw();
oTable.fnAddData(options.aaData);
} else {
oTable.clear();
oTable.rows.add(options.aaData).draw();
}
} else {
oTable = _renderDataTableAndEmitEvent($elem, options, $scope);
}
}, 0, false);
};
return {
options: options,
render: function ($scope, $elem) {
var _this = this, _loadedPromise = null, _whenLoaded = function (data) {
_render(_this.options, $elem, data, $scope);
_loadedPromise = null;
}, _startLoading = function (fnPromise) {
if (angular.isFunction(fnPromise)) {
_loadedPromise = fnPromise();
} else {
_loadedPromise = fnPromise;
}
_showLoading($elem);
_loadedPromise.then(_whenLoaded);
}, _reload = function (fnPromise) {
if (_loadedPromise) {
_loadedPromise.then(function () {
_startLoading(fnPromise);
});
} else {
_startLoading(fnPromise);
}
};
$scope.$watch('dtOptions.fnPromise', function (fnPromise) {
if (angular.isDefined(fnPromise)) {
_reload(fnPromise);
} else {
throw new Error('You must provide a promise or a function that returns a promise!');
}
});
$scope.$watch('dtOptions.reload', function (reload) {
if (reload) {
$scope.dtOptions.reload = false;
_reload($scope.dtOptions.fnPromise);
}
});
}
};
}
|
[
"function",
"(",
"options",
")",
"{",
"var",
"oTable",
";",
"var",
"_render",
"=",
"function",
"(",
"options",
",",
"$elem",
",",
"data",
",",
"$scope",
")",
"{",
"options",
".",
"aaData",
"=",
"data",
";",
"// Add $timeout to be sure that angular has finished rendering before calling datatables",
"$timeout",
"(",
"function",
"(",
")",
"{",
"_hideLoading",
"(",
"$elem",
")",
";",
"// Set it to true in order to be able to redraw the dataTable",
"options",
".",
"bDestroy",
"=",
"true",
";",
"// Condition to refresh the dataTable",
"if",
"(",
"oTable",
")",
"{",
"if",
"(",
"_isDTOldVersion",
"(",
"oTable",
")",
")",
"{",
"oTable",
".",
"fnClearTable",
"(",
")",
";",
"oTable",
".",
"fnDraw",
"(",
")",
";",
"oTable",
".",
"fnAddData",
"(",
"options",
".",
"aaData",
")",
";",
"}",
"else",
"{",
"oTable",
".",
"clear",
"(",
")",
";",
"oTable",
".",
"rows",
".",
"add",
"(",
"options",
".",
"aaData",
")",
".",
"draw",
"(",
")",
";",
"}",
"}",
"else",
"{",
"oTable",
"=",
"_renderDataTableAndEmitEvent",
"(",
"$elem",
",",
"options",
",",
"$scope",
")",
";",
"}",
"}",
",",
"0",
",",
"false",
")",
";",
"}",
";",
"return",
"{",
"options",
":",
"options",
",",
"render",
":",
"function",
"(",
"$scope",
",",
"$elem",
")",
"{",
"var",
"_this",
"=",
"this",
",",
"_loadedPromise",
"=",
"null",
",",
"_whenLoaded",
"=",
"function",
"(",
"data",
")",
"{",
"_render",
"(",
"_this",
".",
"options",
",",
"$elem",
",",
"data",
",",
"$scope",
")",
";",
"_loadedPromise",
"=",
"null",
";",
"}",
",",
"_startLoading",
"=",
"function",
"(",
"fnPromise",
")",
"{",
"if",
"(",
"angular",
".",
"isFunction",
"(",
"fnPromise",
")",
")",
"{",
"_loadedPromise",
"=",
"fnPromise",
"(",
")",
";",
"}",
"else",
"{",
"_loadedPromise",
"=",
"fnPromise",
";",
"}",
"_showLoading",
"(",
"$elem",
")",
";",
"_loadedPromise",
".",
"then",
"(",
"_whenLoaded",
")",
";",
"}",
",",
"_reload",
"=",
"function",
"(",
"fnPromise",
")",
"{",
"if",
"(",
"_loadedPromise",
")",
"{",
"_loadedPromise",
".",
"then",
"(",
"function",
"(",
")",
"{",
"_startLoading",
"(",
"fnPromise",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"_startLoading",
"(",
"fnPromise",
")",
";",
"}",
"}",
";",
"$scope",
".",
"$watch",
"(",
"'dtOptions.fnPromise'",
",",
"function",
"(",
"fnPromise",
")",
"{",
"if",
"(",
"angular",
".",
"isDefined",
"(",
"fnPromise",
")",
")",
"{",
"_reload",
"(",
"fnPromise",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'You must provide a promise or a function that returns a promise!'",
")",
";",
"}",
"}",
")",
";",
"$scope",
".",
"$watch",
"(",
"'dtOptions.reload'",
",",
"function",
"(",
"reload",
")",
"{",
"if",
"(",
"reload",
")",
"{",
"$scope",
".",
"dtOptions",
".",
"reload",
"=",
"false",
";",
"_reload",
"(",
"$scope",
".",
"dtOptions",
".",
"fnPromise",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
";",
"}"
] |
Renderer for displaying with a promise
@param options the options
@returns {{options: *}} the renderer
@constructor
|
[
"Renderer",
"for",
"displaying",
"with",
"a",
"promise"
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/angular-datatables/angular-datatables.js#L953-L1015
|
|
37,438 |
infrabel/themes-gnap
|
raw/angular-datatables/angular-datatables.js
|
function (options) {
var oTable;
var _render = function (options, $elem, $scope) {
// Set it to true in order to be able to redraw the dataTable
options.bDestroy = true;
// Add $timeout to be sure that angular has finished rendering before calling datatables
$timeout(function () {
_hideLoading($elem);
// Condition to refresh the dataTable
if (oTable) {
if (_hasReloadAjaxPlugin(oTable)) {
// Reload Ajax data using the plugin "fnReloadAjax": https://next.datatables.net/plug-ins/api/fnReloadAjax
// For DataTable v1.9.4
oTable.fnReloadAjax(options.sAjaxSource);
} else if (!_isDTOldVersion(oTable)) {
// For DataTable v1.10+, DT provides methods https://datatables.net/reference/api/ajax.url()
var ajaxUrl = options.sAjaxSource || options.ajax.url || options.ajax;
oTable.ajax.url(ajaxUrl).load();
} else {
throw new Error('Reload Ajax not supported. Please use the plugin "fnReloadAjax" (https://next.datatables.net/plug-ins/api/fnReloadAjax) or use a more recent version of DataTables (v1.10+)');
}
} else {
oTable = _renderDataTableAndEmitEvent($elem, options, $scope);
}
}, 0, false);
};
return {
options: options,
render: function ($scope, $elem) {
var _this = this;
// Define default values in case it is an ajax datatables
if (angular.isUndefined(_this.options.sAjaxDataProp)) {
_this.options.sAjaxDataProp = DT_DEFAULT_OPTIONS.sAjaxDataProp;
}
if (angular.isUndefined(_this.options.aoColumns)) {
_this.options.aoColumns = DT_DEFAULT_OPTIONS.aoColumns;
}
$scope.$watch('dtOptions.sAjaxSource', function (sAjaxSource) {
if (angular.isDefined(sAjaxSource)) {
_this.options.sAjaxSource = sAjaxSource;
if (angular.isDefined(_this.options.ajax)) {
if (angular.isObject(_this.options.ajax)) {
_this.options.ajax.url = sAjaxSource;
} else {
_this.options.ajax = { url: sAjaxSource };
}
}
}
_render(options, $elem, $scope);
});
$scope.$watch('dtOptions.reload', function (reload) {
if (reload) {
$scope.dtOptions.reload = false;
_render(options, $elem, $scope);
}
});
}
};
}
|
javascript
|
function (options) {
var oTable;
var _render = function (options, $elem, $scope) {
// Set it to true in order to be able to redraw the dataTable
options.bDestroy = true;
// Add $timeout to be sure that angular has finished rendering before calling datatables
$timeout(function () {
_hideLoading($elem);
// Condition to refresh the dataTable
if (oTable) {
if (_hasReloadAjaxPlugin(oTable)) {
// Reload Ajax data using the plugin "fnReloadAjax": https://next.datatables.net/plug-ins/api/fnReloadAjax
// For DataTable v1.9.4
oTable.fnReloadAjax(options.sAjaxSource);
} else if (!_isDTOldVersion(oTable)) {
// For DataTable v1.10+, DT provides methods https://datatables.net/reference/api/ajax.url()
var ajaxUrl = options.sAjaxSource || options.ajax.url || options.ajax;
oTable.ajax.url(ajaxUrl).load();
} else {
throw new Error('Reload Ajax not supported. Please use the plugin "fnReloadAjax" (https://next.datatables.net/plug-ins/api/fnReloadAjax) or use a more recent version of DataTables (v1.10+)');
}
} else {
oTable = _renderDataTableAndEmitEvent($elem, options, $scope);
}
}, 0, false);
};
return {
options: options,
render: function ($scope, $elem) {
var _this = this;
// Define default values in case it is an ajax datatables
if (angular.isUndefined(_this.options.sAjaxDataProp)) {
_this.options.sAjaxDataProp = DT_DEFAULT_OPTIONS.sAjaxDataProp;
}
if (angular.isUndefined(_this.options.aoColumns)) {
_this.options.aoColumns = DT_DEFAULT_OPTIONS.aoColumns;
}
$scope.$watch('dtOptions.sAjaxSource', function (sAjaxSource) {
if (angular.isDefined(sAjaxSource)) {
_this.options.sAjaxSource = sAjaxSource;
if (angular.isDefined(_this.options.ajax)) {
if (angular.isObject(_this.options.ajax)) {
_this.options.ajax.url = sAjaxSource;
} else {
_this.options.ajax = { url: sAjaxSource };
}
}
}
_render(options, $elem, $scope);
});
$scope.$watch('dtOptions.reload', function (reload) {
if (reload) {
$scope.dtOptions.reload = false;
_render(options, $elem, $scope);
}
});
}
};
}
|
[
"function",
"(",
"options",
")",
"{",
"var",
"oTable",
";",
"var",
"_render",
"=",
"function",
"(",
"options",
",",
"$elem",
",",
"$scope",
")",
"{",
"// Set it to true in order to be able to redraw the dataTable",
"options",
".",
"bDestroy",
"=",
"true",
";",
"// Add $timeout to be sure that angular has finished rendering before calling datatables",
"$timeout",
"(",
"function",
"(",
")",
"{",
"_hideLoading",
"(",
"$elem",
")",
";",
"// Condition to refresh the dataTable",
"if",
"(",
"oTable",
")",
"{",
"if",
"(",
"_hasReloadAjaxPlugin",
"(",
"oTable",
")",
")",
"{",
"// Reload Ajax data using the plugin \"fnReloadAjax\": https://next.datatables.net/plug-ins/api/fnReloadAjax",
"// For DataTable v1.9.4",
"oTable",
".",
"fnReloadAjax",
"(",
"options",
".",
"sAjaxSource",
")",
";",
"}",
"else",
"if",
"(",
"!",
"_isDTOldVersion",
"(",
"oTable",
")",
")",
"{",
"// For DataTable v1.10+, DT provides methods https://datatables.net/reference/api/ajax.url()",
"var",
"ajaxUrl",
"=",
"options",
".",
"sAjaxSource",
"||",
"options",
".",
"ajax",
".",
"url",
"||",
"options",
".",
"ajax",
";",
"oTable",
".",
"ajax",
".",
"url",
"(",
"ajaxUrl",
")",
".",
"load",
"(",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Reload Ajax not supported. Please use the plugin \"fnReloadAjax\" (https://next.datatables.net/plug-ins/api/fnReloadAjax) or use a more recent version of DataTables (v1.10+)'",
")",
";",
"}",
"}",
"else",
"{",
"oTable",
"=",
"_renderDataTableAndEmitEvent",
"(",
"$elem",
",",
"options",
",",
"$scope",
")",
";",
"}",
"}",
",",
"0",
",",
"false",
")",
";",
"}",
";",
"return",
"{",
"options",
":",
"options",
",",
"render",
":",
"function",
"(",
"$scope",
",",
"$elem",
")",
"{",
"var",
"_this",
"=",
"this",
";",
"// Define default values in case it is an ajax datatables",
"if",
"(",
"angular",
".",
"isUndefined",
"(",
"_this",
".",
"options",
".",
"sAjaxDataProp",
")",
")",
"{",
"_this",
".",
"options",
".",
"sAjaxDataProp",
"=",
"DT_DEFAULT_OPTIONS",
".",
"sAjaxDataProp",
";",
"}",
"if",
"(",
"angular",
".",
"isUndefined",
"(",
"_this",
".",
"options",
".",
"aoColumns",
")",
")",
"{",
"_this",
".",
"options",
".",
"aoColumns",
"=",
"DT_DEFAULT_OPTIONS",
".",
"aoColumns",
";",
"}",
"$scope",
".",
"$watch",
"(",
"'dtOptions.sAjaxSource'",
",",
"function",
"(",
"sAjaxSource",
")",
"{",
"if",
"(",
"angular",
".",
"isDefined",
"(",
"sAjaxSource",
")",
")",
"{",
"_this",
".",
"options",
".",
"sAjaxSource",
"=",
"sAjaxSource",
";",
"if",
"(",
"angular",
".",
"isDefined",
"(",
"_this",
".",
"options",
".",
"ajax",
")",
")",
"{",
"if",
"(",
"angular",
".",
"isObject",
"(",
"_this",
".",
"options",
".",
"ajax",
")",
")",
"{",
"_this",
".",
"options",
".",
"ajax",
".",
"url",
"=",
"sAjaxSource",
";",
"}",
"else",
"{",
"_this",
".",
"options",
".",
"ajax",
"=",
"{",
"url",
":",
"sAjaxSource",
"}",
";",
"}",
"}",
"}",
"_render",
"(",
"options",
",",
"$elem",
",",
"$scope",
")",
";",
"}",
")",
";",
"$scope",
".",
"$watch",
"(",
"'dtOptions.reload'",
",",
"function",
"(",
"reload",
")",
"{",
"if",
"(",
"reload",
")",
"{",
"$scope",
".",
"dtOptions",
".",
"reload",
"=",
"false",
";",
"_render",
"(",
"options",
",",
"$elem",
",",
"$scope",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
";",
"}"
] |
Renderer for displaying with Ajax
@param options the options
@returns {{options: *}} the renderer
@constructor
|
[
"Renderer",
"for",
"displaying",
"with",
"Ajax"
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/angular-datatables/angular-datatables.js#L1022-L1080
|
|
37,439 |
chriszarate/supergenpass-lib
|
src/lib/hostname.js
|
removeSubdomains
|
function removeSubdomains(hostname) {
const hostnameParts = hostname.split('.');
// A hostname with less than three parts is as short as it will get.
if (hostnameParts.length < 2) {
return hostname;
}
// Try to find a match in the list of ccTLDs.
const ccTld = find(tldList, part => endsWith(hostname, `.${part}`));
if (ccTld) {
// Get one extra part from the hostname.
const partCount = ccTld.split('.').length + 1;
return hostnameParts.slice(0 - partCount).join('.');
}
// If no ccTLDs were matched, return the final two parts of the hostname.
return hostnameParts.slice(-2).join('.');
}
|
javascript
|
function removeSubdomains(hostname) {
const hostnameParts = hostname.split('.');
// A hostname with less than three parts is as short as it will get.
if (hostnameParts.length < 2) {
return hostname;
}
// Try to find a match in the list of ccTLDs.
const ccTld = find(tldList, part => endsWith(hostname, `.${part}`));
if (ccTld) {
// Get one extra part from the hostname.
const partCount = ccTld.split('.').length + 1;
return hostnameParts.slice(0 - partCount).join('.');
}
// If no ccTLDs were matched, return the final two parts of the hostname.
return hostnameParts.slice(-2).join('.');
}
|
[
"function",
"removeSubdomains",
"(",
"hostname",
")",
"{",
"const",
"hostnameParts",
"=",
"hostname",
".",
"split",
"(",
"'.'",
")",
";",
"// A hostname with less than three parts is as short as it will get.",
"if",
"(",
"hostnameParts",
".",
"length",
"<",
"2",
")",
"{",
"return",
"hostname",
";",
"}",
"// Try to find a match in the list of ccTLDs.",
"const",
"ccTld",
"=",
"find",
"(",
"tldList",
",",
"part",
"=>",
"endsWith",
"(",
"hostname",
",",
"`",
"${",
"part",
"}",
"`",
")",
")",
";",
"if",
"(",
"ccTld",
")",
"{",
"// Get one extra part from the hostname.",
"const",
"partCount",
"=",
"ccTld",
".",
"split",
"(",
"'.'",
")",
".",
"length",
"+",
"1",
";",
"return",
"hostnameParts",
".",
"slice",
"(",
"0",
"-",
"partCount",
")",
".",
"join",
"(",
"'.'",
")",
";",
"}",
"// If no ccTLDs were matched, return the final two parts of the hostname.",
"return",
"hostnameParts",
".",
"slice",
"(",
"-",
"2",
")",
".",
"join",
"(",
"'.'",
")",
";",
"}"
] |
Remove subdomains while respecting a number of secondary ccTLDs.
|
[
"Remove",
"subdomains",
"while",
"respecting",
"a",
"number",
"of",
"secondary",
"ccTLDs",
"."
] |
eb9ee92050813d498229bfe0e6ccbcb87124cf90
|
https://github.com/chriszarate/supergenpass-lib/blob/eb9ee92050813d498229bfe0e6ccbcb87124cf90/src/lib/hostname.js#L13-L31
|
37,440 |
chriszarate/supergenpass-lib
|
src/lib/hostname.js
|
getHostname
|
function getHostname(url, userOptions = {}) {
const defaults = {
removeSubdomains: true,
};
const options = Object.assign({}, defaults, userOptions);
const domainRegExp = /^(?:[a-z]+:\/\/)?(?:[^/@]+@)?([^/:]+)/i;
const ipAddressRegExp = /^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/;
const domainMatch = url.match(domainRegExp);
if (domainMatch === null) {
throw new Error(`URL is invalid: ${url}`);
}
// If the hostname is an IP address, no further processing can be done.
const hostname = domainMatch[1];
if (ipAddressRegExp.test(hostname)) {
return hostname;
}
// Return the hostname with subdomains removed, if requested.
return (options.removeSubdomains) ? removeSubdomains(hostname) : hostname;
}
|
javascript
|
function getHostname(url, userOptions = {}) {
const defaults = {
removeSubdomains: true,
};
const options = Object.assign({}, defaults, userOptions);
const domainRegExp = /^(?:[a-z]+:\/\/)?(?:[^/@]+@)?([^/:]+)/i;
const ipAddressRegExp = /^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/;
const domainMatch = url.match(domainRegExp);
if (domainMatch === null) {
throw new Error(`URL is invalid: ${url}`);
}
// If the hostname is an IP address, no further processing can be done.
const hostname = domainMatch[1];
if (ipAddressRegExp.test(hostname)) {
return hostname;
}
// Return the hostname with subdomains removed, if requested.
return (options.removeSubdomains) ? removeSubdomains(hostname) : hostname;
}
|
[
"function",
"getHostname",
"(",
"url",
",",
"userOptions",
"=",
"{",
"}",
")",
"{",
"const",
"defaults",
"=",
"{",
"removeSubdomains",
":",
"true",
",",
"}",
";",
"const",
"options",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"defaults",
",",
"userOptions",
")",
";",
"const",
"domainRegExp",
"=",
"/",
"^(?:[a-z]+:\\/\\/)?(?:[^/@]+@)?([^/:]+)",
"/",
"i",
";",
"const",
"ipAddressRegExp",
"=",
"/",
"^\\d{1,3}\\.\\d{1,3}.\\d{1,3}\\.\\d{1,3}$",
"/",
";",
"const",
"domainMatch",
"=",
"url",
".",
"match",
"(",
"domainRegExp",
")",
";",
"if",
"(",
"domainMatch",
"===",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"url",
"}",
"`",
")",
";",
"}",
"// If the hostname is an IP address, no further processing can be done.",
"const",
"hostname",
"=",
"domainMatch",
"[",
"1",
"]",
";",
"if",
"(",
"ipAddressRegExp",
".",
"test",
"(",
"hostname",
")",
")",
"{",
"return",
"hostname",
";",
"}",
"// Return the hostname with subdomains removed, if requested.",
"return",
"(",
"options",
".",
"removeSubdomains",
")",
"?",
"removeSubdomains",
"(",
"hostname",
")",
":",
"hostname",
";",
"}"
] |
Isolate the domain name of a URL.
|
[
"Isolate",
"the",
"domain",
"name",
"of",
"a",
"URL",
"."
] |
eb9ee92050813d498229bfe0e6ccbcb87124cf90
|
https://github.com/chriszarate/supergenpass-lib/blob/eb9ee92050813d498229bfe0e6ccbcb87124cf90/src/lib/hostname.js#L34-L55
|
37,441 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/x-editable/ace-editable.js
|
function() {
var self = this;
this.$input = this.$tpl.find('input[type=hidden]:eq(0)');
this.$file = this.$tpl.find('input[type=file]:eq(0)');
this.$file.attr({'name':this.name});
this.$input.attr({'name':this.name+'-hidden'});
this.options.image.before_change = this.options.image.before_change || function(files, dropped) {
var file = files[0];
if(typeof file === "string") {
//files is just a file name here (in browsers that don't support FileReader API)
if(! (/\.(jpe?g|png|gif)$/i).test(file) ) {
if(self.on_error) self.on_error(1);
return false;
}
}
else {//file is a File object
var type = $.trim(file.type);
if( ( type.length > 0 && ! (/^image\/(jpe?g|png|gif)$/i).test(type) )
|| ( type.length == 0 && ! (/\.(jpe?g|png|gif)$/i).test(file.name) )//for android default browser!
)
{
if(self.on_error) self.on_error(1);
return false;
}
if( self.max_size && file.size > self.max_size ) {
if(self.on_error) self.on_error(2);
return false;
}
}
if(self.on_success) self.on_success();
return true;
}
this.options.image.before_remove = this.options.image.before_remove || function() {
self.$input.val(null);
return true;
}
this.$file.ace_file_input(this.options.image).on('change', function(){
var $rand = (self.$file.val() || self.$file.data('ace_input_files')) ? Math.random() + "" + (new Date()).getTime() : null;
self.$input.val($rand)//set a random value, so that selected file is uploaded each time, even if it's the same file, because inline editable plugin does not update if the value is not changed!
}).closest('.ace-file-input').css({'width':'150px'}).closest('.editable-input').addClass('editable-image');
}
|
javascript
|
function() {
var self = this;
this.$input = this.$tpl.find('input[type=hidden]:eq(0)');
this.$file = this.$tpl.find('input[type=file]:eq(0)');
this.$file.attr({'name':this.name});
this.$input.attr({'name':this.name+'-hidden'});
this.options.image.before_change = this.options.image.before_change || function(files, dropped) {
var file = files[0];
if(typeof file === "string") {
//files is just a file name here (in browsers that don't support FileReader API)
if(! (/\.(jpe?g|png|gif)$/i).test(file) ) {
if(self.on_error) self.on_error(1);
return false;
}
}
else {//file is a File object
var type = $.trim(file.type);
if( ( type.length > 0 && ! (/^image\/(jpe?g|png|gif)$/i).test(type) )
|| ( type.length == 0 && ! (/\.(jpe?g|png|gif)$/i).test(file.name) )//for android default browser!
)
{
if(self.on_error) self.on_error(1);
return false;
}
if( self.max_size && file.size > self.max_size ) {
if(self.on_error) self.on_error(2);
return false;
}
}
if(self.on_success) self.on_success();
return true;
}
this.options.image.before_remove = this.options.image.before_remove || function() {
self.$input.val(null);
return true;
}
this.$file.ace_file_input(this.options.image).on('change', function(){
var $rand = (self.$file.val() || self.$file.data('ace_input_files')) ? Math.random() + "" + (new Date()).getTime() : null;
self.$input.val($rand)//set a random value, so that selected file is uploaded each time, even if it's the same file, because inline editable plugin does not update if the value is not changed!
}).closest('.ace-file-input').css({'width':'150px'}).closest('.editable-input').addClass('editable-image');
}
|
[
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"this",
".",
"$input",
"=",
"this",
".",
"$tpl",
".",
"find",
"(",
"'input[type=hidden]:eq(0)'",
")",
";",
"this",
".",
"$file",
"=",
"this",
".",
"$tpl",
".",
"find",
"(",
"'input[type=file]:eq(0)'",
")",
";",
"this",
".",
"$file",
".",
"attr",
"(",
"{",
"'name'",
":",
"this",
".",
"name",
"}",
")",
";",
"this",
".",
"$input",
".",
"attr",
"(",
"{",
"'name'",
":",
"this",
".",
"name",
"+",
"'-hidden'",
"}",
")",
";",
"this",
".",
"options",
".",
"image",
".",
"before_change",
"=",
"this",
".",
"options",
".",
"image",
".",
"before_change",
"||",
"function",
"(",
"files",
",",
"dropped",
")",
"{",
"var",
"file",
"=",
"files",
"[",
"0",
"]",
";",
"if",
"(",
"typeof",
"file",
"===",
"\"string\"",
")",
"{",
"//files is just a file name here (in browsers that don't support FileReader API)",
"if",
"(",
"!",
"(",
"/",
"\\.(jpe?g|png|gif)$",
"/",
"i",
")",
".",
"test",
"(",
"file",
")",
")",
"{",
"if",
"(",
"self",
".",
"on_error",
")",
"self",
".",
"on_error",
"(",
"1",
")",
";",
"return",
"false",
";",
"}",
"}",
"else",
"{",
"//file is a File object",
"var",
"type",
"=",
"$",
".",
"trim",
"(",
"file",
".",
"type",
")",
";",
"if",
"(",
"(",
"type",
".",
"length",
">",
"0",
"&&",
"!",
"(",
"/",
"^image\\/(jpe?g|png|gif)$",
"/",
"i",
")",
".",
"test",
"(",
"type",
")",
")",
"||",
"(",
"type",
".",
"length",
"==",
"0",
"&&",
"!",
"(",
"/",
"\\.(jpe?g|png|gif)$",
"/",
"i",
")",
".",
"test",
"(",
"file",
".",
"name",
")",
")",
"//for android default browser!",
")",
"{",
"if",
"(",
"self",
".",
"on_error",
")",
"self",
".",
"on_error",
"(",
"1",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"self",
".",
"max_size",
"&&",
"file",
".",
"size",
">",
"self",
".",
"max_size",
")",
"{",
"if",
"(",
"self",
".",
"on_error",
")",
"self",
".",
"on_error",
"(",
"2",
")",
";",
"return",
"false",
";",
"}",
"}",
"if",
"(",
"self",
".",
"on_success",
")",
"self",
".",
"on_success",
"(",
")",
";",
"return",
"true",
";",
"}",
"this",
".",
"options",
".",
"image",
".",
"before_remove",
"=",
"this",
".",
"options",
".",
"image",
".",
"before_remove",
"||",
"function",
"(",
")",
"{",
"self",
".",
"$input",
".",
"val",
"(",
"null",
")",
";",
"return",
"true",
";",
"}",
"this",
".",
"$file",
".",
"ace_file_input",
"(",
"this",
".",
"options",
".",
"image",
")",
".",
"on",
"(",
"'change'",
",",
"function",
"(",
")",
"{",
"var",
"$rand",
"=",
"(",
"self",
".",
"$file",
".",
"val",
"(",
")",
"||",
"self",
".",
"$file",
".",
"data",
"(",
"'ace_input_files'",
")",
")",
"?",
"Math",
".",
"random",
"(",
")",
"+",
"\"\"",
"+",
"(",
"new",
"Date",
"(",
")",
")",
".",
"getTime",
"(",
")",
":",
"null",
";",
"self",
".",
"$input",
".",
"val",
"(",
"$rand",
")",
"//set a random value, so that selected file is uploaded each time, even if it's the same file, because inline editable plugin does not update if the value is not changed!",
"}",
")",
".",
"closest",
"(",
"'.ace-file-input'",
")",
".",
"css",
"(",
"{",
"'width'",
":",
"'150px'",
"}",
")",
".",
"closest",
"(",
"'.editable-input'",
")",
".",
"addClass",
"(",
"'editable-image'",
")",
";",
"}"
] |
Renders input from tpl
@method render()
|
[
"Renders",
"input",
"from",
"tpl"
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/x-editable/ace-editable.js#L40-L85
|
|
37,442 |
RoganMurley/hitagi.js
|
src/components/graphics/graphic.js
|
function (params) {
this.$id = 'graphic';
this.$deps = []; // Position dependency added later if relative positioning is true.
params = _.extend({
alpha: 1,
anchor: {
x: 0.5,
y: 0.5
},
relative: true,
scale: {
x: 1,
y: 1
},
tint: 0xffffff,
translate: {
x: 0,
y: 0
},
visible: true,
z: 0
}, params);
if (params.relative) {
this.$deps.push('position');
}
this.alpha = params.alpha;
this.anchor = params.anchor;
this.relative = params.relative;
this.scale = params.scale;
this.tint = params.tint;
this.translate = params.translate;
this.visible = params.visible;
this.z = params.z;
}
|
javascript
|
function (params) {
this.$id = 'graphic';
this.$deps = []; // Position dependency added later if relative positioning is true.
params = _.extend({
alpha: 1,
anchor: {
x: 0.5,
y: 0.5
},
relative: true,
scale: {
x: 1,
y: 1
},
tint: 0xffffff,
translate: {
x: 0,
y: 0
},
visible: true,
z: 0
}, params);
if (params.relative) {
this.$deps.push('position');
}
this.alpha = params.alpha;
this.anchor = params.anchor;
this.relative = params.relative;
this.scale = params.scale;
this.tint = params.tint;
this.translate = params.translate;
this.visible = params.visible;
this.z = params.z;
}
|
[
"function",
"(",
"params",
")",
"{",
"this",
".",
"$id",
"=",
"'graphic'",
";",
"this",
".",
"$deps",
"=",
"[",
"]",
";",
"// Position dependency added later if relative positioning is true.",
"params",
"=",
"_",
".",
"extend",
"(",
"{",
"alpha",
":",
"1",
",",
"anchor",
":",
"{",
"x",
":",
"0.5",
",",
"y",
":",
"0.5",
"}",
",",
"relative",
":",
"true",
",",
"scale",
":",
"{",
"x",
":",
"1",
",",
"y",
":",
"1",
"}",
",",
"tint",
":",
"0xffffff",
",",
"translate",
":",
"{",
"x",
":",
"0",
",",
"y",
":",
"0",
"}",
",",
"visible",
":",
"true",
",",
"z",
":",
"0",
"}",
",",
"params",
")",
";",
"if",
"(",
"params",
".",
"relative",
")",
"{",
"this",
".",
"$deps",
".",
"push",
"(",
"'position'",
")",
";",
"}",
"this",
".",
"alpha",
"=",
"params",
".",
"alpha",
";",
"this",
".",
"anchor",
"=",
"params",
".",
"anchor",
";",
"this",
".",
"relative",
"=",
"params",
".",
"relative",
";",
"this",
".",
"scale",
"=",
"params",
".",
"scale",
";",
"this",
".",
"tint",
"=",
"params",
".",
"tint",
";",
"this",
".",
"translate",
"=",
"params",
".",
"translate",
";",
"this",
".",
"visible",
"=",
"params",
".",
"visible",
";",
"this",
".",
"z",
"=",
"params",
".",
"z",
";",
"}"
] |
Represents a graphic to draw.
|
[
"Represents",
"a",
"graphic",
"to",
"draw",
"."
] |
6ad88d8df3af9b1708d70bb0c1f5a7a39ead9053
|
https://github.com/RoganMurley/hitagi.js/blob/6ad88d8df3af9b1708d70bb0c1f5a7a39ead9053/src/components/graphics/graphic.js#L7-L44
|
|
37,443 |
joshfire/woodman
|
lib/layouts/patternlayout.js
|
function (config, loggerContext) {
Layout.call(this, config, loggerContext);
this.pattern = this.config.pattern ||
PatternLayout.DEFAULT_CONVERSION_PATTERN;
this.compactObjects = this.config.compactObjects || false;
}
|
javascript
|
function (config, loggerContext) {
Layout.call(this, config, loggerContext);
this.pattern = this.config.pattern ||
PatternLayout.DEFAULT_CONVERSION_PATTERN;
this.compactObjects = this.config.compactObjects || false;
}
|
[
"function",
"(",
"config",
",",
"loggerContext",
")",
"{",
"Layout",
".",
"call",
"(",
"this",
",",
"config",
",",
"loggerContext",
")",
";",
"this",
".",
"pattern",
"=",
"this",
".",
"config",
".",
"pattern",
"||",
"PatternLayout",
".",
"DEFAULT_CONVERSION_PATTERN",
";",
"this",
".",
"compactObjects",
"=",
"this",
".",
"config",
".",
"compactObjects",
"||",
"false",
";",
"}"
] |
Lays out a log event using a regexp-like format string.
@constructor
@extends {Layout}
@param {Object} config Layout configuration. Structure depends on concrete
layout class being used
@param {LoggerContext} loggerContext Reference to the logger context that
gave birth to this layout.
|
[
"Lays",
"out",
"a",
"log",
"event",
"using",
"a",
"regexp",
"-",
"like",
"format",
"string",
"."
] |
fdc05de2124388780924980e6f27bf4483056d18
|
https://github.com/joshfire/woodman/blob/fdc05de2124388780924980e6f27bf4483056d18/lib/layouts/patternlayout.js#L89-L94
|
|
37,444 |
SBoudrias/gruntfile-editor
|
lib/index.js
|
function (gruntfileContent) {
var defaultGruntfilePath = path.join(__dirname, 'default-gruntfile.js');
gruntfileContent = gruntfileContent || fs.readFileSync(defaultGruntfilePath);
this.gruntfile = new Tree(gruntfileContent.toString());
}
|
javascript
|
function (gruntfileContent) {
var defaultGruntfilePath = path.join(__dirname, 'default-gruntfile.js');
gruntfileContent = gruntfileContent || fs.readFileSync(defaultGruntfilePath);
this.gruntfile = new Tree(gruntfileContent.toString());
}
|
[
"function",
"(",
"gruntfileContent",
")",
"{",
"var",
"defaultGruntfilePath",
"=",
"path",
".",
"join",
"(",
"__dirname",
",",
"'default-gruntfile.js'",
")",
";",
"gruntfileContent",
"=",
"gruntfileContent",
"||",
"fs",
".",
"readFileSync",
"(",
"defaultGruntfilePath",
")",
";",
"this",
".",
"gruntfile",
"=",
"new",
"Tree",
"(",
"gruntfileContent",
".",
"toString",
"(",
")",
")",
";",
"}"
] |
A class managing the edition of the project Gruntfile content. Editing the
Gruntfile using this class allow easier Generator composability as they can
work and add parts to the same Gruntfile without having to parse the
Gruntfile AST themselves.
@constructor
@param {String} gruntfileContent - The actual `Gruntfile.js` content
|
[
"A",
"class",
"managing",
"the",
"edition",
"of",
"the",
"project",
"Gruntfile",
"content",
".",
"Editing",
"the",
"Gruntfile",
"using",
"this",
"class",
"allow",
"easier",
"Generator",
"composability",
"as",
"they",
"can",
"work",
"and",
"add",
"parts",
"to",
"the",
"same",
"Gruntfile",
"without",
"having",
"to",
"parse",
"the",
"Gruntfile",
"AST",
"themselves",
"."
] |
a5e1d849a20c3e2102c0c59926a5c919ca43a2b7
|
https://github.com/SBoudrias/gruntfile-editor/blob/a5e1d849a20c3e2102c0c59926a5c919ca43a2b7/lib/index.js#L18-L22
|
|
37,445 |
Adezandee/node-cp
|
cp.js
|
function(checks, callback) {
fs.lstat(options.source, function(err, stats) {
/* istanbul ignore else */
if (stats.isFile()) {
copyFile(options, callback);
} else if (stats.isDirectory()) {
copyDir(options, callback);
} else if (stats.isSymbolicLink()) {
copySymlink(options, callback);
} else {
callback(new Error('Unsupported file type !'));
}
});
}
|
javascript
|
function(checks, callback) {
fs.lstat(options.source, function(err, stats) {
/* istanbul ignore else */
if (stats.isFile()) {
copyFile(options, callback);
} else if (stats.isDirectory()) {
copyDir(options, callback);
} else if (stats.isSymbolicLink()) {
copySymlink(options, callback);
} else {
callback(new Error('Unsupported file type !'));
}
});
}
|
[
"function",
"(",
"checks",
",",
"callback",
")",
"{",
"fs",
".",
"lstat",
"(",
"options",
".",
"source",
",",
"function",
"(",
"err",
",",
"stats",
")",
"{",
"/* istanbul ignore else */",
"if",
"(",
"stats",
".",
"isFile",
"(",
")",
")",
"{",
"copyFile",
"(",
"options",
",",
"callback",
")",
";",
"}",
"else",
"if",
"(",
"stats",
".",
"isDirectory",
"(",
")",
")",
"{",
"copyDir",
"(",
"options",
",",
"callback",
")",
";",
"}",
"else",
"if",
"(",
"stats",
".",
"isSymbolicLink",
"(",
")",
")",
"{",
"copySymlink",
"(",
"options",
",",
"callback",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"new",
"Error",
"(",
"'Unsupported file type !'",
")",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Read the source and acts accordingly to its type
|
[
"Read",
"the",
"source",
"and",
"acts",
"accordingly",
"to",
"its",
"type"
] |
e053ec042f2084c0d1f9ddab1f3727f1c0d422b6
|
https://github.com/Adezandee/node-cp/blob/e053ec042f2084c0d1f9ddab1f3727f1c0d422b6/cp.js#L29-L42
|
|
37,446 |
Adezandee/node-cp
|
cp.js
|
function(callback) {
fs.exists(options.source, function(exists) {
if(!exists) { callback(new Error('Source file do not exists!')); }
else { callback(null, true); }
});
}
|
javascript
|
function(callback) {
fs.exists(options.source, function(exists) {
if(!exists) { callback(new Error('Source file do not exists!')); }
else { callback(null, true); }
});
}
|
[
"function",
"(",
"callback",
")",
"{",
"fs",
".",
"exists",
"(",
"options",
".",
"source",
",",
"function",
"(",
"exists",
")",
"{",
"if",
"(",
"!",
"exists",
")",
"{",
"callback",
"(",
"new",
"Error",
"(",
"'Source file do not exists!'",
")",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"null",
",",
"true",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Check if source exists
|
[
"Check",
"if",
"source",
"exists"
] |
e053ec042f2084c0d1f9ddab1f3727f1c0d422b6
|
https://github.com/Adezandee/node-cp/blob/e053ec042f2084c0d1f9ddab1f3727f1c0d422b6/cp.js#L51-L56
|
|
37,447 |
Adezandee/node-cp
|
cp.js
|
function(linkString, callback) {
fs.exists(_toFile, function (exists) {
callback(null, exists, linkString);
});
}
|
javascript
|
function(linkString, callback) {
fs.exists(_toFile, function (exists) {
callback(null, exists, linkString);
});
}
|
[
"function",
"(",
"linkString",
",",
"callback",
")",
"{",
"fs",
".",
"exists",
"(",
"_toFile",
",",
"function",
"(",
"exists",
")",
"{",
"callback",
"(",
"null",
",",
"exists",
",",
"linkString",
")",
";",
"}",
")",
";",
"}"
] |
Check if the copied symlink already exists in destination folder
|
[
"Check",
"if",
"the",
"copied",
"symlink",
"already",
"exists",
"in",
"destination",
"folder"
] |
e053ec042f2084c0d1f9ddab1f3727f1c0d422b6
|
https://github.com/Adezandee/node-cp/blob/e053ec042f2084c0d1f9ddab1f3727f1c0d422b6/cp.js#L92-L96
|
|
37,448 |
Adezandee/node-cp
|
cp.js
|
function(exists, linkString, callback) {
if (exists) {
return callback(null, symlink);
}
fs.symlink(linkString, _toFile, function(err) {
callback(err, symlink);
});
}
|
javascript
|
function(exists, linkString, callback) {
if (exists) {
return callback(null, symlink);
}
fs.symlink(linkString, _toFile, function(err) {
callback(err, symlink);
});
}
|
[
"function",
"(",
"exists",
",",
"linkString",
",",
"callback",
")",
"{",
"if",
"(",
"exists",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"symlink",
")",
";",
"}",
"fs",
".",
"symlink",
"(",
"linkString",
",",
"_toFile",
",",
"function",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
",",
"symlink",
")",
";",
"}",
")",
";",
"}"
] |
If link does not already exists, creates it
|
[
"If",
"link",
"does",
"not",
"already",
"exists",
"creates",
"it"
] |
e053ec042f2084c0d1f9ddab1f3727f1c0d422b6
|
https://github.com/Adezandee/node-cp/blob/e053ec042f2084c0d1f9ddab1f3727f1c0d422b6/cp.js#L99-L106
|
|
37,449 |
Adezandee/node-cp
|
cp.js
|
function(stats, callback) {
fs.readFile(file, function(err, data) {
callback(err, data, stats);
});
}
|
javascript
|
function(stats, callback) {
fs.readFile(file, function(err, data) {
callback(err, data, stats);
});
}
|
[
"function",
"(",
"stats",
",",
"callback",
")",
"{",
"fs",
".",
"readFile",
"(",
"file",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"callback",
"(",
"err",
",",
"data",
",",
"stats",
")",
";",
"}",
")",
";",
"}"
] |
Read the file
|
[
"Read",
"the",
"file"
] |
e053ec042f2084c0d1f9ddab1f3727f1c0d422b6
|
https://github.com/Adezandee/node-cp/blob/e053ec042f2084c0d1f9ddab1f3727f1c0d422b6/cp.js#L123-L127
|
|
37,450 |
Adezandee/node-cp
|
cp.js
|
function(data, stats, callback) {
fs.writeFile(_toFile, data, stats, function(err) {
callback(err, _toFile);
});
}
|
javascript
|
function(data, stats, callback) {
fs.writeFile(_toFile, data, stats, function(err) {
callback(err, _toFile);
});
}
|
[
"function",
"(",
"data",
",",
"stats",
",",
"callback",
")",
"{",
"fs",
".",
"writeFile",
"(",
"_toFile",
",",
"data",
",",
"stats",
",",
"function",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
",",
"_toFile",
")",
";",
"}",
")",
";",
"}"
] |
Write the new file in destination folder
|
[
"Write",
"the",
"new",
"file",
"in",
"destination",
"folder"
] |
e053ec042f2084c0d1f9ddab1f3727f1c0d422b6
|
https://github.com/Adezandee/node-cp/blob/e053ec042f2084c0d1f9ddab1f3727f1c0d422b6/cp.js#L130-L134
|
|
37,451 |
rjrodger/seneca-perm
|
lib/ACLMicroservicesBuilder.js
|
processAuthResultForEntity
|
function processAuthResultForEntity(err, entity) {
if(stopAll) return
if(err && err.code !== ACL_ERROR_CODE) {
stopAll = true
callback(err, undefined)
} else {
if(entity) {
filteredEntities.push(entity)
}
callbackCount ++
if(callbackCount === entities.length) {
callback(undefined, filteredEntities)
}
}
}
|
javascript
|
function processAuthResultForEntity(err, entity) {
if(stopAll) return
if(err && err.code !== ACL_ERROR_CODE) {
stopAll = true
callback(err, undefined)
} else {
if(entity) {
filteredEntities.push(entity)
}
callbackCount ++
if(callbackCount === entities.length) {
callback(undefined, filteredEntities)
}
}
}
|
[
"function",
"processAuthResultForEntity",
"(",
"err",
",",
"entity",
")",
"{",
"if",
"(",
"stopAll",
")",
"return",
"if",
"(",
"err",
"&&",
"err",
".",
"code",
"!==",
"ACL_ERROR_CODE",
")",
"{",
"stopAll",
"=",
"true",
"callback",
"(",
"err",
",",
"undefined",
")",
"}",
"else",
"{",
"if",
"(",
"entity",
")",
"{",
"filteredEntities",
".",
"push",
"(",
"entity",
")",
"}",
"callbackCount",
"++",
"if",
"(",
"callbackCount",
"===",
"entities",
".",
"length",
")",
"{",
"callback",
"(",
"undefined",
",",
"filteredEntities",
")",
"}",
"}",
"}"
] |
this closure is evil
|
[
"this",
"closure",
"is",
"evil"
] |
cca9169e0d40d9796e11d30c2c878486ecfdcb4a
|
https://github.com/rjrodger/seneca-perm/blob/cca9169e0d40d9796e11d30c2c878486ecfdcb4a/lib/ACLMicroservicesBuilder.js#L188-L205
|
37,452 |
xinix-technology/xin
|
core/event.js
|
_getMatcher
|
function _getMatcher (element) {
if (_matcher) {
return _matcher;
}
if (element.matches) {
_matcher = element.matches;
return _matcher;
}
if (element.webkitMatchesSelector) {
_matcher = element.webkitMatchesSelector;
return _matcher;
}
if (element.mozMatchesSelector) {
_matcher = element.mozMatchesSelector;
return _matcher;
}
if (element.msMatchesSelector) {
_matcher = element.msMatchesSelector;
return _matcher;
}
if (element.oMatchesSelector) {
_matcher = element.oMatchesSelector;
return _matcher;
}
// if it doesn't match a native browser method
// fall back to the delegator function
_matcher = Delegator.matchesSelector;
return _matcher;
}
|
javascript
|
function _getMatcher (element) {
if (_matcher) {
return _matcher;
}
if (element.matches) {
_matcher = element.matches;
return _matcher;
}
if (element.webkitMatchesSelector) {
_matcher = element.webkitMatchesSelector;
return _matcher;
}
if (element.mozMatchesSelector) {
_matcher = element.mozMatchesSelector;
return _matcher;
}
if (element.msMatchesSelector) {
_matcher = element.msMatchesSelector;
return _matcher;
}
if (element.oMatchesSelector) {
_matcher = element.oMatchesSelector;
return _matcher;
}
// if it doesn't match a native browser method
// fall back to the delegator function
_matcher = Delegator.matchesSelector;
return _matcher;
}
|
[
"function",
"_getMatcher",
"(",
"element",
")",
"{",
"if",
"(",
"_matcher",
")",
"{",
"return",
"_matcher",
";",
"}",
"if",
"(",
"element",
".",
"matches",
")",
"{",
"_matcher",
"=",
"element",
".",
"matches",
";",
"return",
"_matcher",
";",
"}",
"if",
"(",
"element",
".",
"webkitMatchesSelector",
")",
"{",
"_matcher",
"=",
"element",
".",
"webkitMatchesSelector",
";",
"return",
"_matcher",
";",
"}",
"if",
"(",
"element",
".",
"mozMatchesSelector",
")",
"{",
"_matcher",
"=",
"element",
".",
"mozMatchesSelector",
";",
"return",
"_matcher",
";",
"}",
"if",
"(",
"element",
".",
"msMatchesSelector",
")",
"{",
"_matcher",
"=",
"element",
".",
"msMatchesSelector",
";",
"return",
"_matcher",
";",
"}",
"if",
"(",
"element",
".",
"oMatchesSelector",
")",
"{",
"_matcher",
"=",
"element",
".",
"oMatchesSelector",
";",
"return",
"_matcher",
";",
"}",
"// if it doesn't match a native browser method",
"// fall back to the delegator function",
"_matcher",
"=",
"Delegator",
".",
"matchesSelector",
";",
"return",
"_matcher",
";",
"}"
] |
returns function to use for determining if an element
matches a query selector
@returns {Function}
|
[
"returns",
"function",
"to",
"use",
"for",
"determining",
"if",
"an",
"element",
"matches",
"a",
"query",
"selector"
] |
5e644c82d91e2dd6b3b4242ba00713c52f4f553f
|
https://github.com/xinix-technology/xin/blob/5e644c82d91e2dd6b3b4242ba00713c52f4f553f/core/event.js#L33-L67
|
37,453 |
xinix-technology/xin
|
core/event.js
|
_matchesSelector
|
function _matchesSelector (element, selector, boundElement) {
// no selector means this event was bound directly to this element
if (selector === '_root') {
return boundElement;
}
// if we have moved up to the element you bound the event to
// then we have come too far
if (element === boundElement) {
return;
}
if (_getMatcher(element).call(element, selector)) {
return element;
}
// if this element did not match but has a parent we should try
// going up the tree to see if any of the parent elements match
// for example if you are looking for a click on an <a> tag but there
// is a <span> inside of the a tag that it is the target,
// it should still work
if (element.parentNode) {
_level++;
return _matchesSelector(element.parentNode, selector, boundElement);
}
}
|
javascript
|
function _matchesSelector (element, selector, boundElement) {
// no selector means this event was bound directly to this element
if (selector === '_root') {
return boundElement;
}
// if we have moved up to the element you bound the event to
// then we have come too far
if (element === boundElement) {
return;
}
if (_getMatcher(element).call(element, selector)) {
return element;
}
// if this element did not match but has a parent we should try
// going up the tree to see if any of the parent elements match
// for example if you are looking for a click on an <a> tag but there
// is a <span> inside of the a tag that it is the target,
// it should still work
if (element.parentNode) {
_level++;
return _matchesSelector(element.parentNode, selector, boundElement);
}
}
|
[
"function",
"_matchesSelector",
"(",
"element",
",",
"selector",
",",
"boundElement",
")",
"{",
"// no selector means this event was bound directly to this element",
"if",
"(",
"selector",
"===",
"'_root'",
")",
"{",
"return",
"boundElement",
";",
"}",
"// if we have moved up to the element you bound the event to",
"// then we have come too far",
"if",
"(",
"element",
"===",
"boundElement",
")",
"{",
"return",
";",
"}",
"if",
"(",
"_getMatcher",
"(",
"element",
")",
".",
"call",
"(",
"element",
",",
"selector",
")",
")",
"{",
"return",
"element",
";",
"}",
"// if this element did not match but has a parent we should try",
"// going up the tree to see if any of the parent elements match",
"// for example if you are looking for a click on an <a> tag but there",
"// is a <span> inside of the a tag that it is the target,",
"// it should still work",
"if",
"(",
"element",
".",
"parentNode",
")",
"{",
"_level",
"++",
";",
"return",
"_matchesSelector",
"(",
"element",
".",
"parentNode",
",",
"selector",
",",
"boundElement",
")",
";",
"}",
"}"
] |
determines if the specified element matches a given selector
@param {Node} element - the element to compare against the selector
@param {string} selector
@param {Node} boundElement - the element the listener was attached to
@returns {void|Node}
|
[
"determines",
"if",
"the",
"specified",
"element",
"matches",
"a",
"given",
"selector"
] |
5e644c82d91e2dd6b3b4242ba00713c52f4f553f
|
https://github.com/xinix-technology/xin/blob/5e644c82d91e2dd6b3b4242ba00713c52f4f553f/core/event.js#L77-L102
|
37,454 |
xinix-technology/xin
|
core/event.js
|
_bind
|
function _bind (events, selector, callback, remove) {
// fail silently if you pass null or undefined as an alement
// in the Delegator constructor
if (!this.element) {
return;
}
if (!(events instanceof Array)) {
events = [events];
}
if (!callback && typeof (selector) === 'function') {
callback = selector;
selector = '_root';
}
if (selector instanceof window.Element) {
let id;
if (selector.hasAttribute('bind-event-id')) {
id = selector.getAttribute('bind-event-id');
} else {
id = nextEventId();
selector.setAttribute('bind-event-id', id);
}
selector = `[bind-event-id="${id}"]`;
}
let id = this.id;
let i;
function _getGlobalCallback (type) {
return function (e) {
_handleEvent(id, e, type);
};
}
for (i = 0; i < events.length; i++) {
_aliases(events[i]).forEach(alias => {
if (remove) {
_removeHandler(this, alias, selector, callback);
return;
}
if (!_handlers[id] || !_handlers[id][alias]) {
Delegator.addEvent(this, alias, _getGlobalCallback(alias));
}
_addHandler(this, alias, selector, callback);
});
}
return this;
}
|
javascript
|
function _bind (events, selector, callback, remove) {
// fail silently if you pass null or undefined as an alement
// in the Delegator constructor
if (!this.element) {
return;
}
if (!(events instanceof Array)) {
events = [events];
}
if (!callback && typeof (selector) === 'function') {
callback = selector;
selector = '_root';
}
if (selector instanceof window.Element) {
let id;
if (selector.hasAttribute('bind-event-id')) {
id = selector.getAttribute('bind-event-id');
} else {
id = nextEventId();
selector.setAttribute('bind-event-id', id);
}
selector = `[bind-event-id="${id}"]`;
}
let id = this.id;
let i;
function _getGlobalCallback (type) {
return function (e) {
_handleEvent(id, e, type);
};
}
for (i = 0; i < events.length; i++) {
_aliases(events[i]).forEach(alias => {
if (remove) {
_removeHandler(this, alias, selector, callback);
return;
}
if (!_handlers[id] || !_handlers[id][alias]) {
Delegator.addEvent(this, alias, _getGlobalCallback(alias));
}
_addHandler(this, alias, selector, callback);
});
}
return this;
}
|
[
"function",
"_bind",
"(",
"events",
",",
"selector",
",",
"callback",
",",
"remove",
")",
"{",
"// fail silently if you pass null or undefined as an alement",
"// in the Delegator constructor",
"if",
"(",
"!",
"this",
".",
"element",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"(",
"events",
"instanceof",
"Array",
")",
")",
"{",
"events",
"=",
"[",
"events",
"]",
";",
"}",
"if",
"(",
"!",
"callback",
"&&",
"typeof",
"(",
"selector",
")",
"===",
"'function'",
")",
"{",
"callback",
"=",
"selector",
";",
"selector",
"=",
"'_root'",
";",
"}",
"if",
"(",
"selector",
"instanceof",
"window",
".",
"Element",
")",
"{",
"let",
"id",
";",
"if",
"(",
"selector",
".",
"hasAttribute",
"(",
"'bind-event-id'",
")",
")",
"{",
"id",
"=",
"selector",
".",
"getAttribute",
"(",
"'bind-event-id'",
")",
";",
"}",
"else",
"{",
"id",
"=",
"nextEventId",
"(",
")",
";",
"selector",
".",
"setAttribute",
"(",
"'bind-event-id'",
",",
"id",
")",
";",
"}",
"selector",
"=",
"`",
"${",
"id",
"}",
"`",
";",
"}",
"let",
"id",
"=",
"this",
".",
"id",
";",
"let",
"i",
";",
"function",
"_getGlobalCallback",
"(",
"type",
")",
"{",
"return",
"function",
"(",
"e",
")",
"{",
"_handleEvent",
"(",
"id",
",",
"e",
",",
"type",
")",
";",
"}",
";",
"}",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"events",
".",
"length",
";",
"i",
"++",
")",
"{",
"_aliases",
"(",
"events",
"[",
"i",
"]",
")",
".",
"forEach",
"(",
"alias",
"=>",
"{",
"if",
"(",
"remove",
")",
"{",
"_removeHandler",
"(",
"this",
",",
"alias",
",",
"selector",
",",
"callback",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"_handlers",
"[",
"id",
"]",
"||",
"!",
"_handlers",
"[",
"id",
"]",
"[",
"alias",
"]",
")",
"{",
"Delegator",
".",
"addEvent",
"(",
"this",
",",
"alias",
",",
"_getGlobalCallback",
"(",
"alias",
")",
")",
";",
"}",
"_addHandler",
"(",
"this",
",",
"alias",
",",
"selector",
",",
"callback",
")",
";",
"}",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
binds the specified events to the element
@param {string|Array} events
@param {string} selector
@param {Function} callback
@param {boolean=} remove
@returns {Object}
|
[
"binds",
"the",
"specified",
"events",
"to",
"the",
"element"
] |
5e644c82d91e2dd6b3b4242ba00713c52f4f553f
|
https://github.com/xinix-technology/xin/blob/5e644c82d91e2dd6b3b4242ba00713c52f4f553f/core/event.js#L260-L312
|
37,455 |
jimivdw/grunt-mutation-testing
|
lib/reporting/json/JSONReporter.js
|
JSONReporter
|
function JSONReporter(dir, config) {
this._config = config;
var fileName = config.file || DEFAULT_FILE_NAME;
this._filePath = path.join(dir, fileName);
}
|
javascript
|
function JSONReporter(dir, config) {
this._config = config;
var fileName = config.file || DEFAULT_FILE_NAME;
this._filePath = path.join(dir, fileName);
}
|
[
"function",
"JSONReporter",
"(",
"dir",
",",
"config",
")",
"{",
"this",
".",
"_config",
"=",
"config",
";",
"var",
"fileName",
"=",
"config",
".",
"file",
"||",
"DEFAULT_FILE_NAME",
";",
"this",
".",
"_filePath",
"=",
"path",
".",
"join",
"(",
"dir",
",",
"fileName",
")",
";",
"}"
] |
JSON report generator.
@param {string} dir - Report directory
@param {object=} config - Reporter configuration
@constructor
|
[
"JSON",
"report",
"generator",
"."
] |
698b1b20813cd7d46cf44f09cc016f5cd6460f5f
|
https://github.com/jimivdw/grunt-mutation-testing/blob/698b1b20813cd7d46cf44f09cc016f5cd6460f5f/lib/reporting/json/JSONReporter.js#L22-L27
|
37,456 |
jimivdw/grunt-mutation-testing
|
lib/reporting/json/JSONReporter.js
|
getMutationScore
|
function getMutationScore(stats) {
return {
total: (stats.all - stats.survived) / stats.all,
killed: stats.killed / stats.all,
survived: stats.survived / stats.all,
ignored: stats.ignored / stats.all,
untested: stats.untested / stats.all
};
}
|
javascript
|
function getMutationScore(stats) {
return {
total: (stats.all - stats.survived) / stats.all,
killed: stats.killed / stats.all,
survived: stats.survived / stats.all,
ignored: stats.ignored / stats.all,
untested: stats.untested / stats.all
};
}
|
[
"function",
"getMutationScore",
"(",
"stats",
")",
"{",
"return",
"{",
"total",
":",
"(",
"stats",
".",
"all",
"-",
"stats",
".",
"survived",
")",
"/",
"stats",
".",
"all",
",",
"killed",
":",
"stats",
".",
"killed",
"/",
"stats",
".",
"all",
",",
"survived",
":",
"stats",
".",
"survived",
"/",
"stats",
".",
"all",
",",
"ignored",
":",
"stats",
".",
"ignored",
"/",
"stats",
".",
"all",
",",
"untested",
":",
"stats",
".",
"untested",
"/",
"stats",
".",
"all",
"}",
";",
"}"
] |
Calculate the mutation score from a stats object.
@param {object} stats - The stats from which to calculate the score
@returns {{total: number, killed: number, survived: number, ignored: number, untested: number}}
|
[
"Calculate",
"the",
"mutation",
"score",
"from",
"a",
"stats",
"object",
"."
] |
698b1b20813cd7d46cf44f09cc016f5cd6460f5f
|
https://github.com/jimivdw/grunt-mutation-testing/blob/698b1b20813cd7d46cf44f09cc016f5cd6460f5f/lib/reporting/json/JSONReporter.js#L74-L82
|
37,457 |
jimivdw/grunt-mutation-testing
|
lib/reporting/json/JSONReporter.js
|
getResultsPerDir
|
function getResultsPerDir(results) {
/**
* Decorate the results object with the stats for each directory.
*
* @param {object} results - (part of) mutation testing results
* @returns {object} - Mutation test results decorated with stats
*/
function addDirStats(results) {
var dirStats = {
all: 0,
killed: 0,
survived: 0,
ignored: 0,
untested: 0
};
_.forOwn(results, function(result) {
var stats = result.stats || addDirStats(result).stats;
dirStats.all += stats.all;
dirStats.killed += stats.killed;
dirStats.survived += stats.survived;
dirStats.ignored += stats.ignored;
dirStats.untested += stats.untested;
});
results.stats = dirStats;
return results;
}
/**
* Decorate the results object with the mutation score for each directory.
*
* @param {object} results - (part of) mutation testing results, decorated with mutation stats
* @returns {object} - Mutation test results decorated with mutation scores
*/
function addMutationScores(results) {
_.forOwn(results, function(result) {
if(_.has(result, 'stats')) {
addMutationScores(result);
}
});
results.mutationScore = getMutationScore(results.stats);
return results;
}
var resultsPerDir = {};
_.forEach(_.clone(results), function(fileResult) {
_.set(resultsPerDir, IOUtils.getDirectoryList(fileResult.fileName), fileResult);
});
return addMutationScores(addDirStats(resultsPerDir));
}
|
javascript
|
function getResultsPerDir(results) {
/**
* Decorate the results object with the stats for each directory.
*
* @param {object} results - (part of) mutation testing results
* @returns {object} - Mutation test results decorated with stats
*/
function addDirStats(results) {
var dirStats = {
all: 0,
killed: 0,
survived: 0,
ignored: 0,
untested: 0
};
_.forOwn(results, function(result) {
var stats = result.stats || addDirStats(result).stats;
dirStats.all += stats.all;
dirStats.killed += stats.killed;
dirStats.survived += stats.survived;
dirStats.ignored += stats.ignored;
dirStats.untested += stats.untested;
});
results.stats = dirStats;
return results;
}
/**
* Decorate the results object with the mutation score for each directory.
*
* @param {object} results - (part of) mutation testing results, decorated with mutation stats
* @returns {object} - Mutation test results decorated with mutation scores
*/
function addMutationScores(results) {
_.forOwn(results, function(result) {
if(_.has(result, 'stats')) {
addMutationScores(result);
}
});
results.mutationScore = getMutationScore(results.stats);
return results;
}
var resultsPerDir = {};
_.forEach(_.clone(results), function(fileResult) {
_.set(resultsPerDir, IOUtils.getDirectoryList(fileResult.fileName), fileResult);
});
return addMutationScores(addDirStats(resultsPerDir));
}
|
[
"function",
"getResultsPerDir",
"(",
"results",
")",
"{",
"/**\n * Decorate the results object with the stats for each directory.\n *\n * @param {object} results - (part of) mutation testing results\n * @returns {object} - Mutation test results decorated with stats\n */",
"function",
"addDirStats",
"(",
"results",
")",
"{",
"var",
"dirStats",
"=",
"{",
"all",
":",
"0",
",",
"killed",
":",
"0",
",",
"survived",
":",
"0",
",",
"ignored",
":",
"0",
",",
"untested",
":",
"0",
"}",
";",
"_",
".",
"forOwn",
"(",
"results",
",",
"function",
"(",
"result",
")",
"{",
"var",
"stats",
"=",
"result",
".",
"stats",
"||",
"addDirStats",
"(",
"result",
")",
".",
"stats",
";",
"dirStats",
".",
"all",
"+=",
"stats",
".",
"all",
";",
"dirStats",
".",
"killed",
"+=",
"stats",
".",
"killed",
";",
"dirStats",
".",
"survived",
"+=",
"stats",
".",
"survived",
";",
"dirStats",
".",
"ignored",
"+=",
"stats",
".",
"ignored",
";",
"dirStats",
".",
"untested",
"+=",
"stats",
".",
"untested",
";",
"}",
")",
";",
"results",
".",
"stats",
"=",
"dirStats",
";",
"return",
"results",
";",
"}",
"/**\n * Decorate the results object with the mutation score for each directory.\n *\n * @param {object} results - (part of) mutation testing results, decorated with mutation stats\n * @returns {object} - Mutation test results decorated with mutation scores\n */",
"function",
"addMutationScores",
"(",
"results",
")",
"{",
"_",
".",
"forOwn",
"(",
"results",
",",
"function",
"(",
"result",
")",
"{",
"if",
"(",
"_",
".",
"has",
"(",
"result",
",",
"'stats'",
")",
")",
"{",
"addMutationScores",
"(",
"result",
")",
";",
"}",
"}",
")",
";",
"results",
".",
"mutationScore",
"=",
"getMutationScore",
"(",
"results",
".",
"stats",
")",
";",
"return",
"results",
";",
"}",
"var",
"resultsPerDir",
"=",
"{",
"}",
";",
"_",
".",
"forEach",
"(",
"_",
".",
"clone",
"(",
"results",
")",
",",
"function",
"(",
"fileResult",
")",
"{",
"_",
".",
"set",
"(",
"resultsPerDir",
",",
"IOUtils",
".",
"getDirectoryList",
"(",
"fileResult",
".",
"fileName",
")",
",",
"fileResult",
")",
";",
"}",
")",
";",
"return",
"addMutationScores",
"(",
"addDirStats",
"(",
"resultsPerDir",
")",
")",
";",
"}"
] |
Calculate the mutation test results per directory.
@param {object} results - Mutation testing results
@returns {object} - The mutation test results per directory
|
[
"Calculate",
"the",
"mutation",
"test",
"results",
"per",
"directory",
"."
] |
698b1b20813cd7d46cf44f09cc016f5cd6460f5f
|
https://github.com/jimivdw/grunt-mutation-testing/blob/698b1b20813cd7d46cf44f09cc016f5cd6460f5f/lib/reporting/json/JSONReporter.js#L90-L144
|
37,458 |
jimivdw/grunt-mutation-testing
|
lib/reporting/json/JSONReporter.js
|
addDirStats
|
function addDirStats(results) {
var dirStats = {
all: 0,
killed: 0,
survived: 0,
ignored: 0,
untested: 0
};
_.forOwn(results, function(result) {
var stats = result.stats || addDirStats(result).stats;
dirStats.all += stats.all;
dirStats.killed += stats.killed;
dirStats.survived += stats.survived;
dirStats.ignored += stats.ignored;
dirStats.untested += stats.untested;
});
results.stats = dirStats;
return results;
}
|
javascript
|
function addDirStats(results) {
var dirStats = {
all: 0,
killed: 0,
survived: 0,
ignored: 0,
untested: 0
};
_.forOwn(results, function(result) {
var stats = result.stats || addDirStats(result).stats;
dirStats.all += stats.all;
dirStats.killed += stats.killed;
dirStats.survived += stats.survived;
dirStats.ignored += stats.ignored;
dirStats.untested += stats.untested;
});
results.stats = dirStats;
return results;
}
|
[
"function",
"addDirStats",
"(",
"results",
")",
"{",
"var",
"dirStats",
"=",
"{",
"all",
":",
"0",
",",
"killed",
":",
"0",
",",
"survived",
":",
"0",
",",
"ignored",
":",
"0",
",",
"untested",
":",
"0",
"}",
";",
"_",
".",
"forOwn",
"(",
"results",
",",
"function",
"(",
"result",
")",
"{",
"var",
"stats",
"=",
"result",
".",
"stats",
"||",
"addDirStats",
"(",
"result",
")",
".",
"stats",
";",
"dirStats",
".",
"all",
"+=",
"stats",
".",
"all",
";",
"dirStats",
".",
"killed",
"+=",
"stats",
".",
"killed",
";",
"dirStats",
".",
"survived",
"+=",
"stats",
".",
"survived",
";",
"dirStats",
".",
"ignored",
"+=",
"stats",
".",
"ignored",
";",
"dirStats",
".",
"untested",
"+=",
"stats",
".",
"untested",
";",
"}",
")",
";",
"results",
".",
"stats",
"=",
"dirStats",
";",
"return",
"results",
";",
"}"
] |
Decorate the results object with the stats for each directory.
@param {object} results - (part of) mutation testing results
@returns {object} - Mutation test results decorated with stats
|
[
"Decorate",
"the",
"results",
"object",
"with",
"the",
"stats",
"for",
"each",
"directory",
"."
] |
698b1b20813cd7d46cf44f09cc016f5cd6460f5f
|
https://github.com/jimivdw/grunt-mutation-testing/blob/698b1b20813cd7d46cf44f09cc016f5cd6460f5f/lib/reporting/json/JSONReporter.js#L98-L118
|
37,459 |
jimivdw/grunt-mutation-testing
|
lib/reporting/json/JSONReporter.js
|
addMutationScores
|
function addMutationScores(results) {
_.forOwn(results, function(result) {
if(_.has(result, 'stats')) {
addMutationScores(result);
}
});
results.mutationScore = getMutationScore(results.stats);
return results;
}
|
javascript
|
function addMutationScores(results) {
_.forOwn(results, function(result) {
if(_.has(result, 'stats')) {
addMutationScores(result);
}
});
results.mutationScore = getMutationScore(results.stats);
return results;
}
|
[
"function",
"addMutationScores",
"(",
"results",
")",
"{",
"_",
".",
"forOwn",
"(",
"results",
",",
"function",
"(",
"result",
")",
"{",
"if",
"(",
"_",
".",
"has",
"(",
"result",
",",
"'stats'",
")",
")",
"{",
"addMutationScores",
"(",
"result",
")",
";",
"}",
"}",
")",
";",
"results",
".",
"mutationScore",
"=",
"getMutationScore",
"(",
"results",
".",
"stats",
")",
";",
"return",
"results",
";",
"}"
] |
Decorate the results object with the mutation score for each directory.
@param {object} results - (part of) mutation testing results, decorated with mutation stats
@returns {object} - Mutation test results decorated with mutation scores
|
[
"Decorate",
"the",
"results",
"object",
"with",
"the",
"mutation",
"score",
"for",
"each",
"directory",
"."
] |
698b1b20813cd7d46cf44f09cc016f5cd6460f5f
|
https://github.com/jimivdw/grunt-mutation-testing/blob/698b1b20813cd7d46cf44f09cc016f5cd6460f5f/lib/reporting/json/JSONReporter.js#L126-L135
|
37,460 |
petermbenjamin/exploitalert
|
src/search.js
|
search
|
function search(platform) {
return new Promise((resolve, reject) => {
if (!platform || platform === '') reject(new Error('platform cannot be blank'));
const options = {
method: 'GET',
hostname: 'www.exploitalert.com',
path: `/api/search-exploit?name=${platform}`,
};
const req = http.request(options, (res) => {
const chunks = [];
res.on('data', (chunk) => {
chunks.push(chunk);
});
res.on('end', () => {
const body = Buffer.concat(chunks);
resolve(JSON.parse(body));
});
});
req.on('error', err => reject(err));
req.end();
});
}
|
javascript
|
function search(platform) {
return new Promise((resolve, reject) => {
if (!platform || platform === '') reject(new Error('platform cannot be blank'));
const options = {
method: 'GET',
hostname: 'www.exploitalert.com',
path: `/api/search-exploit?name=${platform}`,
};
const req = http.request(options, (res) => {
const chunks = [];
res.on('data', (chunk) => {
chunks.push(chunk);
});
res.on('end', () => {
const body = Buffer.concat(chunks);
resolve(JSON.parse(body));
});
});
req.on('error', err => reject(err));
req.end();
});
}
|
[
"function",
"search",
"(",
"platform",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"if",
"(",
"!",
"platform",
"||",
"platform",
"===",
"''",
")",
"reject",
"(",
"new",
"Error",
"(",
"'platform cannot be blank'",
")",
")",
";",
"const",
"options",
"=",
"{",
"method",
":",
"'GET'",
",",
"hostname",
":",
"'www.exploitalert.com'",
",",
"path",
":",
"`",
"${",
"platform",
"}",
"`",
",",
"}",
";",
"const",
"req",
"=",
"http",
".",
"request",
"(",
"options",
",",
"(",
"res",
")",
"=>",
"{",
"const",
"chunks",
"=",
"[",
"]",
";",
"res",
".",
"on",
"(",
"'data'",
",",
"(",
"chunk",
")",
"=>",
"{",
"chunks",
".",
"push",
"(",
"chunk",
")",
";",
"}",
")",
";",
"res",
".",
"on",
"(",
"'end'",
",",
"(",
")",
"=>",
"{",
"const",
"body",
"=",
"Buffer",
".",
"concat",
"(",
"chunks",
")",
";",
"resolve",
"(",
"JSON",
".",
"parse",
"(",
"body",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"req",
".",
"on",
"(",
"'error'",
",",
"err",
"=>",
"reject",
"(",
"err",
")",
")",
";",
"req",
".",
"end",
"(",
")",
";",
"}",
")",
";",
"}"
] |
Searches exploitalert db
@param {string} platform - the platform to search for
|
[
"Searches",
"exploitalert",
"db"
] |
a250d497a6be13db968b72ab0139028d6d1744ac
|
https://github.com/petermbenjamin/exploitalert/blob/a250d497a6be13db968b72ab0139028d6d1744ac/src/search.js#L7-L32
|
37,461 |
joshfire/woodman
|
lib/logger.js
|
function (name, loggerContext) {
/**
* Logger name
*/
this.name = name;
/**
* Reference to the logger context that created this logger
*
* The reference is used to create appenders and layouts when
* configuration is applied.
*/
this.loggerContext = loggerContext;
/**
* Parent logger. All loggers have a parent except the root logger
*/
this.parent = null;
/**
* Children loggers. Mostly used during initialization to propagate
* the configuration.
*/
this.children = [];
/**
* Appenders associated with the logger. Set during initialization
*/
this.appenders = [];
/**
* Logger filter. Set during initialization
*/
this.filter = null;
/**
* The trace level of the logger. Log events whose level is below that
* level are logged. Others are discarded.
*/
this.level = 'inherit';
/**
* Additivity flag. Log events are not propagated to the parent logger
* if the flag is not set.
*/
this.additive = true;
/**
* Function used to determine whether a log level is below the
* trace level of the logger
*/
if (this.loggerContext) {
this.isBelow = function (level, referenceLevel) {
return this.loggerContext.logLevel.isBelow(level, referenceLevel);
};
// Set trace functions for all registered levels
utils.each(this.loggerContext.logLevel.getLevels(), function (level) {
var self = this;
if (!this[level]) {
this[level] = function () {
self.traceAtLevel(level, arguments);
};
}
}, this);
}
else {
this.isBelow = function () {
return true;
};
}
}
|
javascript
|
function (name, loggerContext) {
/**
* Logger name
*/
this.name = name;
/**
* Reference to the logger context that created this logger
*
* The reference is used to create appenders and layouts when
* configuration is applied.
*/
this.loggerContext = loggerContext;
/**
* Parent logger. All loggers have a parent except the root logger
*/
this.parent = null;
/**
* Children loggers. Mostly used during initialization to propagate
* the configuration.
*/
this.children = [];
/**
* Appenders associated with the logger. Set during initialization
*/
this.appenders = [];
/**
* Logger filter. Set during initialization
*/
this.filter = null;
/**
* The trace level of the logger. Log events whose level is below that
* level are logged. Others are discarded.
*/
this.level = 'inherit';
/**
* Additivity flag. Log events are not propagated to the parent logger
* if the flag is not set.
*/
this.additive = true;
/**
* Function used to determine whether a log level is below the
* trace level of the logger
*/
if (this.loggerContext) {
this.isBelow = function (level, referenceLevel) {
return this.loggerContext.logLevel.isBelow(level, referenceLevel);
};
// Set trace functions for all registered levels
utils.each(this.loggerContext.logLevel.getLevels(), function (level) {
var self = this;
if (!this[level]) {
this[level] = function () {
self.traceAtLevel(level, arguments);
};
}
}, this);
}
else {
this.isBelow = function () {
return true;
};
}
}
|
[
"function",
"(",
"name",
",",
"loggerContext",
")",
"{",
"/**\n * Logger name\n */",
"this",
".",
"name",
"=",
"name",
";",
"/**\n * Reference to the logger context that created this logger\n *\n * The reference is used to create appenders and layouts when\n * configuration is applied.\n */",
"this",
".",
"loggerContext",
"=",
"loggerContext",
";",
"/**\n * Parent logger. All loggers have a parent except the root logger\n */",
"this",
".",
"parent",
"=",
"null",
";",
"/**\n * Children loggers. Mostly used during initialization to propagate\n * the configuration.\n */",
"this",
".",
"children",
"=",
"[",
"]",
";",
"/**\n * Appenders associated with the logger. Set during initialization\n */",
"this",
".",
"appenders",
"=",
"[",
"]",
";",
"/**\n * Logger filter. Set during initialization\n */",
"this",
".",
"filter",
"=",
"null",
";",
"/**\n * The trace level of the logger. Log events whose level is below that\n * level are logged. Others are discarded.\n */",
"this",
".",
"level",
"=",
"'inherit'",
";",
"/**\n * Additivity flag. Log events are not propagated to the parent logger\n * if the flag is not set.\n */",
"this",
".",
"additive",
"=",
"true",
";",
"/**\n * Function used to determine whether a log level is below the\n * trace level of the logger\n */",
"if",
"(",
"this",
".",
"loggerContext",
")",
"{",
"this",
".",
"isBelow",
"=",
"function",
"(",
"level",
",",
"referenceLevel",
")",
"{",
"return",
"this",
".",
"loggerContext",
".",
"logLevel",
".",
"isBelow",
"(",
"level",
",",
"referenceLevel",
")",
";",
"}",
";",
"// Set trace functions for all registered levels",
"utils",
".",
"each",
"(",
"this",
".",
"loggerContext",
".",
"logLevel",
".",
"getLevels",
"(",
")",
",",
"function",
"(",
"level",
")",
"{",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"!",
"this",
"[",
"level",
"]",
")",
"{",
"this",
"[",
"level",
"]",
"=",
"function",
"(",
")",
"{",
"self",
".",
"traceAtLevel",
"(",
"level",
",",
"arguments",
")",
";",
"}",
";",
"}",
"}",
",",
"this",
")",
";",
"}",
"else",
"{",
"this",
".",
"isBelow",
"=",
"function",
"(",
")",
"{",
"return",
"true",
";",
"}",
";",
"}",
"}"
] |
Definition of the Logger class
@constructor
|
[
"Definition",
"of",
"the",
"Logger",
"class"
] |
fdc05de2124388780924980e6f27bf4483056d18
|
https://github.com/joshfire/woodman/blob/fdc05de2124388780924980e6f27bf4483056d18/lib/logger.js#L34-L105
|
|
37,462 |
AntonyThorpe/knockout-apollo
|
demo/bower_components/ko.plus/dist/ko.plus.js
|
function () {
//check if we are able to execute
if (!canExecuteWrapper.call(options.context || this)) {
//dont attach any global handlers
return instantDeferred(false, null, options.context || this).promise();
}
//notify that we are running and clear any existing error message
isRunning(true);
failed(false);
failMessage('');
//try to invoke the action and get a reference to the deferred object
var promise;
try {
promise = options.action.apply(options.context || this, arguments);
//if the returned result is *not* a promise, create a new one that is already resolved
if (!isPromise(promise)) {
promise = instantDeferred(true, promise, options.context || this).promise();
}
} catch (error) {
promise = instantDeferred(false, error, options.context || this).promise();
}
//set up our callbacks
callbacks.always.forEach(function(callback) {
promise.then(callback, callback);
});
callbacks.fail.forEach(function(callback) {
promise.then(null, callback);
});
callbacks.done.forEach(function(callback) {
promise.then(callback);
});
return promise;
}
|
javascript
|
function () {
//check if we are able to execute
if (!canExecuteWrapper.call(options.context || this)) {
//dont attach any global handlers
return instantDeferred(false, null, options.context || this).promise();
}
//notify that we are running and clear any existing error message
isRunning(true);
failed(false);
failMessage('');
//try to invoke the action and get a reference to the deferred object
var promise;
try {
promise = options.action.apply(options.context || this, arguments);
//if the returned result is *not* a promise, create a new one that is already resolved
if (!isPromise(promise)) {
promise = instantDeferred(true, promise, options.context || this).promise();
}
} catch (error) {
promise = instantDeferred(false, error, options.context || this).promise();
}
//set up our callbacks
callbacks.always.forEach(function(callback) {
promise.then(callback, callback);
});
callbacks.fail.forEach(function(callback) {
promise.then(null, callback);
});
callbacks.done.forEach(function(callback) {
promise.then(callback);
});
return promise;
}
|
[
"function",
"(",
")",
"{",
"//check if we are able to execute\r",
"if",
"(",
"!",
"canExecuteWrapper",
".",
"call",
"(",
"options",
".",
"context",
"||",
"this",
")",
")",
"{",
"//dont attach any global handlers\r",
"return",
"instantDeferred",
"(",
"false",
",",
"null",
",",
"options",
".",
"context",
"||",
"this",
")",
".",
"promise",
"(",
")",
";",
"}",
"//notify that we are running and clear any existing error message\r",
"isRunning",
"(",
"true",
")",
";",
"failed",
"(",
"false",
")",
";",
"failMessage",
"(",
"''",
")",
";",
"//try to invoke the action and get a reference to the deferred object\r",
"var",
"promise",
";",
"try",
"{",
"promise",
"=",
"options",
".",
"action",
".",
"apply",
"(",
"options",
".",
"context",
"||",
"this",
",",
"arguments",
")",
";",
"//if the returned result is *not* a promise, create a new one that is already resolved\r",
"if",
"(",
"!",
"isPromise",
"(",
"promise",
")",
")",
"{",
"promise",
"=",
"instantDeferred",
"(",
"true",
",",
"promise",
",",
"options",
".",
"context",
"||",
"this",
")",
".",
"promise",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"error",
")",
"{",
"promise",
"=",
"instantDeferred",
"(",
"false",
",",
"error",
",",
"options",
".",
"context",
"||",
"this",
")",
".",
"promise",
"(",
")",
";",
"}",
"//set up our callbacks\r",
"callbacks",
".",
"always",
".",
"forEach",
"(",
"function",
"(",
"callback",
")",
"{",
"promise",
".",
"then",
"(",
"callback",
",",
"callback",
")",
";",
"}",
")",
";",
"callbacks",
".",
"fail",
".",
"forEach",
"(",
"function",
"(",
"callback",
")",
"{",
"promise",
".",
"then",
"(",
"null",
",",
"callback",
")",
";",
"}",
")",
";",
"callbacks",
".",
"done",
".",
"forEach",
"(",
"function",
"(",
"callback",
")",
"{",
"promise",
".",
"then",
"(",
"callback",
")",
";",
"}",
")",
";",
"return",
"promise",
";",
"}"
] |
execute function (and return object
|
[
"execute",
"function",
"(",
"and",
"return",
"object"
] |
573a7caea7e41877710e69bac001771a6ea86d33
|
https://github.com/AntonyThorpe/knockout-apollo/blob/573a7caea7e41877710e69bac001771a6ea86d33/demo/bower_components/ko.plus/dist/ko.plus.js#L58-L96
|
|
37,463 |
AntonyThorpe/knockout-apollo
|
demo/bower_components/ko.plus/dist/ko.plus.js
|
function (callback) {
callbacks.fail.push(function () {
var result = callback.apply(this, arguments);
if (result) {
failMessage(result);
}
});
return execute;
}
|
javascript
|
function (callback) {
callbacks.fail.push(function () {
var result = callback.apply(this, arguments);
if (result) {
failMessage(result);
}
});
return execute;
}
|
[
"function",
"(",
"callback",
")",
"{",
"callbacks",
".",
"fail",
".",
"push",
"(",
"function",
"(",
")",
"{",
"var",
"result",
"=",
"callback",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"if",
"(",
"result",
")",
"{",
"failMessage",
"(",
"result",
")",
";",
"}",
"}",
")",
";",
"return",
"execute",
";",
"}"
] |
function used to append failure callbacks
|
[
"function",
"used",
"to",
"append",
"failure",
"callbacks"
] |
573a7caea7e41877710e69bac001771a6ea86d33
|
https://github.com/AntonyThorpe/knockout-apollo/blob/573a7caea7e41877710e69bac001771a6ea86d33/demo/bower_components/ko.plus/dist/ko.plus.js#L121-L129
|
|
37,464 |
rfrench/chai-uuid
|
index.js
|
getRegEx
|
function getRegEx(version) {
switch(version.toLowerCase())
{
case 'v1':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[1][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
case 'v2':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[2][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
case 'v3':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[3][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
case 'v4':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
case 'v5':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[5][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
default:
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
}
}
|
javascript
|
function getRegEx(version) {
switch(version.toLowerCase())
{
case 'v1':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[1][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
case 'v2':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[2][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
case 'v3':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[3][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
case 'v4':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
case 'v5':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[5][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
default:
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
}
}
|
[
"function",
"getRegEx",
"(",
"version",
")",
"{",
"switch",
"(",
"version",
".",
"toLowerCase",
"(",
")",
")",
"{",
"case",
"'v1'",
":",
"return",
"/",
"^[0-9A-F]{8}-[0-9A-F]{4}-[1][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$",
"/",
"i",
";",
"case",
"'v2'",
":",
"return",
"/",
"^[0-9A-F]{8}-[0-9A-F]{4}-[2][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$",
"/",
"i",
";",
"case",
"'v3'",
":",
"return",
"/",
"^[0-9A-F]{8}-[0-9A-F]{4}-[3][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$",
"/",
"i",
";",
"case",
"'v4'",
":",
"return",
"/",
"^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$",
"/",
"i",
";",
"case",
"'v5'",
":",
"return",
"/",
"^[0-9A-F]{8}-[0-9A-F]{4}-[5][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$",
"/",
"i",
";",
"default",
":",
"return",
"/",
"^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",
"/",
"i",
";",
"}",
"}"
] |
Returns a valid regex for validating the UUID
@param {String} version
@return {Regex}
|
[
"Returns",
"a",
"valid",
"regex",
"for",
"validating",
"the",
"UUID"
] |
48062e1fc2f8e3dd149f70db6f085650f8aea1b6
|
https://github.com/rfrench/chai-uuid/blob/48062e1fc2f8e3dd149f70db6f085650f8aea1b6/index.js#L12-L28
|
37,465 |
rfrench/chai-uuid
|
index.js
|
uuid
|
function uuid(version) {
var v = (version) ? version : '';
// verify its a valid string
this.assert(
(typeof this._obj === 'string' || this._obj instanceof String),
'expected #{this} to be of type #{exp} but got #{act}',
'expected #{this} to not be of type #{exp}',
'string',
typeof(this._obj)
);
// assert it is a valid uuid
var regex = getRegEx(v);
this.assert(
regex.test(this._obj),
'expected #{this} to be a valid UUID ' + v,
'expected #{this} to not be a UUID ' + v
);
}
|
javascript
|
function uuid(version) {
var v = (version) ? version : '';
// verify its a valid string
this.assert(
(typeof this._obj === 'string' || this._obj instanceof String),
'expected #{this} to be of type #{exp} but got #{act}',
'expected #{this} to not be of type #{exp}',
'string',
typeof(this._obj)
);
// assert it is a valid uuid
var regex = getRegEx(v);
this.assert(
regex.test(this._obj),
'expected #{this} to be a valid UUID ' + v,
'expected #{this} to not be a UUID ' + v
);
}
|
[
"function",
"uuid",
"(",
"version",
")",
"{",
"var",
"v",
"=",
"(",
"version",
")",
"?",
"version",
":",
"''",
";",
"// verify its a valid string",
"this",
".",
"assert",
"(",
"(",
"typeof",
"this",
".",
"_obj",
"===",
"'string'",
"||",
"this",
".",
"_obj",
"instanceof",
"String",
")",
",",
"'expected #{this} to be of type #{exp} but got #{act}'",
",",
"'expected #{this} to not be of type #{exp}'",
",",
"'string'",
",",
"typeof",
"(",
"this",
".",
"_obj",
")",
")",
";",
"// assert it is a valid uuid",
"var",
"regex",
"=",
"getRegEx",
"(",
"v",
")",
";",
"this",
".",
"assert",
"(",
"regex",
".",
"test",
"(",
"this",
".",
"_obj",
")",
",",
"'expected #{this} to be a valid UUID '",
"+",
"v",
",",
"'expected #{this} to not be a UUID '",
"+",
"v",
")",
";",
"}"
] |
Validates a uuid
@param {String} version
|
[
"Validates",
"a",
"uuid"
] |
48062e1fc2f8e3dd149f70db6f085650f8aea1b6
|
https://github.com/rfrench/chai-uuid/blob/48062e1fc2f8e3dd149f70db6f085650f8aea1b6/index.js#L34-L53
|
37,466 |
jimivdw/grunt-mutation-testing
|
lib/karma/KarmaCodeSpecsMatcher.js
|
KarmaCodeSpecsMatcher
|
function KarmaCodeSpecsMatcher(serverPool, config) {
this._serverPool = serverPool;
this._config = _.merge({ karma: { waitForCoverageTime: 5 } }, config);
this._coverageDir = path.join(config.karma.basePath, 'coverage');
}
|
javascript
|
function KarmaCodeSpecsMatcher(serverPool, config) {
this._serverPool = serverPool;
this._config = _.merge({ karma: { waitForCoverageTime: 5 } }, config);
this._coverageDir = path.join(config.karma.basePath, 'coverage');
}
|
[
"function",
"KarmaCodeSpecsMatcher",
"(",
"serverPool",
",",
"config",
")",
"{",
"this",
".",
"_serverPool",
"=",
"serverPool",
";",
"this",
".",
"_config",
"=",
"_",
".",
"merge",
"(",
"{",
"karma",
":",
"{",
"waitForCoverageTime",
":",
"5",
"}",
"}",
",",
"config",
")",
";",
"this",
".",
"_coverageDir",
"=",
"path",
".",
"join",
"(",
"config",
".",
"karma",
".",
"basePath",
",",
"'coverage'",
")",
";",
"}"
] |
Constructor for the KarmaCodeSpecsMatcher
@param {KarmaServerPool} serverPool Karma server pool used to manage the Karma servers
@param {object} config Configuration object
@constructor
|
[
"Constructor",
"for",
"the",
"KarmaCodeSpecsMatcher"
] |
698b1b20813cd7d46cf44f09cc016f5cd6460f5f
|
https://github.com/jimivdw/grunt-mutation-testing/blob/698b1b20813cd7d46cf44f09cc016f5cd6460f5f/lib/karma/KarmaCodeSpecsMatcher.js#L27-L31
|
37,467 |
jimivdw/grunt-mutation-testing
|
utils/ScopeUtils.js
|
processScopeVariables
|
function processScopeVariables(variableDeclaration, loopVariables) {
var identifiers = [], exclusiveCombination;
_.forEach(variableDeclaration.declarations, function(declaration) {
identifiers.push(declaration.id.name);
});
exclusiveCombination = _.xor(loopVariables, identifiers);
return _.intersection(loopVariables, exclusiveCombination);
}
|
javascript
|
function processScopeVariables(variableDeclaration, loopVariables) {
var identifiers = [], exclusiveCombination;
_.forEach(variableDeclaration.declarations, function(declaration) {
identifiers.push(declaration.id.name);
});
exclusiveCombination = _.xor(loopVariables, identifiers);
return _.intersection(loopVariables, exclusiveCombination);
}
|
[
"function",
"processScopeVariables",
"(",
"variableDeclaration",
",",
"loopVariables",
")",
"{",
"var",
"identifiers",
"=",
"[",
"]",
",",
"exclusiveCombination",
";",
"_",
".",
"forEach",
"(",
"variableDeclaration",
".",
"declarations",
",",
"function",
"(",
"declaration",
")",
"{",
"identifiers",
".",
"push",
"(",
"declaration",
".",
"id",
".",
"name",
")",
";",
"}",
")",
";",
"exclusiveCombination",
"=",
"_",
".",
"xor",
"(",
"loopVariables",
",",
"identifiers",
")",
";",
"return",
"_",
".",
"intersection",
"(",
"loopVariables",
",",
"exclusiveCombination",
")",
";",
"}"
] |
Filters Identifiers within given variableDeclaration out of the loopVariables array.
Filtering occurs as follows:
XOR : (intermediate) result + variable identifiers found => a combined array minus identifiers that overlap
INTERSECTION: (intermediate) result + combined array to filter out variables that weren't in the original loopVariables array
@param {object} variableDeclaration declaration block of one or more variables
@param {loopVariables} loopVariables list of variables that are part of a loop invariable and should therefore not undergo mutations - unless overridden by another variable in the current function scope
|
[
"Filters",
"Identifiers",
"within",
"given",
"variableDeclaration",
"out",
"of",
"the",
"loopVariables",
"array",
"."
] |
698b1b20813cd7d46cf44f09cc016f5cd6460f5f
|
https://github.com/jimivdw/grunt-mutation-testing/blob/698b1b20813cd7d46cf44f09cc016f5cd6460f5f/utils/ScopeUtils.js#L56-L65
|
37,468 |
cb1kenobi/gawk
|
src/index.js
|
filterObject
|
function filterObject(gobj, filter) {
let found = true;
let obj = gobj;
// find the value we're interested in
for (let i = 0, len = filter.length; obj && typeof obj === 'object' && i < len; i++) {
if (!obj.hasOwnProperty(filter[i])) {
found = false;
obj = undefined;
break;
}
obj = obj[filter[i]];
}
return { found, obj };
}
|
javascript
|
function filterObject(gobj, filter) {
let found = true;
let obj = gobj;
// find the value we're interested in
for (let i = 0, len = filter.length; obj && typeof obj === 'object' && i < len; i++) {
if (!obj.hasOwnProperty(filter[i])) {
found = false;
obj = undefined;
break;
}
obj = obj[filter[i]];
}
return { found, obj };
}
|
[
"function",
"filterObject",
"(",
"gobj",
",",
"filter",
")",
"{",
"let",
"found",
"=",
"true",
";",
"let",
"obj",
"=",
"gobj",
";",
"// find the value we're interested in",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"len",
"=",
"filter",
".",
"length",
";",
"obj",
"&&",
"typeof",
"obj",
"===",
"'object'",
"&&",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"obj",
".",
"hasOwnProperty",
"(",
"filter",
"[",
"i",
"]",
")",
")",
"{",
"found",
"=",
"false",
";",
"obj",
"=",
"undefined",
";",
"break",
";",
"}",
"obj",
"=",
"obj",
"[",
"filter",
"[",
"i",
"]",
"]",
";",
"}",
"return",
"{",
"found",
",",
"obj",
"}",
";",
"}"
] |
Filters the specified gawk object.
@param {Object} gobj - A gawked object.
@param {Array.<String>} filter - The filter to apply to the gawked object.
@returns {Object}
|
[
"Filters",
"the",
"specified",
"gawk",
"object",
"."
] |
17b75ec735907dda1920b03a8ccc7b3821381cd1
|
https://github.com/cb1kenobi/gawk/blob/17b75ec735907dda1920b03a8ccc7b3821381cd1/src/index.js#L298-L313
|
37,469 |
cb1kenobi/gawk
|
src/index.js
|
hashValue
|
function hashValue(it) {
const str = JSON.stringify(it) || '';
let hash = 5381;
let i = str.length;
while (i) {
hash = hash * 33 ^ str.charCodeAt(--i);
}
return hash >>> 0;
}
|
javascript
|
function hashValue(it) {
const str = JSON.stringify(it) || '';
let hash = 5381;
let i = str.length;
while (i) {
hash = hash * 33 ^ str.charCodeAt(--i);
}
return hash >>> 0;
}
|
[
"function",
"hashValue",
"(",
"it",
")",
"{",
"const",
"str",
"=",
"JSON",
".",
"stringify",
"(",
"it",
")",
"||",
"''",
";",
"let",
"hash",
"=",
"5381",
";",
"let",
"i",
"=",
"str",
".",
"length",
";",
"while",
"(",
"i",
")",
"{",
"hash",
"=",
"hash",
"*",
"33",
"^",
"str",
".",
"charCodeAt",
"(",
"--",
"i",
")",
";",
"}",
"return",
"hash",
">>>",
"0",
";",
"}"
] |
Hashes a value quick and dirty.
@param {*} it - A value to hash.
@returns {Number}
|
[
"Hashes",
"a",
"value",
"quick",
"and",
"dirty",
"."
] |
17b75ec735907dda1920b03a8ccc7b3821381cd1
|
https://github.com/cb1kenobi/gawk/blob/17b75ec735907dda1920b03a8ccc7b3821381cd1/src/index.js#L321-L329
|
37,470 |
cb1kenobi/gawk
|
src/index.js
|
notify
|
function notify(gobj, source) {
const state = gobj.__gawk__;
if (source === undefined) {
source = gobj;
}
// if we're paused, add this object to the list of objects that may have changed
if (state.queue) {
state.queue.add(gobj);
return;
}
// notify all of this object's listeners
if (state.listeners) {
for (const [ listener, filter ] of state.listeners) {
if (filter) {
const { found, obj } = filterObject(gobj, filter);
// compute the hash of the stringified value
const hash = hashValue(obj);
// check if the value changed
if ((found && !state.previous) || (state.previous && hash !== state.previous.get(listener))) {
listener(obj, source);
}
if (!state.previous) {
state.previous = new WeakMap();
}
state.previous.set(listener, hash);
} else {
listener(gobj, source);
}
}
}
// notify all of this object's parents
if (state.parents) {
for (const parent of state.parents) {
notify(parent, source);
}
}
}
|
javascript
|
function notify(gobj, source) {
const state = gobj.__gawk__;
if (source === undefined) {
source = gobj;
}
// if we're paused, add this object to the list of objects that may have changed
if (state.queue) {
state.queue.add(gobj);
return;
}
// notify all of this object's listeners
if (state.listeners) {
for (const [ listener, filter ] of state.listeners) {
if (filter) {
const { found, obj } = filterObject(gobj, filter);
// compute the hash of the stringified value
const hash = hashValue(obj);
// check if the value changed
if ((found && !state.previous) || (state.previous && hash !== state.previous.get(listener))) {
listener(obj, source);
}
if (!state.previous) {
state.previous = new WeakMap();
}
state.previous.set(listener, hash);
} else {
listener(gobj, source);
}
}
}
// notify all of this object's parents
if (state.parents) {
for (const parent of state.parents) {
notify(parent, source);
}
}
}
|
[
"function",
"notify",
"(",
"gobj",
",",
"source",
")",
"{",
"const",
"state",
"=",
"gobj",
".",
"__gawk__",
";",
"if",
"(",
"source",
"===",
"undefined",
")",
"{",
"source",
"=",
"gobj",
";",
"}",
"// if we're paused, add this object to the list of objects that may have changed",
"if",
"(",
"state",
".",
"queue",
")",
"{",
"state",
".",
"queue",
".",
"add",
"(",
"gobj",
")",
";",
"return",
";",
"}",
"// notify all of this object's listeners",
"if",
"(",
"state",
".",
"listeners",
")",
"{",
"for",
"(",
"const",
"[",
"listener",
",",
"filter",
"]",
"of",
"state",
".",
"listeners",
")",
"{",
"if",
"(",
"filter",
")",
"{",
"const",
"{",
"found",
",",
"obj",
"}",
"=",
"filterObject",
"(",
"gobj",
",",
"filter",
")",
";",
"// compute the hash of the stringified value",
"const",
"hash",
"=",
"hashValue",
"(",
"obj",
")",
";",
"// check if the value changed",
"if",
"(",
"(",
"found",
"&&",
"!",
"state",
".",
"previous",
")",
"||",
"(",
"state",
".",
"previous",
"&&",
"hash",
"!==",
"state",
".",
"previous",
".",
"get",
"(",
"listener",
")",
")",
")",
"{",
"listener",
"(",
"obj",
",",
"source",
")",
";",
"}",
"if",
"(",
"!",
"state",
".",
"previous",
")",
"{",
"state",
".",
"previous",
"=",
"new",
"WeakMap",
"(",
")",
";",
"}",
"state",
".",
"previous",
".",
"set",
"(",
"listener",
",",
"hash",
")",
";",
"}",
"else",
"{",
"listener",
"(",
"gobj",
",",
"source",
")",
";",
"}",
"}",
"}",
"// notify all of this object's parents",
"if",
"(",
"state",
".",
"parents",
")",
"{",
"for",
"(",
"const",
"parent",
"of",
"state",
".",
"parents",
")",
"{",
"notify",
"(",
"parent",
",",
"source",
")",
";",
"}",
"}",
"}"
] |
Dispatches change notifications to the listeners.
@param {Object} gobj - The gawked object.
@param {Object|Array} [source] - The gawk object that was modified.
|
[
"Dispatches",
"change",
"notifications",
"to",
"the",
"listeners",
"."
] |
17b75ec735907dda1920b03a8ccc7b3821381cd1
|
https://github.com/cb1kenobi/gawk/blob/17b75ec735907dda1920b03a8ccc7b3821381cd1/src/index.js#L337-L381
|
37,471 |
cb1kenobi/gawk
|
src/index.js
|
copyListeners
|
function copyListeners(dest, src, compareFn) {
if (isGawked(src) && src.__gawk__.listeners) {
if (dest.__gawk__.listeners) {
for (const [ listener, filter ] of src.__gawk__.listeners) {
dest.__gawk__.listeners.set(listener, filter);
}
} else {
dest.__gawk__.listeners = new Map(src.__gawk__.listeners);
}
}
if (!compareFn) {
return;
}
if (Array.isArray(dest)) {
const visited = [];
for (let i = 0, len = dest.length; i < len; i++) {
if (dest[i] !== null && typeof dest[i] === 'object') {
// try to find a match in src
for (let j = 0, len2 = src.length; j < len2; j++) {
if (!visited[j] && src[j] !== null && typeof src[j] === 'object' && compareFn(dest[i], src[j])) {
visited[j] = 1;
copyListeners(dest[i], src[j], compareFn);
break;
}
}
}
}
return;
}
for (const key of Object.getOwnPropertyNames(dest)) {
if (key === '__gawk__') {
continue;
}
if (dest[key] && typeof dest[key] === 'object') {
copyListeners(dest[key], src[key], compareFn);
}
}
}
|
javascript
|
function copyListeners(dest, src, compareFn) {
if (isGawked(src) && src.__gawk__.listeners) {
if (dest.__gawk__.listeners) {
for (const [ listener, filter ] of src.__gawk__.listeners) {
dest.__gawk__.listeners.set(listener, filter);
}
} else {
dest.__gawk__.listeners = new Map(src.__gawk__.listeners);
}
}
if (!compareFn) {
return;
}
if (Array.isArray(dest)) {
const visited = [];
for (let i = 0, len = dest.length; i < len; i++) {
if (dest[i] !== null && typeof dest[i] === 'object') {
// try to find a match in src
for (let j = 0, len2 = src.length; j < len2; j++) {
if (!visited[j] && src[j] !== null && typeof src[j] === 'object' && compareFn(dest[i], src[j])) {
visited[j] = 1;
copyListeners(dest[i], src[j], compareFn);
break;
}
}
}
}
return;
}
for (const key of Object.getOwnPropertyNames(dest)) {
if (key === '__gawk__') {
continue;
}
if (dest[key] && typeof dest[key] === 'object') {
copyListeners(dest[key], src[key], compareFn);
}
}
}
|
[
"function",
"copyListeners",
"(",
"dest",
",",
"src",
",",
"compareFn",
")",
"{",
"if",
"(",
"isGawked",
"(",
"src",
")",
"&&",
"src",
".",
"__gawk__",
".",
"listeners",
")",
"{",
"if",
"(",
"dest",
".",
"__gawk__",
".",
"listeners",
")",
"{",
"for",
"(",
"const",
"[",
"listener",
",",
"filter",
"]",
"of",
"src",
".",
"__gawk__",
".",
"listeners",
")",
"{",
"dest",
".",
"__gawk__",
".",
"listeners",
".",
"set",
"(",
"listener",
",",
"filter",
")",
";",
"}",
"}",
"else",
"{",
"dest",
".",
"__gawk__",
".",
"listeners",
"=",
"new",
"Map",
"(",
"src",
".",
"__gawk__",
".",
"listeners",
")",
";",
"}",
"}",
"if",
"(",
"!",
"compareFn",
")",
"{",
"return",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"dest",
")",
")",
"{",
"const",
"visited",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"len",
"=",
"dest",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"dest",
"[",
"i",
"]",
"!==",
"null",
"&&",
"typeof",
"dest",
"[",
"i",
"]",
"===",
"'object'",
")",
"{",
"// try to find a match in src",
"for",
"(",
"let",
"j",
"=",
"0",
",",
"len2",
"=",
"src",
".",
"length",
";",
"j",
"<",
"len2",
";",
"j",
"++",
")",
"{",
"if",
"(",
"!",
"visited",
"[",
"j",
"]",
"&&",
"src",
"[",
"j",
"]",
"!==",
"null",
"&&",
"typeof",
"src",
"[",
"j",
"]",
"===",
"'object'",
"&&",
"compareFn",
"(",
"dest",
"[",
"i",
"]",
",",
"src",
"[",
"j",
"]",
")",
")",
"{",
"visited",
"[",
"j",
"]",
"=",
"1",
";",
"copyListeners",
"(",
"dest",
"[",
"i",
"]",
",",
"src",
"[",
"j",
"]",
",",
"compareFn",
")",
";",
"break",
";",
"}",
"}",
"}",
"}",
"return",
";",
"}",
"for",
"(",
"const",
"key",
"of",
"Object",
".",
"getOwnPropertyNames",
"(",
"dest",
")",
")",
"{",
"if",
"(",
"key",
"===",
"'__gawk__'",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"dest",
"[",
"key",
"]",
"&&",
"typeof",
"dest",
"[",
"key",
"]",
"===",
"'object'",
")",
"{",
"copyListeners",
"(",
"dest",
"[",
"key",
"]",
",",
"src",
"[",
"key",
"]",
",",
"compareFn",
")",
";",
"}",
"}",
"}"
] |
Copies listeners from a source gawked object ot a destination gawked object. Note that the
arguments must both be objects and only the `dest` is required to already be gawked.
@param {Object|Array} dest - A gawked object to copy the listeners to.
@param {Object|Array} src - An object to copy the listeners from.
@param {Function} [compareFn] - Doubles up as a deep copy flag and a function to call to compare
a source and destination array elements to check if they are the same.
|
[
"Copies",
"listeners",
"from",
"a",
"source",
"gawked",
"object",
"ot",
"a",
"destination",
"gawked",
"object",
".",
"Note",
"that",
"the",
"arguments",
"must",
"both",
"be",
"objects",
"and",
"only",
"the",
"dest",
"is",
"required",
"to",
"already",
"be",
"gawked",
"."
] |
17b75ec735907dda1920b03a8ccc7b3821381cd1
|
https://github.com/cb1kenobi/gawk/blob/17b75ec735907dda1920b03a8ccc7b3821381cd1/src/index.js#L392-L433
|
37,472 |
cb1kenobi/gawk
|
src/index.js
|
mix
|
function mix(objs, deep) {
const gobj = gawk(objs.shift());
if (!isGawked(gobj) || Array.isArray(gobj)) {
throw new TypeError('Expected destination to be a gawked object');
}
if (!objs.length) {
return gobj;
}
// validate the objects are good
for (const obj of objs) {
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
throw new TypeError('Expected merge source to be an object');
}
}
// we need to detach the parent and all listeners so that they will be notified after everything
// has been merged
gobj.__gawk__.pause();
/**
* Mix an object or gawked object into a gawked object.
* @param {Object} gobj - The destination gawked object.
* @param {Object} src - The source object to copy from.
*/
const mixer = (gobj, src) => {
for (const key of Object.getOwnPropertyNames(src)) {
if (key === '__gawk__') {
continue;
}
const srcValue = src[key];
if (deep && srcValue !== null && typeof srcValue === 'object' && !Array.isArray(srcValue)) {
if (!isGawked(gobj[key])) {
gobj[key] = gawk({}, gobj);
}
mixer(gobj[key], srcValue);
} else if (Array.isArray(gobj[key]) && Array.isArray(srcValue)) {
// overwrite destination with new values
gobj[key].splice(0, gobj[key].length, ...srcValue);
} else {
gobj[key] = gawk(srcValue, gobj);
}
}
};
for (const obj of objs) {
mixer(gobj, obj);
}
gobj.__gawk__.resume();
return gobj;
}
|
javascript
|
function mix(objs, deep) {
const gobj = gawk(objs.shift());
if (!isGawked(gobj) || Array.isArray(gobj)) {
throw new TypeError('Expected destination to be a gawked object');
}
if (!objs.length) {
return gobj;
}
// validate the objects are good
for (const obj of objs) {
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
throw new TypeError('Expected merge source to be an object');
}
}
// we need to detach the parent and all listeners so that they will be notified after everything
// has been merged
gobj.__gawk__.pause();
/**
* Mix an object or gawked object into a gawked object.
* @param {Object} gobj - The destination gawked object.
* @param {Object} src - The source object to copy from.
*/
const mixer = (gobj, src) => {
for (const key of Object.getOwnPropertyNames(src)) {
if (key === '__gawk__') {
continue;
}
const srcValue = src[key];
if (deep && srcValue !== null && typeof srcValue === 'object' && !Array.isArray(srcValue)) {
if (!isGawked(gobj[key])) {
gobj[key] = gawk({}, gobj);
}
mixer(gobj[key], srcValue);
} else if (Array.isArray(gobj[key]) && Array.isArray(srcValue)) {
// overwrite destination with new values
gobj[key].splice(0, gobj[key].length, ...srcValue);
} else {
gobj[key] = gawk(srcValue, gobj);
}
}
};
for (const obj of objs) {
mixer(gobj, obj);
}
gobj.__gawk__.resume();
return gobj;
}
|
[
"function",
"mix",
"(",
"objs",
",",
"deep",
")",
"{",
"const",
"gobj",
"=",
"gawk",
"(",
"objs",
".",
"shift",
"(",
")",
")",
";",
"if",
"(",
"!",
"isGawked",
"(",
"gobj",
")",
"||",
"Array",
".",
"isArray",
"(",
"gobj",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Expected destination to be a gawked object'",
")",
";",
"}",
"if",
"(",
"!",
"objs",
".",
"length",
")",
"{",
"return",
"gobj",
";",
"}",
"// validate the objects are good",
"for",
"(",
"const",
"obj",
"of",
"objs",
")",
"{",
"if",
"(",
"!",
"obj",
"||",
"typeof",
"obj",
"!==",
"'object'",
"||",
"Array",
".",
"isArray",
"(",
"obj",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Expected merge source to be an object'",
")",
";",
"}",
"}",
"// we need to detach the parent and all listeners so that they will be notified after everything",
"// has been merged",
"gobj",
".",
"__gawk__",
".",
"pause",
"(",
")",
";",
"/**\n\t * Mix an object or gawked object into a gawked object.\n\t * @param {Object} gobj - The destination gawked object.\n\t * @param {Object} src - The source object to copy from.\n\t */",
"const",
"mixer",
"=",
"(",
"gobj",
",",
"src",
")",
"=>",
"{",
"for",
"(",
"const",
"key",
"of",
"Object",
".",
"getOwnPropertyNames",
"(",
"src",
")",
")",
"{",
"if",
"(",
"key",
"===",
"'__gawk__'",
")",
"{",
"continue",
";",
"}",
"const",
"srcValue",
"=",
"src",
"[",
"key",
"]",
";",
"if",
"(",
"deep",
"&&",
"srcValue",
"!==",
"null",
"&&",
"typeof",
"srcValue",
"===",
"'object'",
"&&",
"!",
"Array",
".",
"isArray",
"(",
"srcValue",
")",
")",
"{",
"if",
"(",
"!",
"isGawked",
"(",
"gobj",
"[",
"key",
"]",
")",
")",
"{",
"gobj",
"[",
"key",
"]",
"=",
"gawk",
"(",
"{",
"}",
",",
"gobj",
")",
";",
"}",
"mixer",
"(",
"gobj",
"[",
"key",
"]",
",",
"srcValue",
")",
";",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"gobj",
"[",
"key",
"]",
")",
"&&",
"Array",
".",
"isArray",
"(",
"srcValue",
")",
")",
"{",
"// overwrite destination with new values",
"gobj",
"[",
"key",
"]",
".",
"splice",
"(",
"0",
",",
"gobj",
"[",
"key",
"]",
".",
"length",
",",
"...",
"srcValue",
")",
";",
"}",
"else",
"{",
"gobj",
"[",
"key",
"]",
"=",
"gawk",
"(",
"srcValue",
",",
"gobj",
")",
";",
"}",
"}",
"}",
";",
"for",
"(",
"const",
"obj",
"of",
"objs",
")",
"{",
"mixer",
"(",
"gobj",
",",
"obj",
")",
";",
"}",
"gobj",
".",
"__gawk__",
".",
"resume",
"(",
")",
";",
"return",
"gobj",
";",
"}"
] |
Mixes an array of objects or gawked objects into the specified gawked object.
@param {Array.<Object>} objs - An array of objects or gawked objects.
@param {Boolean} [deep=false] - When true, mixes subobjects into each other.
@returns {Object}
|
[
"Mixes",
"an",
"array",
"of",
"objects",
"or",
"gawked",
"objects",
"into",
"the",
"specified",
"gawked",
"object",
"."
] |
17b75ec735907dda1920b03a8ccc7b3821381cd1
|
https://github.com/cb1kenobi/gawk/blob/17b75ec735907dda1920b03a8ccc7b3821381cd1/src/index.js#L658-L713
|
37,473 |
AntonyThorpe/knockout-apollo
|
demo/bower_components/knockoutjs/src/subscribables/dependentObservable.js
|
computedBeginDependencyDetectionCallback
|
function computedBeginDependencyDetectionCallback(subscribable, id) {
var computedObservable = this.computedObservable,
state = computedObservable[computedState];
if (!state.isDisposed) {
if (this.disposalCount && this.disposalCandidates[id]) {
// Don't want to dispose this subscription, as it's still being used
computedObservable.addDependencyTracking(id, subscribable, this.disposalCandidates[id]);
this.disposalCandidates[id] = null; // No need to actually delete the property - disposalCandidates is a transient object anyway
--this.disposalCount;
} else if (!state.dependencyTracking[id]) {
// Brand new subscription - add it
computedObservable.addDependencyTracking(id, subscribable, state.isSleeping ? { _target: subscribable } : computedObservable.subscribeToDependency(subscribable));
}
// If the observable we've accessed has a pending notification, ensure we get notified of the actual final value (bypass equality checks)
if (subscribable._notificationIsPending) {
subscribable._notifyNextChangeIfValueIsDifferent();
}
}
}
|
javascript
|
function computedBeginDependencyDetectionCallback(subscribable, id) {
var computedObservable = this.computedObservable,
state = computedObservable[computedState];
if (!state.isDisposed) {
if (this.disposalCount && this.disposalCandidates[id]) {
// Don't want to dispose this subscription, as it's still being used
computedObservable.addDependencyTracking(id, subscribable, this.disposalCandidates[id]);
this.disposalCandidates[id] = null; // No need to actually delete the property - disposalCandidates is a transient object anyway
--this.disposalCount;
} else if (!state.dependencyTracking[id]) {
// Brand new subscription - add it
computedObservable.addDependencyTracking(id, subscribable, state.isSleeping ? { _target: subscribable } : computedObservable.subscribeToDependency(subscribable));
}
// If the observable we've accessed has a pending notification, ensure we get notified of the actual final value (bypass equality checks)
if (subscribable._notificationIsPending) {
subscribable._notifyNextChangeIfValueIsDifferent();
}
}
}
|
[
"function",
"computedBeginDependencyDetectionCallback",
"(",
"subscribable",
",",
"id",
")",
"{",
"var",
"computedObservable",
"=",
"this",
".",
"computedObservable",
",",
"state",
"=",
"computedObservable",
"[",
"computedState",
"]",
";",
"if",
"(",
"!",
"state",
".",
"isDisposed",
")",
"{",
"if",
"(",
"this",
".",
"disposalCount",
"&&",
"this",
".",
"disposalCandidates",
"[",
"id",
"]",
")",
"{",
"// Don't want to dispose this subscription, as it's still being used",
"computedObservable",
".",
"addDependencyTracking",
"(",
"id",
",",
"subscribable",
",",
"this",
".",
"disposalCandidates",
"[",
"id",
"]",
")",
";",
"this",
".",
"disposalCandidates",
"[",
"id",
"]",
"=",
"null",
";",
"// No need to actually delete the property - disposalCandidates is a transient object anyway",
"--",
"this",
".",
"disposalCount",
";",
"}",
"else",
"if",
"(",
"!",
"state",
".",
"dependencyTracking",
"[",
"id",
"]",
")",
"{",
"// Brand new subscription - add it",
"computedObservable",
".",
"addDependencyTracking",
"(",
"id",
",",
"subscribable",
",",
"state",
".",
"isSleeping",
"?",
"{",
"_target",
":",
"subscribable",
"}",
":",
"computedObservable",
".",
"subscribeToDependency",
"(",
"subscribable",
")",
")",
";",
"}",
"// If the observable we've accessed has a pending notification, ensure we get notified of the actual final value (bypass equality checks)",
"if",
"(",
"subscribable",
".",
"_notificationIsPending",
")",
"{",
"subscribable",
".",
"_notifyNextChangeIfValueIsDifferent",
"(",
")",
";",
"}",
"}",
"}"
] |
This function gets called each time a dependency is detected while evaluating a computed. It's factored out as a shared function to avoid creating unnecessary function instances during evaluation.
|
[
"This",
"function",
"gets",
"called",
"each",
"time",
"a",
"dependency",
"is",
"detected",
"while",
"evaluating",
"a",
"computed",
".",
"It",
"s",
"factored",
"out",
"as",
"a",
"shared",
"function",
"to",
"avoid",
"creating",
"unnecessary",
"function",
"instances",
"during",
"evaluation",
"."
] |
573a7caea7e41877710e69bac001771a6ea86d33
|
https://github.com/AntonyThorpe/knockout-apollo/blob/573a7caea7e41877710e69bac001771a6ea86d33/demo/bower_components/knockoutjs/src/subscribables/dependentObservable.js#L126-L144
|
37,474 |
rjrodger/seneca-perm
|
express-example/public/js/cookies.js
|
function (sKey) {
return decodeURI(document.cookie.replace(new RegExp('(?:(?:^|.*;)\\s*' + encodeURI(sKey).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=\\s*([^;]*).*$)|^.*$'), '$1')) || null;
}
|
javascript
|
function (sKey) {
return decodeURI(document.cookie.replace(new RegExp('(?:(?:^|.*;)\\s*' + encodeURI(sKey).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=\\s*([^;]*).*$)|^.*$'), '$1')) || null;
}
|
[
"function",
"(",
"sKey",
")",
"{",
"return",
"decodeURI",
"(",
"document",
".",
"cookie",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"'(?:(?:^|.*;)\\\\s*'",
"+",
"encodeURI",
"(",
"sKey",
")",
".",
"replace",
"(",
"/",
"[\\-\\.\\+\\*]",
"/",
"g",
",",
"'\\\\$&'",
")",
"+",
"'\\\\s*\\\\=\\\\s*([^;]*).*$)|^.*$'",
")",
",",
"'$1'",
")",
")",
"||",
"null",
";",
"}"
] |
Read a cookie. If the cookie doesn't exist a null value will be returned.
### Syntax
Cookies.getItem(name)
### Example usage
Cookies.getItem('test1');
Cookies.getItem('test5');
Cookies.getItem('test1');
Cookies.getItem('test5');
Cookies.getItem('unexistingCookie');
Cookies.getItem();
### Parameters
@param sKey - name - the name of the cookie to read (string).
@returns {string|null}
|
[
"Read",
"a",
"cookie",
".",
"If",
"the",
"cookie",
"doesn",
"t",
"exist",
"a",
"null",
"value",
"will",
"be",
"returned",
"."
] |
cca9169e0d40d9796e11d30c2c878486ecfdcb4a
|
https://github.com/rjrodger/seneca-perm/blob/cca9169e0d40d9796e11d30c2c878486ecfdcb4a/express-example/public/js/cookies.js#L63-L65
|
|
37,475 |
rjrodger/seneca-perm
|
express-example/public/js/cookies.js
|
function (sKey, sPath) {
if (!sKey || !this.hasItem(sKey)) { return false; }
document.cookie = encodeURI(sKey) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT' + (sPath ? '; path=' + sPath : '');
return true;
}
|
javascript
|
function (sKey, sPath) {
if (!sKey || !this.hasItem(sKey)) { return false; }
document.cookie = encodeURI(sKey) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT' + (sPath ? '; path=' + sPath : '');
return true;
}
|
[
"function",
"(",
"sKey",
",",
"sPath",
")",
"{",
"if",
"(",
"!",
"sKey",
"||",
"!",
"this",
".",
"hasItem",
"(",
"sKey",
")",
")",
"{",
"return",
"false",
";",
"}",
"document",
".",
"cookie",
"=",
"encodeURI",
"(",
"sKey",
")",
"+",
"'=; expires=Thu, 01 Jan 1970 00:00:00 GMT'",
"+",
"(",
"sPath",
"?",
"'; path='",
"+",
"sPath",
":",
"''",
")",
";",
"return",
"true",
";",
"}"
] |
Delete a cookie
### Syntax
Cookies.removeItem(name[, path])
### Example usage
Cookies.removeItem('test1');
Cookies.removeItem('test5', '/home');
### Parameters
@param sKey - name - the name of the cookie to remove (string).
@param sPath - path (optional) - e.g., "/", "/mydir"; if not specified, defaults to the current path of the current document location (string or null).
@returns {boolean}
|
[
"Delete",
"a",
"cookie"
] |
cca9169e0d40d9796e11d30c2c878486ecfdcb4a
|
https://github.com/rjrodger/seneca-perm/blob/cca9169e0d40d9796e11d30c2c878486ecfdcb4a/express-example/public/js/cookies.js#L141-L145
|
|
37,476 |
knockout/tko.binding.if
|
dist/tko.binding.if.js
|
bindingContext
|
function bindingContext(dataItemOrAccessor, parentContext, dataItemAlias, extendCallback, settings) {
var self = this,
isFunc = typeof(dataItemOrAccessor) == "function" && !isObservable(dataItemOrAccessor),
nodes,
subscribable;
// The binding context object includes static properties for the current, parent, and root view models.
// If a view model is actually stored in an observable, the corresponding binding context object, and
// any child contexts, must be updated when the view model is changed.
function updateContext() {
// Most of the time, the context will directly get a view model object, but if a function is given,
// we call the function to retrieve the view model. If the function accesses any observables or returns
// an observable, the dependency is tracked, and those observables can later cause the binding
// context to be updated.
var dataItemOrObservable = isFunc ? dataItemOrAccessor() : dataItemOrAccessor,
dataItem = unwrap(dataItemOrObservable);
if (parentContext) {
// When a "parent" context is given, register a dependency on the parent context. Thus whenever the
// parent context is updated, this context will also be updated.
if (parentContext._subscribable)
parentContext._subscribable();
// Copy $root and any custom properties from the parent context
extend(self, parentContext);
// Because the above copy overwrites our own properties, we need to reset them.
self._subscribable = subscribable;
} else {
self.$parents = [];
self.$root = dataItem;
// Export 'ko' in the binding context so it will be available in bindings and templates
// even if 'ko' isn't exported as a global, such as when using an AMD loader.
// See https://github.com/SteveSanderson/knockout/issues/490
self.ko = options.knockoutInstance;
}
self.$rawData = dataItemOrObservable;
self.$data = dataItem;
if (dataItemAlias)
self[dataItemAlias] = dataItem;
// The extendCallback function is provided when creating a child context or extending a context.
// It handles the specific actions needed to finish setting up the binding context. Actions in this
// function could also add dependencies to this binding context.
if (extendCallback)
extendCallback(self, parentContext, dataItem);
return self.$data;
}
function disposeWhen() {
return nodes && !anyDomNodeIsAttachedToDocument(nodes);
}
if (settings && settings.exportDependencies) {
// The "exportDependencies" option means that the calling code will track any dependencies and re-create
// the binding context when they change.
updateContext();
return;
}
subscribable = computed(updateContext, null, { disposeWhen: disposeWhen, disposeWhenNodeIsRemoved: true });
// At this point, the binding context has been initialized, and the "subscribable" computed observable is
// subscribed to any observables that were accessed in the process. If there is nothing to track, the
// computed will be inactive, and we can safely throw it away. If it's active, the computed is stored in
// the context object.
if (subscribable.isActive()) {
self._subscribable = subscribable;
// Always notify because even if the model ($data) hasn't changed, other context properties might have changed
subscribable.equalityComparer = null;
// We need to be able to dispose of this computed observable when it's no longer needed. This would be
// easy if we had a single node to watch, but binding contexts can be used by many different nodes, and
// we cannot assume that those nodes have any relation to each other. So instead we track any node that
// the context is attached to, and dispose the computed when all of those nodes have been cleaned.
// Add properties to *subscribable* instead of *self* because any properties added to *self* may be overwritten on updates
nodes = [];
subscribable._addNode = function(node) {
nodes.push(node);
addDisposeCallback(node, function(node) {
arrayRemoveItem(nodes, node);
if (!nodes.length) {
subscribable.dispose();
self._subscribable = subscribable = undefined;
}
});
};
}
}
|
javascript
|
function bindingContext(dataItemOrAccessor, parentContext, dataItemAlias, extendCallback, settings) {
var self = this,
isFunc = typeof(dataItemOrAccessor) == "function" && !isObservable(dataItemOrAccessor),
nodes,
subscribable;
// The binding context object includes static properties for the current, parent, and root view models.
// If a view model is actually stored in an observable, the corresponding binding context object, and
// any child contexts, must be updated when the view model is changed.
function updateContext() {
// Most of the time, the context will directly get a view model object, but if a function is given,
// we call the function to retrieve the view model. If the function accesses any observables or returns
// an observable, the dependency is tracked, and those observables can later cause the binding
// context to be updated.
var dataItemOrObservable = isFunc ? dataItemOrAccessor() : dataItemOrAccessor,
dataItem = unwrap(dataItemOrObservable);
if (parentContext) {
// When a "parent" context is given, register a dependency on the parent context. Thus whenever the
// parent context is updated, this context will also be updated.
if (parentContext._subscribable)
parentContext._subscribable();
// Copy $root and any custom properties from the parent context
extend(self, parentContext);
// Because the above copy overwrites our own properties, we need to reset them.
self._subscribable = subscribable;
} else {
self.$parents = [];
self.$root = dataItem;
// Export 'ko' in the binding context so it will be available in bindings and templates
// even if 'ko' isn't exported as a global, such as when using an AMD loader.
// See https://github.com/SteveSanderson/knockout/issues/490
self.ko = options.knockoutInstance;
}
self.$rawData = dataItemOrObservable;
self.$data = dataItem;
if (dataItemAlias)
self[dataItemAlias] = dataItem;
// The extendCallback function is provided when creating a child context or extending a context.
// It handles the specific actions needed to finish setting up the binding context. Actions in this
// function could also add dependencies to this binding context.
if (extendCallback)
extendCallback(self, parentContext, dataItem);
return self.$data;
}
function disposeWhen() {
return nodes && !anyDomNodeIsAttachedToDocument(nodes);
}
if (settings && settings.exportDependencies) {
// The "exportDependencies" option means that the calling code will track any dependencies and re-create
// the binding context when they change.
updateContext();
return;
}
subscribable = computed(updateContext, null, { disposeWhen: disposeWhen, disposeWhenNodeIsRemoved: true });
// At this point, the binding context has been initialized, and the "subscribable" computed observable is
// subscribed to any observables that were accessed in the process. If there is nothing to track, the
// computed will be inactive, and we can safely throw it away. If it's active, the computed is stored in
// the context object.
if (subscribable.isActive()) {
self._subscribable = subscribable;
// Always notify because even if the model ($data) hasn't changed, other context properties might have changed
subscribable.equalityComparer = null;
// We need to be able to dispose of this computed observable when it's no longer needed. This would be
// easy if we had a single node to watch, but binding contexts can be used by many different nodes, and
// we cannot assume that those nodes have any relation to each other. So instead we track any node that
// the context is attached to, and dispose the computed when all of those nodes have been cleaned.
// Add properties to *subscribable* instead of *self* because any properties added to *self* may be overwritten on updates
nodes = [];
subscribable._addNode = function(node) {
nodes.push(node);
addDisposeCallback(node, function(node) {
arrayRemoveItem(nodes, node);
if (!nodes.length) {
subscribable.dispose();
self._subscribable = subscribable = undefined;
}
});
};
}
}
|
[
"function",
"bindingContext",
"(",
"dataItemOrAccessor",
",",
"parentContext",
",",
"dataItemAlias",
",",
"extendCallback",
",",
"settings",
")",
"{",
"var",
"self",
"=",
"this",
",",
"isFunc",
"=",
"typeof",
"(",
"dataItemOrAccessor",
")",
"==",
"\"function\"",
"&&",
"!",
"isObservable",
"(",
"dataItemOrAccessor",
")",
",",
"nodes",
",",
"subscribable",
";",
"// The binding context object includes static properties for the current, parent, and root view models.",
"// If a view model is actually stored in an observable, the corresponding binding context object, and",
"// any child contexts, must be updated when the view model is changed.",
"function",
"updateContext",
"(",
")",
"{",
"// Most of the time, the context will directly get a view model object, but if a function is given,",
"// we call the function to retrieve the view model. If the function accesses any observables or returns",
"// an observable, the dependency is tracked, and those observables can later cause the binding",
"// context to be updated.",
"var",
"dataItemOrObservable",
"=",
"isFunc",
"?",
"dataItemOrAccessor",
"(",
")",
":",
"dataItemOrAccessor",
",",
"dataItem",
"=",
"unwrap",
"(",
"dataItemOrObservable",
")",
";",
"if",
"(",
"parentContext",
")",
"{",
"// When a \"parent\" context is given, register a dependency on the parent context. Thus whenever the",
"// parent context is updated, this context will also be updated.",
"if",
"(",
"parentContext",
".",
"_subscribable",
")",
"parentContext",
".",
"_subscribable",
"(",
")",
";",
"// Copy $root and any custom properties from the parent context",
"extend",
"(",
"self",
",",
"parentContext",
")",
";",
"// Because the above copy overwrites our own properties, we need to reset them.",
"self",
".",
"_subscribable",
"=",
"subscribable",
";",
"}",
"else",
"{",
"self",
".",
"$parents",
"=",
"[",
"]",
";",
"self",
".",
"$root",
"=",
"dataItem",
";",
"// Export 'ko' in the binding context so it will be available in bindings and templates",
"// even if 'ko' isn't exported as a global, such as when using an AMD loader.",
"// See https://github.com/SteveSanderson/knockout/issues/490",
"self",
".",
"ko",
"=",
"options",
".",
"knockoutInstance",
";",
"}",
"self",
".",
"$rawData",
"=",
"dataItemOrObservable",
";",
"self",
".",
"$data",
"=",
"dataItem",
";",
"if",
"(",
"dataItemAlias",
")",
"self",
"[",
"dataItemAlias",
"]",
"=",
"dataItem",
";",
"// The extendCallback function is provided when creating a child context or extending a context.",
"// It handles the specific actions needed to finish setting up the binding context. Actions in this",
"// function could also add dependencies to this binding context.",
"if",
"(",
"extendCallback",
")",
"extendCallback",
"(",
"self",
",",
"parentContext",
",",
"dataItem",
")",
";",
"return",
"self",
".",
"$data",
";",
"}",
"function",
"disposeWhen",
"(",
")",
"{",
"return",
"nodes",
"&&",
"!",
"anyDomNodeIsAttachedToDocument",
"(",
"nodes",
")",
";",
"}",
"if",
"(",
"settings",
"&&",
"settings",
".",
"exportDependencies",
")",
"{",
"// The \"exportDependencies\" option means that the calling code will track any dependencies and re-create",
"// the binding context when they change.",
"updateContext",
"(",
")",
";",
"return",
";",
"}",
"subscribable",
"=",
"computed",
"(",
"updateContext",
",",
"null",
",",
"{",
"disposeWhen",
":",
"disposeWhen",
",",
"disposeWhenNodeIsRemoved",
":",
"true",
"}",
")",
";",
"// At this point, the binding context has been initialized, and the \"subscribable\" computed observable is",
"// subscribed to any observables that were accessed in the process. If there is nothing to track, the",
"// computed will be inactive, and we can safely throw it away. If it's active, the computed is stored in",
"// the context object.",
"if",
"(",
"subscribable",
".",
"isActive",
"(",
")",
")",
"{",
"self",
".",
"_subscribable",
"=",
"subscribable",
";",
"// Always notify because even if the model ($data) hasn't changed, other context properties might have changed",
"subscribable",
".",
"equalityComparer",
"=",
"null",
";",
"// We need to be able to dispose of this computed observable when it's no longer needed. This would be",
"// easy if we had a single node to watch, but binding contexts can be used by many different nodes, and",
"// we cannot assume that those nodes have any relation to each other. So instead we track any node that",
"// the context is attached to, and dispose the computed when all of those nodes have been cleaned.",
"// Add properties to *subscribable* instead of *self* because any properties added to *self* may be overwritten on updates",
"nodes",
"=",
"[",
"]",
";",
"subscribable",
".",
"_addNode",
"=",
"function",
"(",
"node",
")",
"{",
"nodes",
".",
"push",
"(",
"node",
")",
";",
"addDisposeCallback",
"(",
"node",
",",
"function",
"(",
"node",
")",
"{",
"arrayRemoveItem",
"(",
"nodes",
",",
"node",
")",
";",
"if",
"(",
"!",
"nodes",
".",
"length",
")",
"{",
"subscribable",
".",
"dispose",
"(",
")",
";",
"self",
".",
"_subscribable",
"=",
"subscribable",
"=",
"undefined",
";",
"}",
"}",
")",
";",
"}",
";",
"}",
"}"
] |
The bindingContext constructor is only called directly to create the root context. For child contexts, use bindingContext.createChildContext or bindingContext.extend.
|
[
"The",
"bindingContext",
"constructor",
"is",
"only",
"called",
"directly",
"to",
"create",
"the",
"root",
"context",
".",
"For",
"child",
"contexts",
"use",
"bindingContext",
".",
"createChildContext",
"or",
"bindingContext",
".",
"extend",
"."
] |
ab33a6a6fd393077243068d1e79f0be838016cc5
|
https://github.com/knockout/tko.binding.if/blob/ab33a6a6fd393077243068d1e79f0be838016cc5/dist/tko.binding.if.js#L1942-L2035
|
37,477 |
knockout/tko.binding.if
|
dist/tko.binding.if.js
|
updateContext
|
function updateContext() {
// Most of the time, the context will directly get a view model object, but if a function is given,
// we call the function to retrieve the view model. If the function accesses any observables or returns
// an observable, the dependency is tracked, and those observables can later cause the binding
// context to be updated.
var dataItemOrObservable = isFunc ? dataItemOrAccessor() : dataItemOrAccessor,
dataItem = unwrap(dataItemOrObservable);
if (parentContext) {
// When a "parent" context is given, register a dependency on the parent context. Thus whenever the
// parent context is updated, this context will also be updated.
if (parentContext._subscribable)
parentContext._subscribable();
// Copy $root and any custom properties from the parent context
extend(self, parentContext);
// Because the above copy overwrites our own properties, we need to reset them.
self._subscribable = subscribable;
} else {
self.$parents = [];
self.$root = dataItem;
// Export 'ko' in the binding context so it will be available in bindings and templates
// even if 'ko' isn't exported as a global, such as when using an AMD loader.
// See https://github.com/SteveSanderson/knockout/issues/490
self.ko = options.knockoutInstance;
}
self.$rawData = dataItemOrObservable;
self.$data = dataItem;
if (dataItemAlias)
self[dataItemAlias] = dataItem;
// The extendCallback function is provided when creating a child context or extending a context.
// It handles the specific actions needed to finish setting up the binding context. Actions in this
// function could also add dependencies to this binding context.
if (extendCallback)
extendCallback(self, parentContext, dataItem);
return self.$data;
}
|
javascript
|
function updateContext() {
// Most of the time, the context will directly get a view model object, but if a function is given,
// we call the function to retrieve the view model. If the function accesses any observables or returns
// an observable, the dependency is tracked, and those observables can later cause the binding
// context to be updated.
var dataItemOrObservable = isFunc ? dataItemOrAccessor() : dataItemOrAccessor,
dataItem = unwrap(dataItemOrObservable);
if (parentContext) {
// When a "parent" context is given, register a dependency on the parent context. Thus whenever the
// parent context is updated, this context will also be updated.
if (parentContext._subscribable)
parentContext._subscribable();
// Copy $root and any custom properties from the parent context
extend(self, parentContext);
// Because the above copy overwrites our own properties, we need to reset them.
self._subscribable = subscribable;
} else {
self.$parents = [];
self.$root = dataItem;
// Export 'ko' in the binding context so it will be available in bindings and templates
// even if 'ko' isn't exported as a global, such as when using an AMD loader.
// See https://github.com/SteveSanderson/knockout/issues/490
self.ko = options.knockoutInstance;
}
self.$rawData = dataItemOrObservable;
self.$data = dataItem;
if (dataItemAlias)
self[dataItemAlias] = dataItem;
// The extendCallback function is provided when creating a child context or extending a context.
// It handles the specific actions needed to finish setting up the binding context. Actions in this
// function could also add dependencies to this binding context.
if (extendCallback)
extendCallback(self, parentContext, dataItem);
return self.$data;
}
|
[
"function",
"updateContext",
"(",
")",
"{",
"// Most of the time, the context will directly get a view model object, but if a function is given,",
"// we call the function to retrieve the view model. If the function accesses any observables or returns",
"// an observable, the dependency is tracked, and those observables can later cause the binding",
"// context to be updated.",
"var",
"dataItemOrObservable",
"=",
"isFunc",
"?",
"dataItemOrAccessor",
"(",
")",
":",
"dataItemOrAccessor",
",",
"dataItem",
"=",
"unwrap",
"(",
"dataItemOrObservable",
")",
";",
"if",
"(",
"parentContext",
")",
"{",
"// When a \"parent\" context is given, register a dependency on the parent context. Thus whenever the",
"// parent context is updated, this context will also be updated.",
"if",
"(",
"parentContext",
".",
"_subscribable",
")",
"parentContext",
".",
"_subscribable",
"(",
")",
";",
"// Copy $root and any custom properties from the parent context",
"extend",
"(",
"self",
",",
"parentContext",
")",
";",
"// Because the above copy overwrites our own properties, we need to reset them.",
"self",
".",
"_subscribable",
"=",
"subscribable",
";",
"}",
"else",
"{",
"self",
".",
"$parents",
"=",
"[",
"]",
";",
"self",
".",
"$root",
"=",
"dataItem",
";",
"// Export 'ko' in the binding context so it will be available in bindings and templates",
"// even if 'ko' isn't exported as a global, such as when using an AMD loader.",
"// See https://github.com/SteveSanderson/knockout/issues/490",
"self",
".",
"ko",
"=",
"options",
".",
"knockoutInstance",
";",
"}",
"self",
".",
"$rawData",
"=",
"dataItemOrObservable",
";",
"self",
".",
"$data",
"=",
"dataItem",
";",
"if",
"(",
"dataItemAlias",
")",
"self",
"[",
"dataItemAlias",
"]",
"=",
"dataItem",
";",
"// The extendCallback function is provided when creating a child context or extending a context.",
"// It handles the specific actions needed to finish setting up the binding context. Actions in this",
"// function could also add dependencies to this binding context.",
"if",
"(",
"extendCallback",
")",
"extendCallback",
"(",
"self",
",",
"parentContext",
",",
"dataItem",
")",
";",
"return",
"self",
".",
"$data",
";",
"}"
] |
The binding context object includes static properties for the current, parent, and root view models. If a view model is actually stored in an observable, the corresponding binding context object, and any child contexts, must be updated when the view model is changed.
|
[
"The",
"binding",
"context",
"object",
"includes",
"static",
"properties",
"for",
"the",
"current",
"parent",
"and",
"root",
"view",
"models",
".",
"If",
"a",
"view",
"model",
"is",
"actually",
"stored",
"in",
"an",
"observable",
"the",
"corresponding",
"binding",
"context",
"object",
"and",
"any",
"child",
"contexts",
"must",
"be",
"updated",
"when",
"the",
"view",
"model",
"is",
"changed",
"."
] |
ab33a6a6fd393077243068d1e79f0be838016cc5
|
https://github.com/knockout/tko.binding.if/blob/ab33a6a6fd393077243068d1e79f0be838016cc5/dist/tko.binding.if.js#L1952-L1992
|
37,478 |
knockout/tko.binding.if
|
dist/tko.binding.if.js
|
cloneIfElseNodes
|
function cloneIfElseNodes(element, hasElse) {
var children = childNodes(element),
ifNodes = [],
elseNodes = [],
target = ifNodes;
for (var i = 0, j = children.length; i < j; ++i) {
if (hasElse && isElseNode(children[i])) {
target = elseNodes;
hasElse = false;
} else {
target.push(cleanNode(children[i].cloneNode(true)));
}
}
return {
ifNodes: ifNodes,
elseNodes: elseNodes
};
}
|
javascript
|
function cloneIfElseNodes(element, hasElse) {
var children = childNodes(element),
ifNodes = [],
elseNodes = [],
target = ifNodes;
for (var i = 0, j = children.length; i < j; ++i) {
if (hasElse && isElseNode(children[i])) {
target = elseNodes;
hasElse = false;
} else {
target.push(cleanNode(children[i].cloneNode(true)));
}
}
return {
ifNodes: ifNodes,
elseNodes: elseNodes
};
}
|
[
"function",
"cloneIfElseNodes",
"(",
"element",
",",
"hasElse",
")",
"{",
"var",
"children",
"=",
"childNodes",
"(",
"element",
")",
",",
"ifNodes",
"=",
"[",
"]",
",",
"elseNodes",
"=",
"[",
"]",
",",
"target",
"=",
"ifNodes",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"j",
"=",
"children",
".",
"length",
";",
"i",
"<",
"j",
";",
"++",
"i",
")",
"{",
"if",
"(",
"hasElse",
"&&",
"isElseNode",
"(",
"children",
"[",
"i",
"]",
")",
")",
"{",
"target",
"=",
"elseNodes",
";",
"hasElse",
"=",
"false",
";",
"}",
"else",
"{",
"target",
".",
"push",
"(",
"cleanNode",
"(",
"children",
"[",
"i",
"]",
".",
"cloneNode",
"(",
"true",
")",
")",
")",
";",
"}",
"}",
"return",
"{",
"ifNodes",
":",
"ifNodes",
",",
"elseNodes",
":",
"elseNodes",
"}",
";",
"}"
] |
Clone the nodes, returning `ifNodes`, `elseNodes`
@param {HTMLElement} element The nodes to be cloned
@param {boolean} hasElse short-circuit to speed up the inner-loop.
@return {object} Containing the cloned nodes.
|
[
"Clone",
"the",
"nodes",
"returning",
"ifNodes",
"elseNodes"
] |
ab33a6a6fd393077243068d1e79f0be838016cc5
|
https://github.com/knockout/tko.binding.if/blob/ab33a6a6fd393077243068d1e79f0be838016cc5/dist/tko.binding.if.js#L2534-L2553
|
37,479 |
knockout/tko.binding.if
|
dist/tko.binding.if.js
|
makeWithIfBinding
|
function makeWithIfBinding(isWith, isNot, isElse, makeContextCallback) {
return {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var didDisplayOnLastUpdate,
hasElse = detectElse(element),
completesElseChain = observable(),
ifElseNodes,
precedingConditional;
set(element, "conditional", {
elseChainSatisfied: completesElseChain,
});
if (isElse) {
precedingConditional = getPrecedingConditional(element);
}
computed(function() {
var rawValue = valueAccessor(),
dataValue = unwrap(rawValue),
shouldDisplayIf = !isNot !== !dataValue || (isElse && rawValue === undefined), // equivalent to (isNot ? !dataValue : !!dataValue) || isElse && rawValue === undefined
isFirstRender = !ifElseNodes,
needsRefresh = isFirstRender || isWith || (shouldDisplayIf !== didDisplayOnLastUpdate);
if (precedingConditional && precedingConditional.elseChainSatisfied()) {
needsRefresh = shouldDisplayIf !== false;
shouldDisplayIf = false;
completesElseChain(true);
} else {
completesElseChain(shouldDisplayIf);
}
if (!needsRefresh) { return; }
if (isFirstRender && (getDependenciesCount() || hasElse)) {
ifElseNodes = cloneIfElseNodes(element, hasElse);
}
if (shouldDisplayIf) {
if (!isFirstRender || hasElse) {
setDomNodeChildren(element, cloneNodes(ifElseNodes.ifNodes));
}
} else if (ifElseNodes) {
setDomNodeChildren(element, cloneNodes(ifElseNodes.elseNodes));
} else {
emptyNode(element);
}
applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, rawValue) : bindingContext, element);
didDisplayOnLastUpdate = shouldDisplayIf;
}, null, { disposeWhenNodeIsRemoved: element });
return { 'controlsDescendantBindings': true };
},
allowVirtualElements: true,
bindingRewriteValidator: false
};
}
|
javascript
|
function makeWithIfBinding(isWith, isNot, isElse, makeContextCallback) {
return {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var didDisplayOnLastUpdate,
hasElse = detectElse(element),
completesElseChain = observable(),
ifElseNodes,
precedingConditional;
set(element, "conditional", {
elseChainSatisfied: completesElseChain,
});
if (isElse) {
precedingConditional = getPrecedingConditional(element);
}
computed(function() {
var rawValue = valueAccessor(),
dataValue = unwrap(rawValue),
shouldDisplayIf = !isNot !== !dataValue || (isElse && rawValue === undefined), // equivalent to (isNot ? !dataValue : !!dataValue) || isElse && rawValue === undefined
isFirstRender = !ifElseNodes,
needsRefresh = isFirstRender || isWith || (shouldDisplayIf !== didDisplayOnLastUpdate);
if (precedingConditional && precedingConditional.elseChainSatisfied()) {
needsRefresh = shouldDisplayIf !== false;
shouldDisplayIf = false;
completesElseChain(true);
} else {
completesElseChain(shouldDisplayIf);
}
if (!needsRefresh) { return; }
if (isFirstRender && (getDependenciesCount() || hasElse)) {
ifElseNodes = cloneIfElseNodes(element, hasElse);
}
if (shouldDisplayIf) {
if (!isFirstRender || hasElse) {
setDomNodeChildren(element, cloneNodes(ifElseNodes.ifNodes));
}
} else if (ifElseNodes) {
setDomNodeChildren(element, cloneNodes(ifElseNodes.elseNodes));
} else {
emptyNode(element);
}
applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, rawValue) : bindingContext, element);
didDisplayOnLastUpdate = shouldDisplayIf;
}, null, { disposeWhenNodeIsRemoved: element });
return { 'controlsDescendantBindings': true };
},
allowVirtualElements: true,
bindingRewriteValidator: false
};
}
|
[
"function",
"makeWithIfBinding",
"(",
"isWith",
",",
"isNot",
",",
"isElse",
",",
"makeContextCallback",
")",
"{",
"return",
"{",
"init",
":",
"function",
"(",
"element",
",",
"valueAccessor",
",",
"allBindings",
",",
"viewModel",
",",
"bindingContext",
")",
"{",
"var",
"didDisplayOnLastUpdate",
",",
"hasElse",
"=",
"detectElse",
"(",
"element",
")",
",",
"completesElseChain",
"=",
"observable",
"(",
")",
",",
"ifElseNodes",
",",
"precedingConditional",
";",
"set",
"(",
"element",
",",
"\"conditional\"",
",",
"{",
"elseChainSatisfied",
":",
"completesElseChain",
",",
"}",
")",
";",
"if",
"(",
"isElse",
")",
"{",
"precedingConditional",
"=",
"getPrecedingConditional",
"(",
"element",
")",
";",
"}",
"computed",
"(",
"function",
"(",
")",
"{",
"var",
"rawValue",
"=",
"valueAccessor",
"(",
")",
",",
"dataValue",
"=",
"unwrap",
"(",
"rawValue",
")",
",",
"shouldDisplayIf",
"=",
"!",
"isNot",
"!==",
"!",
"dataValue",
"||",
"(",
"isElse",
"&&",
"rawValue",
"===",
"undefined",
")",
",",
"// equivalent to (isNot ? !dataValue : !!dataValue) || isElse && rawValue === undefined",
"isFirstRender",
"=",
"!",
"ifElseNodes",
",",
"needsRefresh",
"=",
"isFirstRender",
"||",
"isWith",
"||",
"(",
"shouldDisplayIf",
"!==",
"didDisplayOnLastUpdate",
")",
";",
"if",
"(",
"precedingConditional",
"&&",
"precedingConditional",
".",
"elseChainSatisfied",
"(",
")",
")",
"{",
"needsRefresh",
"=",
"shouldDisplayIf",
"!==",
"false",
";",
"shouldDisplayIf",
"=",
"false",
";",
"completesElseChain",
"(",
"true",
")",
";",
"}",
"else",
"{",
"completesElseChain",
"(",
"shouldDisplayIf",
")",
";",
"}",
"if",
"(",
"!",
"needsRefresh",
")",
"{",
"return",
";",
"}",
"if",
"(",
"isFirstRender",
"&&",
"(",
"getDependenciesCount",
"(",
")",
"||",
"hasElse",
")",
")",
"{",
"ifElseNodes",
"=",
"cloneIfElseNodes",
"(",
"element",
",",
"hasElse",
")",
";",
"}",
"if",
"(",
"shouldDisplayIf",
")",
"{",
"if",
"(",
"!",
"isFirstRender",
"||",
"hasElse",
")",
"{",
"setDomNodeChildren",
"(",
"element",
",",
"cloneNodes",
"(",
"ifElseNodes",
".",
"ifNodes",
")",
")",
";",
"}",
"}",
"else",
"if",
"(",
"ifElseNodes",
")",
"{",
"setDomNodeChildren",
"(",
"element",
",",
"cloneNodes",
"(",
"ifElseNodes",
".",
"elseNodes",
")",
")",
";",
"}",
"else",
"{",
"emptyNode",
"(",
"element",
")",
";",
"}",
"applyBindingsToDescendants",
"(",
"makeContextCallback",
"?",
"makeContextCallback",
"(",
"bindingContext",
",",
"rawValue",
")",
":",
"bindingContext",
",",
"element",
")",
";",
"didDisplayOnLastUpdate",
"=",
"shouldDisplayIf",
";",
"}",
",",
"null",
",",
"{",
"disposeWhenNodeIsRemoved",
":",
"element",
"}",
")",
";",
"return",
"{",
"'controlsDescendantBindings'",
":",
"true",
"}",
";",
"}",
",",
"allowVirtualElements",
":",
"true",
",",
"bindingRewriteValidator",
":",
"false",
"}",
";",
"}"
] |
Create a DOMbinding that controls DOM nodes presence
Covers e.g.
1. DOM Nodes contents
<div data-bind='if: x'>
<!-- else --> ... an optional "if"
</div>
2. Virtual elements
<!-- ko if: x -->
<!-- else -->
<!-- /ko -->
3. Else binding
<div data-bind='if: x'></div>
<div data-bind='else'></div>
|
[
"Create",
"a",
"DOMbinding",
"that",
"controls",
"DOM",
"nodes",
"presence"
] |
ab33a6a6fd393077243068d1e79f0be838016cc5
|
https://github.com/knockout/tko.binding.if/blob/ab33a6a6fd393077243068d1e79f0be838016cc5/dist/tko.binding.if.js#L2596-L2655
|
37,480 |
ToMMApps/express-waf
|
modules/csrf-module.js
|
filterByUrls
|
function filterByUrls(url) {
if(_config.refererIndependentUrls) {
var isRefererIndependend = false;
for(var i in _config.refererIndependentUrls) {
if(new RegExp(_config.refererIndependentUrls[i]).test(url.split('?')[0])) {
isRefererIndependend = true;
break;
}
}
return isRefererIndependend;
} else {
return url === '/';
}
}
|
javascript
|
function filterByUrls(url) {
if(_config.refererIndependentUrls) {
var isRefererIndependend = false;
for(var i in _config.refererIndependentUrls) {
if(new RegExp(_config.refererIndependentUrls[i]).test(url.split('?')[0])) {
isRefererIndependend = true;
break;
}
}
return isRefererIndependend;
} else {
return url === '/';
}
}
|
[
"function",
"filterByUrls",
"(",
"url",
")",
"{",
"if",
"(",
"_config",
".",
"refererIndependentUrls",
")",
"{",
"var",
"isRefererIndependend",
"=",
"false",
";",
"for",
"(",
"var",
"i",
"in",
"_config",
".",
"refererIndependentUrls",
")",
"{",
"if",
"(",
"new",
"RegExp",
"(",
"_config",
".",
"refererIndependentUrls",
"[",
"i",
"]",
")",
".",
"test",
"(",
"url",
".",
"split",
"(",
"'?'",
")",
"[",
"0",
"]",
")",
")",
"{",
"isRefererIndependend",
"=",
"true",
";",
"break",
";",
"}",
"}",
"return",
"isRefererIndependend",
";",
"}",
"else",
"{",
"return",
"url",
"===",
"'/'",
";",
"}",
"}"
] |
This method checks by configured whitelist, if the url is in the list of allowed urls without a
referer in the header
@param url
@returns {boolean}
|
[
"This",
"method",
"checks",
"by",
"configured",
"whitelist",
"if",
"the",
"url",
"is",
"in",
"the",
"list",
"of",
"allowed",
"urls",
"without",
"a",
"referer",
"in",
"the",
"header"
] |
5c2c3ec379722d3ee63b3bf8c5fe65d4a0c0bb6a
|
https://github.com/ToMMApps/express-waf/blob/5c2c3ec379722d3ee63b3bf8c5fe65d4a0c0bb6a/modules/csrf-module.js#L79-L92
|
37,481 |
ToMMApps/express-waf
|
modules/csrf-module.js
|
filterByMethods
|
function filterByMethods(req) {
if(_config.allowedMethods) {
return _config.allowedMethods.indexOf(req.method) > -1;
} else if(_config.blockedMethods){
return !(_config.blockedMethods.indexOf(req.method) > -1);
} else {
return true;
}
}
|
javascript
|
function filterByMethods(req) {
if(_config.allowedMethods) {
return _config.allowedMethods.indexOf(req.method) > -1;
} else if(_config.blockedMethods){
return !(_config.blockedMethods.indexOf(req.method) > -1);
} else {
return true;
}
}
|
[
"function",
"filterByMethods",
"(",
"req",
")",
"{",
"if",
"(",
"_config",
".",
"allowedMethods",
")",
"{",
"return",
"_config",
".",
"allowedMethods",
".",
"indexOf",
"(",
"req",
".",
"method",
")",
">",
"-",
"1",
";",
"}",
"else",
"if",
"(",
"_config",
".",
"blockedMethods",
")",
"{",
"return",
"!",
"(",
"_config",
".",
"blockedMethods",
".",
"indexOf",
"(",
"req",
".",
"method",
")",
">",
"-",
"1",
")",
";",
"}",
"else",
"{",
"return",
"true",
";",
"}",
"}"
] |
This Method checks by configured black or whitelist, if the REST-Method is allowed or not
If no black or whitelist exists it allows method by default
@param req
@returns {boolean}
|
[
"This",
"Method",
"checks",
"by",
"configured",
"black",
"or",
"whitelist",
"if",
"the",
"REST",
"-",
"Method",
"is",
"allowed",
"or",
"not",
"If",
"no",
"black",
"or",
"whitelist",
"exists",
"it",
"allows",
"method",
"by",
"default"
] |
5c2c3ec379722d3ee63b3bf8c5fe65d4a0c0bb6a
|
https://github.com/ToMMApps/express-waf/blob/5c2c3ec379722d3ee63b3bf8c5fe65d4a0c0bb6a/modules/csrf-module.js#L100-L108
|
37,482 |
jonschlinkert/arr
|
index.js
|
indexOf
|
function indexOf(arr, value, start) {
start = start || 0;
if (arr == null) {
return -1;
}
var len = arr.length;
var i = start < 0 ? len + start : start;
while (i < len) {
if (arr[i] === value) {
return i;
}
i++;
}
return -1;
}
|
javascript
|
function indexOf(arr, value, start) {
start = start || 0;
if (arr == null) {
return -1;
}
var len = arr.length;
var i = start < 0 ? len + start : start;
while (i < len) {
if (arr[i] === value) {
return i;
}
i++;
}
return -1;
}
|
[
"function",
"indexOf",
"(",
"arr",
",",
"value",
",",
"start",
")",
"{",
"start",
"=",
"start",
"||",
"0",
";",
"if",
"(",
"arr",
"==",
"null",
")",
"{",
"return",
"-",
"1",
";",
"}",
"var",
"len",
"=",
"arr",
".",
"length",
";",
"var",
"i",
"=",
"start",
"<",
"0",
"?",
"len",
"+",
"start",
":",
"start",
";",
"while",
"(",
"i",
"<",
"len",
")",
"{",
"if",
"(",
"arr",
"[",
"i",
"]",
"===",
"value",
")",
"{",
"return",
"i",
";",
"}",
"i",
"++",
";",
"}",
"return",
"-",
"1",
";",
"}"
] |
Custom `indexOf` implementation that works with sparse arrays
to provide consisten results in any environment or browser.
@param {Array} `arr`
@param {*} `value`
@param {Array} `start` Optionally define a starting index.
@return {Array}
|
[
"Custom",
"indexOf",
"implementation",
"that",
"works",
"with",
"sparse",
"arrays",
"to",
"provide",
"consisten",
"results",
"in",
"any",
"environment",
"or",
"browser",
"."
] |
a816f3da59bef18a91b8a6936560f723a5cd57f3
|
https://github.com/jonschlinkert/arr/blob/a816f3da59bef18a91b8a6936560f723a5cd57f3/index.js#L30-L44
|
37,483 |
jonschlinkert/arr
|
index.js
|
every
|
function every(arr, cb, thisArg) {
cb = makeIterator(cb, thisArg);
var result = true;
if (arr == null) {
return result;
}
var len = arr.length;
var i = -1;
while (++i < len) {
if (!cb(arr[i], i, arr)) {
result = false;
break;
}
}
return result;
}
|
javascript
|
function every(arr, cb, thisArg) {
cb = makeIterator(cb, thisArg);
var result = true;
if (arr == null) {
return result;
}
var len = arr.length;
var i = -1;
while (++i < len) {
if (!cb(arr[i], i, arr)) {
result = false;
break;
}
}
return result;
}
|
[
"function",
"every",
"(",
"arr",
",",
"cb",
",",
"thisArg",
")",
"{",
"cb",
"=",
"makeIterator",
"(",
"cb",
",",
"thisArg",
")",
";",
"var",
"result",
"=",
"true",
";",
"if",
"(",
"arr",
"==",
"null",
")",
"{",
"return",
"result",
";",
"}",
"var",
"len",
"=",
"arr",
".",
"length",
";",
"var",
"i",
"=",
"-",
"1",
";",
"while",
"(",
"++",
"i",
"<",
"len",
")",
"{",
"if",
"(",
"!",
"cb",
"(",
"arr",
"[",
"i",
"]",
",",
"i",
",",
"arr",
")",
")",
"{",
"result",
"=",
"false",
";",
"break",
";",
"}",
"}",
"return",
"result",
";",
"}"
] |
Return `true` if the callback returns `true`
for every element in the `array`.
@param {Array} `array` The array to check.
@param {*} `value`
@return {Boolean}
|
[
"Return",
"true",
"if",
"the",
"callback",
"returns",
"true",
"for",
"every",
"element",
"in",
"the",
"array",
"."
] |
a816f3da59bef18a91b8a6936560f723a5cd57f3
|
https://github.com/jonschlinkert/arr/blob/a816f3da59bef18a91b8a6936560f723a5cd57f3/index.js#L68-L85
|
37,484 |
jonschlinkert/arr
|
index.js
|
filter
|
function filter(arr, cb, thisArg) {
cb = makeIterator(cb, thisArg);
if (arr == null) {
return [];
}
var len = arr.length;
var res = [];
for (var i = 0; i < len; i++) {
var ele = arr[i];
if (cb(ele, i, arr)) {
res.push(ele);
}
}
return res;
}
|
javascript
|
function filter(arr, cb, thisArg) {
cb = makeIterator(cb, thisArg);
if (arr == null) {
return [];
}
var len = arr.length;
var res = [];
for (var i = 0; i < len; i++) {
var ele = arr[i];
if (cb(ele, i, arr)) {
res.push(ele);
}
}
return res;
}
|
[
"function",
"filter",
"(",
"arr",
",",
"cb",
",",
"thisArg",
")",
"{",
"cb",
"=",
"makeIterator",
"(",
"cb",
",",
"thisArg",
")",
";",
"if",
"(",
"arr",
"==",
"null",
")",
"{",
"return",
"[",
"]",
";",
"}",
"var",
"len",
"=",
"arr",
".",
"length",
";",
"var",
"res",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"ele",
"=",
"arr",
"[",
"i",
"]",
";",
"if",
"(",
"cb",
"(",
"ele",
",",
"i",
",",
"arr",
")",
")",
"{",
"res",
".",
"push",
"(",
"ele",
")",
";",
"}",
"}",
"return",
"res",
";",
"}"
] |
Like JavaScript's native filter method, but faster.
@param {Array} `arr` The array to filter
@param {Function} `cb` Callback function.
@param {Array} `thisArg`
@return {Array}
|
[
"Like",
"JavaScript",
"s",
"native",
"filter",
"method",
"but",
"faster",
"."
] |
a816f3da59bef18a91b8a6936560f723a5cd57f3
|
https://github.com/jonschlinkert/arr/blob/a816f3da59bef18a91b8a6936560f723a5cd57f3/index.js#L96-L111
|
37,485 |
jonschlinkert/arr
|
index.js
|
filterType
|
function filterType(arr, type) {
var len = arr.length;
var res = [];
for (var i = 0; i < len; i++) {
var ele = arr[i];
if (typeOf(ele) === type) {
res.push(ele);
}
}
return res;
}
|
javascript
|
function filterType(arr, type) {
var len = arr.length;
var res = [];
for (var i = 0; i < len; i++) {
var ele = arr[i];
if (typeOf(ele) === type) {
res.push(ele);
}
}
return res;
}
|
[
"function",
"filterType",
"(",
"arr",
",",
"type",
")",
"{",
"var",
"len",
"=",
"arr",
".",
"length",
";",
"var",
"res",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"ele",
"=",
"arr",
"[",
"i",
"]",
";",
"if",
"(",
"typeOf",
"(",
"ele",
")",
"===",
"type",
")",
"{",
"res",
".",
"push",
"(",
"ele",
")",
";",
"}",
"}",
"return",
"res",
";",
"}"
] |
Filter `array`, returning only the values of the given `type`.
```js
var arr = ['a', {a: 'b'}, 1, 'b', 2, {c: 'd'}, 'c'];
utils.filterType(arr, 'object');
//=> [{a: 'b'}, {c: 'd'}]
```
@param {Array} `array`
@param {String} `type` Native type, e.g. `string`, `object`
@return {Boolean}
@api public
|
[
"Filter",
"array",
"returning",
"only",
"the",
"values",
"of",
"the",
"given",
"type",
"."
] |
a816f3da59bef18a91b8a6936560f723a5cd57f3
|
https://github.com/jonschlinkert/arr/blob/a816f3da59bef18a91b8a6936560f723a5cd57f3/index.js#L129-L139
|
37,486 |
jonschlinkert/arr
|
index.js
|
strings
|
function strings(arr, i) {
var values = filterType(arr, 'string');
return i ? values[i] : values;
}
|
javascript
|
function strings(arr, i) {
var values = filterType(arr, 'string');
return i ? values[i] : values;
}
|
[
"function",
"strings",
"(",
"arr",
",",
"i",
")",
"{",
"var",
"values",
"=",
"filterType",
"(",
"arr",
",",
"'string'",
")",
";",
"return",
"i",
"?",
"values",
"[",
"i",
"]",
":",
"values",
";",
"}"
] |
Filter `array`, returning only the strings.
```js
var arr = ['a', {a: 'b'}, 1, 'b', 2, {c: 'd'}, 'c'];
utils.strings(arr);
//=> ['a', 'b', 'c']
```
@param {Array} `array`
@param {Array} `index` Optionally specify the index of the string to return, otherwise all strings are returned.
@return {Array} Array of strings or empty array.
@api public
|
[
"Filter",
"array",
"returning",
"only",
"the",
"strings",
"."
] |
a816f3da59bef18a91b8a6936560f723a5cd57f3
|
https://github.com/jonschlinkert/arr/blob/a816f3da59bef18a91b8a6936560f723a5cd57f3/index.js#L296-L299
|
37,487 |
jonschlinkert/arr
|
index.js
|
objects
|
function objects(arr, i) {
var values = filterType(arr, 'object');
return i ? values[i] : values;
}
|
javascript
|
function objects(arr, i) {
var values = filterType(arr, 'object');
return i ? values[i] : values;
}
|
[
"function",
"objects",
"(",
"arr",
",",
"i",
")",
"{",
"var",
"values",
"=",
"filterType",
"(",
"arr",
",",
"'object'",
")",
";",
"return",
"i",
"?",
"values",
"[",
"i",
"]",
":",
"values",
";",
"}"
] |
Filter `array`, returning only the objects.
```js
var arr = ['a', {a: 'b'}, 1, 'b', 2, {c: 'd'}, 'c'];
utils.objects(arr);
//=> [{a: 'b'}, {c: 'd'}]
```
@param {Array} `array`
@param {Array} `index` Optionally specify the index of the object to return, otherwise all objects are returned.
@return {Array} Array of objects or empty array.
@api public
|
[
"Filter",
"array",
"returning",
"only",
"the",
"objects",
"."
] |
a816f3da59bef18a91b8a6936560f723a5cd57f3
|
https://github.com/jonschlinkert/arr/blob/a816f3da59bef18a91b8a6936560f723a5cd57f3/index.js#L317-L320
|
37,488 |
jonschlinkert/arr
|
index.js
|
functions
|
function functions(arr, i) {
var values = filterType(arr, 'function');
return i ? values[i] : values;
}
|
javascript
|
function functions(arr, i) {
var values = filterType(arr, 'function');
return i ? values[i] : values;
}
|
[
"function",
"functions",
"(",
"arr",
",",
"i",
")",
"{",
"var",
"values",
"=",
"filterType",
"(",
"arr",
",",
"'function'",
")",
";",
"return",
"i",
"?",
"values",
"[",
"i",
"]",
":",
"values",
";",
"}"
] |
Filter `array`, returning only the functions.
```js
var one = function() {};
var two = function() {};
var arr = ['a', {a: 'b'}, 1, one, 'b', 2, {c: 'd'}, two, 'c'];
utils.functions(arr);
//=> [one, two]
```
@param {Array} `array`
@param {Array} `index` Optionally specify the index of the function to return, otherwise all functions are returned.
@return {Array} Array of functions or empty array.
@api public
|
[
"Filter",
"array",
"returning",
"only",
"the",
"functions",
"."
] |
a816f3da59bef18a91b8a6936560f723a5cd57f3
|
https://github.com/jonschlinkert/arr/blob/a816f3da59bef18a91b8a6936560f723a5cd57f3/index.js#L340-L343
|
37,489 |
jonschlinkert/arr
|
index.js
|
arrays
|
function arrays(arr, i) {
var values = filterType(arr, 'array');
return i ? values[i] : values;
}
|
javascript
|
function arrays(arr, i) {
var values = filterType(arr, 'array');
return i ? values[i] : values;
}
|
[
"function",
"arrays",
"(",
"arr",
",",
"i",
")",
"{",
"var",
"values",
"=",
"filterType",
"(",
"arr",
",",
"'array'",
")",
";",
"return",
"i",
"?",
"values",
"[",
"i",
"]",
":",
"values",
";",
"}"
] |
Filter `array`, returning only the arrays.
```js
var arr = ['a', ['aaa'], 1, 'b', ['bbb'], 2, {c: 'd'}, 'c'];
utils.objects(arr);
//=> [['aaa'], ['bbb']]
```
@param {Array} `array`
@param {Array} `index` Optionally specify the index of the array to return, otherwise all arrays are returned.
@return {Array} Array of arrays or empty array.
@api public
|
[
"Filter",
"array",
"returning",
"only",
"the",
"arrays",
"."
] |
a816f3da59bef18a91b8a6936560f723a5cd57f3
|
https://github.com/jonschlinkert/arr/blob/a816f3da59bef18a91b8a6936560f723a5cd57f3/index.js#L361-L364
|
37,490 |
jonschlinkert/arr
|
index.js
|
first
|
function first(arr, cb, thisArg) {
if (arguments.length === 1) {
return arr[0];
}
if (typeOf(cb) === 'string') {
return findFirst(arr, isType(cb));
}
return findFirst(arr, cb, thisArg);
}
|
javascript
|
function first(arr, cb, thisArg) {
if (arguments.length === 1) {
return arr[0];
}
if (typeOf(cb) === 'string') {
return findFirst(arr, isType(cb));
}
return findFirst(arr, cb, thisArg);
}
|
[
"function",
"first",
"(",
"arr",
",",
"cb",
",",
"thisArg",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
")",
"{",
"return",
"arr",
"[",
"0",
"]",
";",
"}",
"if",
"(",
"typeOf",
"(",
"cb",
")",
"===",
"'string'",
")",
"{",
"return",
"findFirst",
"(",
"arr",
",",
"isType",
"(",
"cb",
")",
")",
";",
"}",
"return",
"findFirst",
"(",
"arr",
",",
"cb",
",",
"thisArg",
")",
";",
"}"
] |
Return the first element in `array`, or, if a callback is passed,
return the first value for which the returns true.
```js
var arr = ['a', {a: 'b'}, 1, one, 'b', 2, {c: 'd'}, two, 'c'];
utils.first(arr);
//=> 'a'
utils.first(arr, isType('object'));
//=> {a: 'b'}
utils.first(arr, 'object');
//=> {a: 'b'}
```
@param {Array} `array`
@return {*}
@api public
|
[
"Return",
"the",
"first",
"element",
"in",
"array",
"or",
"if",
"a",
"callback",
"is",
"passed",
"return",
"the",
"first",
"value",
"for",
"which",
"the",
"returns",
"true",
"."
] |
a816f3da59bef18a91b8a6936560f723a5cd57f3
|
https://github.com/jonschlinkert/arr/blob/a816f3da59bef18a91b8a6936560f723a5cd57f3/index.js#L388-L396
|
37,491 |
jonschlinkert/arr
|
index.js
|
last
|
function last(arr, cb, thisArg) {
if (arguments.length === 1) {
return arr[arr.length - 1];
}
if (typeOf(cb) === 'string') {
return findLast(arr, isType(cb));
}
return findLast(arr, cb, thisArg);
}
|
javascript
|
function last(arr, cb, thisArg) {
if (arguments.length === 1) {
return arr[arr.length - 1];
}
if (typeOf(cb) === 'string') {
return findLast(arr, isType(cb));
}
return findLast(arr, cb, thisArg);
}
|
[
"function",
"last",
"(",
"arr",
",",
"cb",
",",
"thisArg",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
")",
"{",
"return",
"arr",
"[",
"arr",
".",
"length",
"-",
"1",
"]",
";",
"}",
"if",
"(",
"typeOf",
"(",
"cb",
")",
"===",
"'string'",
")",
"{",
"return",
"findLast",
"(",
"arr",
",",
"isType",
"(",
"cb",
")",
")",
";",
"}",
"return",
"findLast",
"(",
"arr",
",",
"cb",
",",
"thisArg",
")",
";",
"}"
] |
Return the last element in `array`, or, if a callback is passed,
return the last value for which the returns true.
```js
// `one` and `two` are functions
var arr = ['a', {a: 'b'}, 1, one, 'b', 2, {c: 'd'}, two, 'c'];
utils.last(arr);
//=> 'c'
utils.last(arr, isType('function'));
//=> two
utils.last(arr, 'object');
//=> {c: 'd'}
```
@param {Array} `array`
@return {*}
@api public
|
[
"Return",
"the",
"last",
"element",
"in",
"array",
"or",
"if",
"a",
"callback",
"is",
"passed",
"return",
"the",
"last",
"value",
"for",
"which",
"the",
"returns",
"true",
"."
] |
a816f3da59bef18a91b8a6936560f723a5cd57f3
|
https://github.com/jonschlinkert/arr/blob/a816f3da59bef18a91b8a6936560f723a5cd57f3/index.js#L420-L428
|
37,492 |
hiproxy/open-browser
|
lib/index.js
|
function (browser, url, proxyURL, pacFileURL, dataDir, bypassList) {
// Firefox pac set
// http://www.indexdata.com/connector-platform/enginedoc/proxy-auto.html
// http://kb.mozillazine.org/Network.proxy.autoconfig_url
// user_pref("network.proxy.autoconfig_url", "http://us2.indexdata.com:9005/id/cf.pac");
// user_pref("network.proxy.type", 2);
return this.detect(browser).then(function (browserPath) {
if (!browserPath) {
throw Error('[Error] can not find browser ' + browser);
} else {
dataDir = dataDir || path.join(os.tmpdir(), 'op-browser');
if (os.platform() === 'win32') {
browserPath = '"' + browserPath + '"';
}
var commandOptions = configUtil[browser](dataDir, url, browserPath, proxyURL, pacFileURL, bypassList);
return new Promise(function (resolve, reject) {
var cmdStr = browserPath + ' ' + commandOptions;
childProcess.exec(cmdStr, {maxBuffer: 50000 * 1024}, function (err) {
if (err) {
reject(err);
} else {
resolve({
path: browserPath,
cmdOptions: commandOptions,
proxyURL: proxyURL,
pacFileURL: pacFileURL
});
}
});
});
}
});
}
|
javascript
|
function (browser, url, proxyURL, pacFileURL, dataDir, bypassList) {
// Firefox pac set
// http://www.indexdata.com/connector-platform/enginedoc/proxy-auto.html
// http://kb.mozillazine.org/Network.proxy.autoconfig_url
// user_pref("network.proxy.autoconfig_url", "http://us2.indexdata.com:9005/id/cf.pac");
// user_pref("network.proxy.type", 2);
return this.detect(browser).then(function (browserPath) {
if (!browserPath) {
throw Error('[Error] can not find browser ' + browser);
} else {
dataDir = dataDir || path.join(os.tmpdir(), 'op-browser');
if (os.platform() === 'win32') {
browserPath = '"' + browserPath + '"';
}
var commandOptions = configUtil[browser](dataDir, url, browserPath, proxyURL, pacFileURL, bypassList);
return new Promise(function (resolve, reject) {
var cmdStr = browserPath + ' ' + commandOptions;
childProcess.exec(cmdStr, {maxBuffer: 50000 * 1024}, function (err) {
if (err) {
reject(err);
} else {
resolve({
path: browserPath,
cmdOptions: commandOptions,
proxyURL: proxyURL,
pacFileURL: pacFileURL
});
}
});
});
}
});
}
|
[
"function",
"(",
"browser",
",",
"url",
",",
"proxyURL",
",",
"pacFileURL",
",",
"dataDir",
",",
"bypassList",
")",
"{",
"// Firefox pac set",
"// http://www.indexdata.com/connector-platform/enginedoc/proxy-auto.html",
"// http://kb.mozillazine.org/Network.proxy.autoconfig_url",
"// user_pref(\"network.proxy.autoconfig_url\", \"http://us2.indexdata.com:9005/id/cf.pac\");",
"// user_pref(\"network.proxy.type\", 2);",
"return",
"this",
".",
"detect",
"(",
"browser",
")",
".",
"then",
"(",
"function",
"(",
"browserPath",
")",
"{",
"if",
"(",
"!",
"browserPath",
")",
"{",
"throw",
"Error",
"(",
"'[Error] can not find browser '",
"+",
"browser",
")",
";",
"}",
"else",
"{",
"dataDir",
"=",
"dataDir",
"||",
"path",
".",
"join",
"(",
"os",
".",
"tmpdir",
"(",
")",
",",
"'op-browser'",
")",
";",
"if",
"(",
"os",
".",
"platform",
"(",
")",
"===",
"'win32'",
")",
"{",
"browserPath",
"=",
"'\"'",
"+",
"browserPath",
"+",
"'\"'",
";",
"}",
"var",
"commandOptions",
"=",
"configUtil",
"[",
"browser",
"]",
"(",
"dataDir",
",",
"url",
",",
"browserPath",
",",
"proxyURL",
",",
"pacFileURL",
",",
"bypassList",
")",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"cmdStr",
"=",
"browserPath",
"+",
"' '",
"+",
"commandOptions",
";",
"childProcess",
".",
"exec",
"(",
"cmdStr",
",",
"{",
"maxBuffer",
":",
"50000",
"*",
"1024",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"}",
"else",
"{",
"resolve",
"(",
"{",
"path",
":",
"browserPath",
",",
"cmdOptions",
":",
"commandOptions",
",",
"proxyURL",
":",
"proxyURL",
",",
"pacFileURL",
":",
"pacFileURL",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] |
open browser window, if the `pacFileURL` is not empty, will use `proxy auto-configuration`
@memberof op-browser
@param {String} browser the browser's name
@param {String} url the url that to open
@param {String} proxyURL the proxy url, format: `http://<hostname>[:[port]]`
@param {String} pacFileURL the proxy url, format: `http://<hostname>[:[port]]/[pac-file-name]`
@param {String} dataDir the user data directory
@param {String} bypassList the list of hosts for whom we bypass proxy settings and use direct connections. the list of hosts for whom we bypass proxy settings and use direct connections, See: "[net/proxy/proxy_bypass_rules.h](https://cs.chromium.org/chromium/src/net/proxy_resolution/proxy_bypass_rules.h?sq=package:chromium&type=cs)" for the format of these rules
@return {Promise}
|
[
"open",
"browser",
"window",
"if",
"the",
"pacFileURL",
"is",
"not",
"empty",
"will",
"use",
"proxy",
"auto",
"-",
"configuration"
] |
bc88e3ab741d1bac8d4358a60e8ba5a273a3ea38
|
https://github.com/hiproxy/open-browser/blob/bc88e3ab741d1bac8d4358a60e8ba5a273a3ea38/lib/index.js#L54-L90
|
|
37,493 |
infrabel/themes-gnap
|
raw/bootstrap/docs/assets/js/vendor/holder.js
|
extend
|
function extend(a,b){
var c={};
for(var i in a){
if(a.hasOwnProperty(i)){
c[i]=a[i];
}
}
for(var i in b){
if(b.hasOwnProperty(i)){
c[i]=b[i];
}
}
return c
}
|
javascript
|
function extend(a,b){
var c={};
for(var i in a){
if(a.hasOwnProperty(i)){
c[i]=a[i];
}
}
for(var i in b){
if(b.hasOwnProperty(i)){
c[i]=b[i];
}
}
return c
}
|
[
"function",
"extend",
"(",
"a",
",",
"b",
")",
"{",
"var",
"c",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"in",
"a",
")",
"{",
"if",
"(",
"a",
".",
"hasOwnProperty",
"(",
"i",
")",
")",
"{",
"c",
"[",
"i",
"]",
"=",
"a",
"[",
"i",
"]",
";",
"}",
"}",
"for",
"(",
"var",
"i",
"in",
"b",
")",
"{",
"if",
"(",
"b",
".",
"hasOwnProperty",
"(",
"i",
")",
")",
"{",
"c",
"[",
"i",
"]",
"=",
"b",
"[",
"i",
"]",
";",
"}",
"}",
"return",
"c",
"}"
] |
shallow object property extend
|
[
"shallow",
"object",
"property",
"extend"
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/bootstrap/docs/assets/js/vendor/holder.js#L624-L637
|
37,494 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/bootstrap-colorpicker.js
|
function(){
try {
this.preview.backgroundColor = this.format.call(this);
} catch(e) {
this.preview.backgroundColor = this.color.toHex();
}
//set the color for brightness/saturation slider
this.base.backgroundColor = this.color.toHex(this.color.value.h, 1, 1, 1);
//set te color for alpha slider
if (this.alpha) {
this.alpha.backgroundColor = this.color.toHex();
}
}
|
javascript
|
function(){
try {
this.preview.backgroundColor = this.format.call(this);
} catch(e) {
this.preview.backgroundColor = this.color.toHex();
}
//set the color for brightness/saturation slider
this.base.backgroundColor = this.color.toHex(this.color.value.h, 1, 1, 1);
//set te color for alpha slider
if (this.alpha) {
this.alpha.backgroundColor = this.color.toHex();
}
}
|
[
"function",
"(",
")",
"{",
"try",
"{",
"this",
".",
"preview",
".",
"backgroundColor",
"=",
"this",
".",
"format",
".",
"call",
"(",
"this",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"this",
".",
"preview",
".",
"backgroundColor",
"=",
"this",
".",
"color",
".",
"toHex",
"(",
")",
";",
"}",
"//set the color for brightness/saturation slider",
"this",
".",
"base",
".",
"backgroundColor",
"=",
"this",
".",
"color",
".",
"toHex",
"(",
"this",
".",
"color",
".",
"value",
".",
"h",
",",
"1",
",",
"1",
",",
"1",
")",
";",
"//set te color for alpha slider",
"if",
"(",
"this",
".",
"alpha",
")",
"{",
"this",
".",
"alpha",
".",
"backgroundColor",
"=",
"this",
".",
"color",
".",
"toHex",
"(",
")",
";",
"}",
"}"
] |
preview color change
|
[
"preview",
"color",
"change"
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/bootstrap-colorpicker.js#L248-L260
|
|
37,495 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/jquery.gritter.js
|
function(unique_id, e, manual_close){
// Remove it then run the callback function
e.remove();
this['_after_close_' + unique_id](e, manual_close);
// Check if the wrapper is empty, if it is.. remove the wrapper
if($('.gritter-item-wrapper').length == 0){
$('#gritter-notice-wrapper').remove();
}
}
|
javascript
|
function(unique_id, e, manual_close){
// Remove it then run the callback function
e.remove();
this['_after_close_' + unique_id](e, manual_close);
// Check if the wrapper is empty, if it is.. remove the wrapper
if($('.gritter-item-wrapper').length == 0){
$('#gritter-notice-wrapper').remove();
}
}
|
[
"function",
"(",
"unique_id",
",",
"e",
",",
"manual_close",
")",
"{",
"// Remove it then run the callback function",
"e",
".",
"remove",
"(",
")",
";",
"this",
"[",
"'_after_close_'",
"+",
"unique_id",
"]",
"(",
"e",
",",
"manual_close",
")",
";",
"// Check if the wrapper is empty, if it is.. remove the wrapper",
"if",
"(",
"$",
"(",
"'.gritter-item-wrapper'",
")",
".",
"length",
"==",
"0",
")",
"{",
"$",
"(",
"'#gritter-notice-wrapper'",
")",
".",
"remove",
"(",
")",
";",
"}",
"}"
] |
If we don't have any more gritter notifications, get rid of the wrapper using this check
@private
@param {Integer} unique_id The ID of the element that was just deleted, use it for a callback
@param {Object} e The jQuery element that we're going to perform the remove() action on
@param {Boolean} manual_close Did we close the gritter dialog with the (X) button
|
[
"If",
"we",
"don",
"t",
"have",
"any",
"more",
"gritter",
"notifications",
"get",
"rid",
"of",
"the",
"wrapper",
"using",
"this",
"check"
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/jquery.gritter.js#L198-L209
|
|
37,496 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/jquery.gritter.js
|
function(e, unique_id, params, unbind_events){
var params = params || {},
fade = (typeof(params.fade) != 'undefined') ? params.fade : true,
fade_out_speed = params.speed || this.fade_out_speed,
manual_close = unbind_events;
this['_before_close_' + unique_id](e, manual_close);
// If this is true, then we are coming from clicking the (X)
if(unbind_events){
e.unbind('mouseenter mouseleave');
}
// Fade it out or remove it
if(fade){
e.animate({
opacity: 0
}, fade_out_speed, function(){
e.animate({ height: 0 }, 300, function(){
Gritter._countRemoveWrapper(unique_id, e, manual_close);
})
})
}
else {
this._countRemoveWrapper(unique_id, e);
}
}
|
javascript
|
function(e, unique_id, params, unbind_events){
var params = params || {},
fade = (typeof(params.fade) != 'undefined') ? params.fade : true,
fade_out_speed = params.speed || this.fade_out_speed,
manual_close = unbind_events;
this['_before_close_' + unique_id](e, manual_close);
// If this is true, then we are coming from clicking the (X)
if(unbind_events){
e.unbind('mouseenter mouseleave');
}
// Fade it out or remove it
if(fade){
e.animate({
opacity: 0
}, fade_out_speed, function(){
e.animate({ height: 0 }, 300, function(){
Gritter._countRemoveWrapper(unique_id, e, manual_close);
})
})
}
else {
this._countRemoveWrapper(unique_id, e);
}
}
|
[
"function",
"(",
"e",
",",
"unique_id",
",",
"params",
",",
"unbind_events",
")",
"{",
"var",
"params",
"=",
"params",
"||",
"{",
"}",
",",
"fade",
"=",
"(",
"typeof",
"(",
"params",
".",
"fade",
")",
"!=",
"'undefined'",
")",
"?",
"params",
".",
"fade",
":",
"true",
",",
"fade_out_speed",
"=",
"params",
".",
"speed",
"||",
"this",
".",
"fade_out_speed",
",",
"manual_close",
"=",
"unbind_events",
";",
"this",
"[",
"'_before_close_'",
"+",
"unique_id",
"]",
"(",
"e",
",",
"manual_close",
")",
";",
"// If this is true, then we are coming from clicking the (X)",
"if",
"(",
"unbind_events",
")",
"{",
"e",
".",
"unbind",
"(",
"'mouseenter mouseleave'",
")",
";",
"}",
"// Fade it out or remove it",
"if",
"(",
"fade",
")",
"{",
"e",
".",
"animate",
"(",
"{",
"opacity",
":",
"0",
"}",
",",
"fade_out_speed",
",",
"function",
"(",
")",
"{",
"e",
".",
"animate",
"(",
"{",
"height",
":",
"0",
"}",
",",
"300",
",",
"function",
"(",
")",
"{",
"Gritter",
".",
"_countRemoveWrapper",
"(",
"unique_id",
",",
"e",
",",
"manual_close",
")",
";",
"}",
")",
"}",
")",
"}",
"else",
"{",
"this",
".",
"_countRemoveWrapper",
"(",
"unique_id",
",",
"e",
")",
";",
"}",
"}"
] |
Fade out an element after it's been on the screen for x amount of time
@private
@param {Object} e The jQuery element to get rid of
@param {Integer} unique_id The id of the element to remove
@param {Object} params An optional list of params to set fade speeds etc.
@param {Boolean} unbind_events Unbind the mouseenter/mouseleave events if they click (X)
|
[
"Fade",
"out",
"an",
"element",
"after",
"it",
"s",
"been",
"on",
"the",
"screen",
"for",
"x",
"amount",
"of",
"time"
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/jquery.gritter.js#L219-L251
|
|
37,497 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/jquery.gritter.js
|
function(unique_id, params, e, unbind_events){
if(!e){
var e = $('#gritter-item-' + unique_id);
}
// We set the fourth param to let the _fade function know to
// unbind the "mouseleave" event. Once you click (X) there's no going back!
this._fade(e, unique_id, params || {}, unbind_events);
}
|
javascript
|
function(unique_id, params, e, unbind_events){
if(!e){
var e = $('#gritter-item-' + unique_id);
}
// We set the fourth param to let the _fade function know to
// unbind the "mouseleave" event. Once you click (X) there's no going back!
this._fade(e, unique_id, params || {}, unbind_events);
}
|
[
"function",
"(",
"unique_id",
",",
"params",
",",
"e",
",",
"unbind_events",
")",
"{",
"if",
"(",
"!",
"e",
")",
"{",
"var",
"e",
"=",
"$",
"(",
"'#gritter-item-'",
"+",
"unique_id",
")",
";",
"}",
"// We set the fourth param to let the _fade function know to ",
"// unbind the \"mouseleave\" event. Once you click (X) there's no going back!",
"this",
".",
"_fade",
"(",
"e",
",",
"unique_id",
",",
"params",
"||",
"{",
"}",
",",
"unbind_events",
")",
";",
"}"
] |
Remove a specific notification based on an ID
@param {Integer} unique_id The ID used to delete a specific notification
@param {Object} params A set of options passed in to determine how to get rid of it
@param {Object} e The jQuery element that we're "fading" then removing
@param {Boolean} unbind_events If we clicked on the (X) we set this to true to unbind mouseenter/mouseleave
|
[
"Remove",
"a",
"specific",
"notification",
"based",
"on",
"an",
"ID"
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/jquery.gritter.js#L289-L299
|
|
37,498 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/jquery.gritter.js
|
function(e, unique_id){
var timer_str = (this._custom_timer) ? this._custom_timer : this.time;
this['_int_id_' + unique_id] = setTimeout(function(){
Gritter._fade(e, unique_id);
}, timer_str);
}
|
javascript
|
function(e, unique_id){
var timer_str = (this._custom_timer) ? this._custom_timer : this.time;
this['_int_id_' + unique_id] = setTimeout(function(){
Gritter._fade(e, unique_id);
}, timer_str);
}
|
[
"function",
"(",
"e",
",",
"unique_id",
")",
"{",
"var",
"timer_str",
"=",
"(",
"this",
".",
"_custom_timer",
")",
"?",
"this",
".",
"_custom_timer",
":",
"this",
".",
"time",
";",
"this",
"[",
"'_int_id_'",
"+",
"unique_id",
"]",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"Gritter",
".",
"_fade",
"(",
"e",
",",
"unique_id",
")",
";",
"}",
",",
"timer_str",
")",
";",
"}"
] |
Set the notification to fade out after a certain amount of time
@private
@param {Object} item The HTML element we're dealing with
@param {Integer} unique_id The ID of the element
|
[
"Set",
"the",
"notification",
"to",
"fade",
"out",
"after",
"a",
"certain",
"amount",
"of",
"time"
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/jquery.gritter.js#L333-L340
|
|
37,499 |
infrabel/themes-gnap
|
raw/ace/assets/js/uncompressed/jquery.gritter.js
|
function(params){
// callbacks (if passed)
var before_close = ($.isFunction(params.before_close)) ? params.before_close : function(){};
var after_close = ($.isFunction(params.after_close)) ? params.after_close : function(){};
var wrap = $('#gritter-notice-wrapper');
before_close(wrap);
wrap.fadeOut(function(){
$(this).remove();
after_close();
});
}
|
javascript
|
function(params){
// callbacks (if passed)
var before_close = ($.isFunction(params.before_close)) ? params.before_close : function(){};
var after_close = ($.isFunction(params.after_close)) ? params.after_close : function(){};
var wrap = $('#gritter-notice-wrapper');
before_close(wrap);
wrap.fadeOut(function(){
$(this).remove();
after_close();
});
}
|
[
"function",
"(",
"params",
")",
"{",
"// callbacks (if passed)",
"var",
"before_close",
"=",
"(",
"$",
".",
"isFunction",
"(",
"params",
".",
"before_close",
")",
")",
"?",
"params",
".",
"before_close",
":",
"function",
"(",
")",
"{",
"}",
";",
"var",
"after_close",
"=",
"(",
"$",
".",
"isFunction",
"(",
"params",
".",
"after_close",
")",
")",
"?",
"params",
".",
"after_close",
":",
"function",
"(",
")",
"{",
"}",
";",
"var",
"wrap",
"=",
"$",
"(",
"'#gritter-notice-wrapper'",
")",
";",
"before_close",
"(",
"wrap",
")",
";",
"wrap",
".",
"fadeOut",
"(",
"function",
"(",
")",
"{",
"$",
"(",
"this",
")",
".",
"remove",
"(",
")",
";",
"after_close",
"(",
")",
";",
"}",
")",
";",
"}"
] |
Bring everything to a halt
@param {Object} params A list of callback functions to pass when all notifications are removed
|
[
"Bring",
"everything",
"to",
"a",
"halt"
] |
9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9
|
https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/jquery.gritter.js#L346-L359
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.