_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q60200
|
handleStretchTabs
|
validation
|
function handleStretchTabs (stretchTabs) {
var elements = getElements();
angular.element(elements.wrapper).toggleClass('md-stretch-tabs', shouldStretchTabs());
updateInkBarStyles();
}
|
javascript
|
{
"resource": ""
}
|
q60201
|
handleOffsetChange
|
validation
|
function handleOffsetChange (left) {
var elements = getElements();
var newValue = ((ctrl.shouldCenterTabs || isRtl() ? '' : '-') + left + 'px');
// Fix double-negative which can happen with RTL support
newValue = newValue.replace('--', '');
angular.element(elements.paging).css($mdConstant.CSS.TRANSFORM, 'translate3d(' + newValue + ', 0, 0)');
$scope.$broadcast('$mdTabsPaginationChanged');
}
|
javascript
|
{
"resource": ""
}
|
q60202
|
scroll
|
validation
|
function scroll (event) {
if (!ctrl.shouldPaginate) return;
event.preventDefault();
ctrl.offsetLeft = fixOffset(ctrl.offsetLeft - event.wheelDelta);
}
|
javascript
|
{
"resource": ""
}
|
q60203
|
shouldPaginate
|
validation
|
function shouldPaginate () {
if (ctrl.noPagination || !loaded) return false;
var canvasWidth = $element.prop('clientWidth');
angular.forEach(getElements().tabs, function (tab) {
canvasWidth -= tab.offsetWidth;
});
return canvasWidth < 0;
}
|
javascript
|
{
"resource": ""
}
|
q60204
|
adjustOffset
|
validation
|
function adjustOffset (index) {
var elements = getElements();
if (!angular.isNumber(index)) index = ctrl.focusIndex;
if (!elements.tabs[ index ]) return;
if (ctrl.shouldCenterTabs) return;
var tab = elements.tabs[ index ],
left = tab.offsetLeft,
right = tab.offsetWidth + left,
extraOffset = 32;
// If we are selecting the first tab (in LTR and RTL), always set the offset to 0
if (index == 0) {
ctrl.offsetLeft = 0;
return;
}
if (isRtl()) {
var tabWidthsBefore = calcTabsWidth(Array.prototype.slice.call(elements.tabs, 0, index));
var tabWidthsIncluding = calcTabsWidth(Array.prototype.slice.call(elements.tabs, 0, index + 1));
ctrl.offsetLeft = Math.min(ctrl.offsetLeft, fixOffset(tabWidthsBefore));
ctrl.offsetLeft = Math.max(ctrl.offsetLeft, fixOffset(tabWidthsIncluding - elements.canvas.clientWidth));
} else {
ctrl.offsetLeft = Math.max(ctrl.offsetLeft, fixOffset(right - elements.canvas.clientWidth + extraOffset));
ctrl.offsetLeft = Math.min(ctrl.offsetLeft, fixOffset(left));
}
}
|
javascript
|
{
"resource": ""
}
|
q60205
|
updateInkBarStyles
|
validation
|
function updateInkBarStyles () {
var elements = getElements();
if (!elements.tabs[ ctrl.selectedIndex ]) {
angular.element(elements.inkBar).css({ left: 'auto', right: 'auto' });
return;
}
if (!ctrl.tabs.length) return queue.push(ctrl.updateInkBarStyles);
// if the element is not visible, we will not be able to calculate sizes until it is
// we should treat that as a resize event rather than just updating the ink bar
if (!$element.prop('offsetParent')) return handleResizeWhenVisible();
var index = ctrl.selectedIndex,
totalWidth = elements.paging.offsetWidth,
tab = elements.tabs[ index ],
left = tab.offsetLeft,
right = totalWidth - left - tab.offsetWidth;
if (ctrl.shouldCenterTabs) {
// We need to use the same calculate process as in the pagination wrapper, to avoid rounding deviations.
var tabWidth = calcTabsWidth(elements.tabs);
if (totalWidth > tabWidth) {
$mdUtil.nextTick(updateInkBarStyles, false);
}
}
updateInkBarClassName();
angular.element(elements.inkBar).css({ left: left + 'px', right: right + 'px' });
}
|
javascript
|
{
"resource": ""
}
|
q60206
|
Barcode1D
|
validation
|
function Barcode1D() {
this.mode = MODE_BARWIDTH;
this.width = 0;
this.height = 0;
this.background = '#FFF';
this.barcolor = '#000';
this.type = 'PNG';
this.offset = 0;
this.modulewidth = 1;
}
|
javascript
|
{
"resource": ""
}
|
q60207
|
update
|
validation
|
function update() {
var stateTree = buildTreeJSON(xebraState.getPatchers());
var nodes = d3.hierarchy(stateTree, function(d) {
return d.children;
});
d3Tree(nodes);
var link = g.selectAll(".link")
.data(nodes.descendants().slice(1))
.enter().append("path")
.attr("class", "link")
.attr("d", diagonal);
var node = g.selectAll(".node")
.data(nodes.descendants())
.enter().append("g")
.attr("class", function(d) { return "node" + (d.children ? " node--internal" : " node--leaf"); })
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });
node.append("circle")
.attr("r", 2.5);
node.append("text")
.attr("dy", function(d) { return d.children ? -10 : 0 })
.attr("x", function(d) { return d.children ? -8 : 8; })
.style("text-anchor", "start" )
.text(function(d) { return d.data.name; });
}
|
javascript
|
{
"resource": ""
}
|
q60208
|
message
|
validation
|
function message(msg, thisArg) {
var sig = colors.red(thisArg.name);
sig += ' in plugin ';
sig += '"' + colors.cyan(thisArg.plugin) + '"';
sig += '\n';
sig += msg;
return sig;
}
|
javascript
|
{
"resource": ""
}
|
q60209
|
setDefaults
|
validation
|
function setDefaults(plugin, message, opts) {
if (typeof plugin === 'object') {
return defaults(plugin);
}
opts = opts || {};
if (message instanceof Error) {
opts.error = message;
} else if (typeof message === 'object') {
opts = message;
} else {
opts.message = message;
}
opts.plugin = plugin;
return defaults(opts);
}
|
javascript
|
{
"resource": ""
}
|
q60210
|
_curry2
|
validation
|
function _curry2(fn) {
return function f2(a, b) {
switch (arguments.length) {
case 0:
return f2;
case 1:
return _isPlaceholder(a) ? f2 : _curry1(function (_b) {
return fn(a, _b);
});
default:
return _isPlaceholder(a) && _isPlaceholder(b) ? f2 : _isPlaceholder(a) ? _curry1(function (_a) {
return fn(_a, b);
}) : _isPlaceholder(b) ? _curry1(function (_b) {
return fn(a, _b);
}) : fn(a, b);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q60211
|
_curry1
|
validation
|
function _curry1(fn) {
return function f1(a) {
if (arguments.length === 0 || _isPlaceholder(a)) {
return f1;
} else {
return fn.apply(this, arguments);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q60212
|
_clone
|
validation
|
function _clone(value, refFrom, refTo, deep) {
var copy = function copy(copiedValue) {
var len = refFrom.length;
var idx = 0;
while (idx < len) {
if (value === refFrom[idx]) {
return refTo[idx];
}
idx += 1;
}
refFrom[idx + 1] = value;
refTo[idx + 1] = copiedValue;
for (var key in value) {
copiedValue[key] = deep ? _clone(value[key], refFrom, refTo, true) : value[key];
}
return copiedValue;
};
switch (type(value)) {
case 'Object':
return copy({});
case 'Array':
return copy([]);
case 'Date':
return new Date(value.valueOf());
case 'RegExp':
return _cloneRegExp(value);
default:
return value;
}
}
|
javascript
|
{
"resource": ""
}
|
q60213
|
pipe
|
validation
|
function pipe() {
if (arguments.length === 0) {
throw new Error('pipe requires at least one argument');
}
return _arity(arguments[0].length, reduce(_pipe, arguments[0], tail(arguments)));
}
|
javascript
|
{
"resource": ""
}
|
q60214
|
pipeP
|
validation
|
function pipeP() {
if (arguments.length === 0) {
throw new Error('pipeP requires at least one argument');
}
return _arity(arguments[0].length, reduce(_pipeP, arguments[0], tail(arguments)));
}
|
javascript
|
{
"resource": ""
}
|
q60215
|
_uniqContentEquals
|
validation
|
function _uniqContentEquals(aIterator, bIterator, stackA, stackB) {
var a = _arrayFromIterator(aIterator);
var b = _arrayFromIterator(bIterator);
function eq(_a, _b) {
return _equals(_a, _b, stackA.slice(), stackB.slice());
}
// if *a* array contains any element that is not included in *b*
return !_containsWith(function (b, aItem) {
return !_containsWith(eq, aItem, b);
}, b, a);
}
|
javascript
|
{
"resource": ""
}
|
q60216
|
delaunayRefine
|
validation
|
function delaunayRefine(points, triangulation) {
var stack = []
var numPoints = points.length
var stars = triangulation.stars
for(var a=0; a<numPoints; ++a) {
var star = stars[a]
for(var j=1; j<star.length; j+=2) {
var b = star[j]
//If order is not consistent, then skip edge
if(b < a) {
continue
}
//Check if edge is constrained
if(triangulation.isConstraint(a, b)) {
continue
}
//Find opposite edge
var x = star[j-1], y = -1
for(var k=1; k<star.length; k+=2) {
if(star[k-1] === b) {
y = star[k]
break
}
}
//If this is a boundary edge, don't flip it
if(y < 0) {
continue
}
//If edge is in circle, flip it
if(inCircle(points[a], points[b], points[x], points[y]) < 0) {
stack.push(a, b)
}
}
}
while(stack.length > 0) {
var b = stack.pop()
var a = stack.pop()
//Find opposite pairs
var x = -1, y = -1
var star = stars[a]
for(var i=1; i<star.length; i+=2) {
var s = star[i-1]
var t = star[i]
if(s === b) {
y = t
} else if(t === b) {
x = s
}
}
//If x/y are both valid then skip edge
if(x < 0 || y < 0) {
continue
}
//If edge is now delaunay, then don't flip it
if(inCircle(points[a], points[b], points[x], points[y]) >= 0) {
continue
}
//Flip the edge
triangulation.flip(a, b)
//Test flipping neighboring edges
testFlip(points, triangulation, stack, x, a, y)
testFlip(points, triangulation, stack, a, y, x)
testFlip(points, triangulation, stack, y, b, x)
testFlip(points, triangulation, stack, b, x, y)
}
}
|
javascript
|
{
"resource": ""
}
|
q60217
|
PartialHull
|
validation
|
function PartialHull(a, b, idx, lowerIds, upperIds) {
this.a = a
this.b = b
this.idx = idx
this.lowerIds = lowerIds
this.upperIds = upperIds
}
|
javascript
|
{
"resource": ""
}
|
q60218
|
Event
|
validation
|
function Event(a, b, type, idx) {
this.a = a
this.b = b
this.type = type
this.idx = idx
}
|
javascript
|
{
"resource": ""
}
|
q60219
|
showValidation
|
validation
|
function showValidation(feedback) {
feedback.errors.forEach(function (error) {
console.log('ERROR: ' + error);
});
feedback.warnings.forEach(function (warning) {
console.log('WARNING: ' + warning);
});
console.log("Validator finished with " + feedback.warnings.length + " warnings and " + feedback.errors.length + " errors.");
process.exit(feedback.errors.length > 0 ? 2 : 0);
}
|
javascript
|
{
"resource": ""
}
|
q60220
|
validation
|
function (input, prefix) {
_.forOwn(input, function (value, key) {
if ((/[^\w-]/).test(key)) {
console.warn(key + ': the key format is not valid');
}
if (_.isPlainObject(value)) {
return recursion(value, prefix ? [prefix, key].join('_') : key);
}
result[(prefix ? [null, prefix, key] : [null, key]).join('_')] =
_.isFinite(value) ? value : _.truncate(_.toString(value), {length: 32765}); // 32765 + 1
});
}
|
javascript
|
{
"resource": ""
}
|
|
q60221
|
shallowCopy
|
validation
|
function shallowCopy(src, dst) {
var i = 0;
if (isArray(src)) {
dst = dst || [];
for (; i < src.length; i++) {
dst[i] = src[i];
}
} else if (isObject(src)) {
dst = dst || {};
var keys = Object.keys(src);
for (var l = keys.length; i < l; i++) {
var key = keys[i];
if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
dst[key] = src[key];
}
}
}
return dst || src;
}
|
javascript
|
{
"resource": ""
}
|
q60222
|
push
|
validation
|
function push() {
var name,
value,
browserCookies,
updated;
//delete any cookies deleted in $cookies
for (name in lastCookies) {
if (isUndefined(cookies[name])) {
$browser.cookies(name, undefined);
}
}
//update all cookies updated in $cookies
for(name in cookies) {
value = cookies[name];
if (!angular.isString(value)) {
value = '' + value;
cookies[name] = value;
}
if (value !== lastCookies[name]) {
$browser.cookies(name, value);
updated = true;
}
}
//verify what was actually stored
if (updated){
updated = false;
browserCookies = $browser.cookies();
for (name in cookies) {
if (cookies[name] !== browserCookies[name]) {
//delete or reset all cookies that the browser dropped from $cookies
if (isUndefined(browserCookies[name])) {
delete cookies[name];
} else {
cookies[name] = browserCookies[name];
}
updated = true;
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q60223
|
$SnifferProvider
|
validation
|
function $SnifferProvider() {
this.$get = ['$window', '$document', function($window, $document) {
var eventSupport = {},
android =
int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
document = $document[0] || {},
documentMode = document.documentMode,
vendorPrefix,
vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/,
bodyStyle = document.body && document.body.style,
transitions = false,
animations = false,
match;
if (bodyStyle) {
for(var prop in bodyStyle) {
if(match = vendorRegex.exec(prop)) {
vendorPrefix = match[0];
vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
break;
}
}
if(!vendorPrefix) {
vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
}
transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
if (android && (!transitions||!animations)) {
transitions = isString(document.body.style.webkitTransition);
animations = isString(document.body.style.webkitAnimation);
}
}
return {
// Android has history.pushState, but it does not update location correctly
// so let's not use the history API at all.
// http://code.google.com/p/android/issues/detail?id=17471
// https://github.com/angular/angular.js/issues/904
// older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
// so let's not use the history API also
// We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
// jshint -W018
history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
// jshint +W018
hashchange: 'onhashchange' in $window &&
// IE8 compatible mode lies
(!documentMode || documentMode > 7),
hasEvent: function(event) {
// IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
// it. In particular the event is not fired when backspace or delete key are pressed or
// when cut operation is performed.
if (event == 'input' && msie == 9) return false;
if (isUndefined(eventSupport[event])) {
var divElm = document.createElement('div');
eventSupport[event] = 'on' + event in divElm;
}
return eventSupport[event];
},
csp: csp(),
vendorPrefix: vendorPrefix,
transitions : transitions,
animations : animations,
android: android,
msie : msie,
msieDocumentMode: documentMode
};
}];
}
|
javascript
|
{
"resource": ""
}
|
q60224
|
addNativeHtml5Validators
|
validation
|
function addNativeHtml5Validators(ctrl, validatorName, badFlags, ignoreFlags, validity) {
if (isObject(validity)) {
ctrl.$$hasNativeValidators = true;
var validator = function(value) {
// Don't overwrite previous validation, don't consider valueMissing to apply (ng-required can
// perform the required validation)
if (!ctrl.$error[validatorName] &&
!testFlags(validity, ignoreFlags) &&
testFlags(validity, badFlags)) {
ctrl.$setValidity(validatorName, false);
return;
}
return value;
};
ctrl.$parsers.push(validator);
}
}
|
javascript
|
{
"resource": ""
}
|
q60225
|
validation
|
function (docular_webapp_target) {
var ABS_SCRIPTS = __dirname;
var ABS_LIB = path.resolve(ABS_SCRIPTS + '/..');
var ABS_DEFAULT_GENERATED_WEBAPP = ABS_LIB + '/generated/';
return docular_webapp_target ? path.resolve(process.cwd() + '/' + docular_webapp_target) : path.relative(process.cwd(), ABS_DEFAULT_GENERATED_WEBAPP);
}
|
javascript
|
{
"resource": ""
}
|
|
q60226
|
validation
|
function(expr, context, subIntegral) {
var simplified = simplify.simplifyCore(expr, context);
if(!simplified.equals(expr)) {
return subIntegral(simplified, context, "simplified expression");
}
}
|
javascript
|
{
"resource": ""
}
|
|
q60227
|
_integral
|
validation
|
function _integral(expr, context, lastRuleComment) {
var exprString = expr.toString({
parenthesis: 'all',
handler: function(node, options) {
if(node.type === 'ParenthesisNode') {
return '(' + node.content.toString(options) + ')';
}
}
});
var debugComment = lastRuleComment ? lastRuleComment + ": " : "";
debugComment += "find integral of " + exprString + " d" + context.variable.name;
context.printDebug(debugComment);
context.debugIndent++;
// Check if we already tried to integrate this expression
if(context.subIntegral[exprString] !== undefined) {
// This could be null, indicating that we couldn't find an integral for
// it (or we are currenly working on it a few levels of recursion up!)
context.printDebug("Precomputed: " + context.subIntegral[exprString]);
context.debugIndent--;
return context.subIntegral[exprString];
}
// Remember that we are working on this integral, just haven't found a
// solution yet!
context.subIntegral[exprString] = null;
for(var i = 0; i < context.rules.length; i++) {
var result = context.rules[i](expr, context, _integral);
if(result !== undefined && result !== null) {
// Remember this solution!
context.subIntegral[exprString] = result;
context.printDebug("Computed: " + result.toString({parenthesis: 'all'}));
context.debugIndent--;
return result;
}
}
// We couldn't find a solution :(
context.printDebug("No integral found");
context.debugIndent--;
return null;
}
|
javascript
|
{
"resource": ""
}
|
q60228
|
checkFile
|
validation
|
function checkFile( src ) {
if ( ! grunt.file.exists( src ) ) {
grunt.log.error( "Source file \"" + src + "\" not fount." );
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q60229
|
parseInlineValues
|
validation
|
function parseInlineValues( string ) {
var match;
var values = {};
while( match = attributesRegex.exec( string ) ) {
values[ match[ 1 ] ] = match[ 2 ];
}
return values;
}
|
javascript
|
{
"resource": ""
}
|
q60230
|
applyIndent
|
validation
|
function applyIndent( indent, content ) {
if ( ! indent || indent.length < 1 ) {
return content;
}
return content
.split( "\n" )
.map( function( line ) {
// do not indent empty lines
return line.trim() !== "" ? ( indent + line ) : "";
} )
.join( "\n" );
}
|
javascript
|
{
"resource": ""
}
|
q60231
|
getArrayValues
|
validation
|
function getArrayValues( string, values ) {
string = string.split( " " ).join( "" );
if ( arrayRegex.test( string ) )
return string.match( arrayRegex )[ 1 ].split( "," );
else {
var array = processPlaceholder( string, values );
if ( ! mout.lang.isArray( array ) ) array = [];
return array;
}
}
|
javascript
|
{
"resource": ""
}
|
q60232
|
validateIf
|
validation
|
function validateIf( inlineValues, values ) {
if ( "_if" in inlineValues ) {
var value = inlineValues[ "_if" ];
delete inlineValues[ "_if" ];
var params = {};
var condition = value.replace( ifRegex, function( match, varname ) {
if( ! varname ) return match;
var resolved = resolveName( varname, values );
// check for semantic falsy values
if ( options.semanticIf === true ) {
resolved = [ "no", "off" ].indexOf( resolved ) === -1;
} else if ( mout.lang.isArray( options.semanticIf ) ) {
resolved = options.semanticIf.indexOf( resolved ) === -1;
} else if ( mout.lang.isFunction( options.semanticIf ) ) {
resolved = options.semanticIf( resolved );
}
params[ varname ] = resolved;
return "params['" + varname + "']";
});
try {
/* jshint evil:true */
/* eslint-disable no-eval */
return ! eval( condition );
} catch( e ) {
grunt.log.error( "Invalid if condition: '" + value + "'" );
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q60233
|
validateRender
|
validation
|
function validateRender( inlineValues ) {
if ( "_render" in inlineValues ) {
var skipValue = inlineValues[ "_render" ];
if ( skipValue in options ) {
return ! options[ skipValue ];
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q60234
|
validateForEach
|
validation
|
function validateForEach( inlineValues, values, array ) {
if ( "_foreach" in inlineValues ) {
// test for object syntax `object as key => value`
var match;
if ( match = forEachRegex.exec( inlineValues[ "_foreach" ] ) ) {
var object = {
keyName: match[ 2 ],
valueName: match[ 3 ],
values: values[ match[ 1 ] ]
};
return object;
}
var set = inlineValues[ "_foreach" ].split( ":" );
delete inlineValues[ "_foreach" ];
// as transforms may contain colons, join rest of list to recreate original string
getArrayValues( set.slice( 1 ).join( ":" ), values ).forEach( function( value ) {
array.push( value );
} );
return set[ 0 ];
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q60235
|
validateBake
|
validation
|
function validateBake( inlineValues ) {
if ( "_bake" in inlineValues ) {
var signature = inlineValues[ "_bake" ];
delete inlineValues[ "_bake" ];
var set = signature.split( ">", 2 );
return {
src: mout.string.trim( set[0] ),
dest: mout.string.trim( set[1] )
};
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q60236
|
validateProcess
|
validation
|
function validateProcess( inlineValues ) {
if ( "_process" in inlineValues ) {
var value = inlineValues[ "_process" ];
delete inlineValues[ "_process" ];
return String(value).toLowerCase() === 'true' ;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q60237
|
extractSection
|
validation
|
function extractSection( content ) {
var depth = 0; // tracks how difference between found opening and closing tags
var start = 0; // character position in `content` where inner-content starts
var position = 0; // current character position within _original_ content
var length = 0; // length section (= spacing plus bake-tag) we currently evaluate
var remain = content; // content left for further extraction
var section = {};
do {
var result = remain.match( regex );
if( ! result ) break;
length = result[ 0 ].length;
position += result.index;
if( depth === 0 ) {
start = position + length;
section = mout.object.merge( section, parseSignature( result[ 4 ] ), {
before: content.slice( 0, position ),
linebreak: result[ 1 ],
indent: result[ 2 ]
} );
}
remain = remain.slice( result.index + length );
depth += ( result[ 3 ] === "-start" );
depth -= ( result[ 3 ] === "-end" );
if( depth === 0 ) {
return mout.object.merge( section, {
inner: content.slice( start, position ),
after: content.slice( position + length )
} );
}
position += length;
} while( true );
return null;
}
|
javascript
|
{
"resource": ""
}
|
q60238
|
parse
|
validation
|
function parse( fileContent, filePath, destFile, values ) {
var section = extractSection( fileContent );
if( section ) {
fileContent = processContent( section.before, values );
if( section.inner ) {
fileContent += replaceString( section.inner, "", "", filePath, section.attributes, filePath, destFile, values );
} else if( section.includePath ) {
fileContent += replaceFile( section.linebreak, section.indent, section.includePath, section.attributes, filePath, destFile, values );
}
fileContent += parse( section.after, filePath, destFile, values );
} else {
return processContent( fileContent, values );
}
return fileContent;
}
|
javascript
|
{
"resource": ""
}
|
q60239
|
processContent
|
validation
|
function processContent( content, values ) {
return mout.lang.isFunction( options.process ) ? options.process( content, values ) : content;
}
|
javascript
|
{
"resource": ""
}
|
q60240
|
compare
|
validation
|
function compare(a, b, index) {
return (
(a.charCodeAt(index) || 0) - (b.charCodeAt(index) || 0) ||
compare(a, b, index + 1)
)
}
|
javascript
|
{
"resource": ""
}
|
q60241
|
javascript
|
validation
|
function javascript(node) {
if (!is(node, 'script')) {
return false
}
if (has(node, 'type')) {
return check(node.properties.type)
}
return !has(node, 'language') || check(node.properties.language, 'text/')
}
|
javascript
|
{
"resource": ""
}
|
q60242
|
check
|
validation
|
function check(value, prefix) {
var val
if (typeof value !== 'string') {
return false
}
val = trim(value.split(';', 1)[0]).toLowerCase()
return val === '' || mime.indexOf((prefix || '') + val) !== -1
}
|
javascript
|
{
"resource": ""
}
|
q60243
|
collapsable
|
validation
|
function collapsable(node) {
return (
is('text', node) ||
element(node, list) ||
embedded(node) ||
bodyOK(node) ||
(element(node, 'meta') && has(node, 'itemProp'))
)
}
|
javascript
|
{
"resource": ""
}
|
q60244
|
render
|
validation
|
function render(req, res, next) {
if (!req.session[sessionName].length) {
next();
} else {
const resultHTML = [];
async.each(
req.session[sessionName],
function(item, next) {
beforeSingleRender(item, function(error, item) {
if (error) return next(error);
app.render(viewName, item, function(error, html) {
if (error) return next(error);
resultHTML.push(html);
next(null);
})
})
},
function(error) {
if (error) return next(error);
req.session[sessionName].length = 0;
afterAllRender(resultHTML, function(error, html) {
if (error) return next(error);
res.locals[localsName] = html;
next();
})
}
)
}
}
|
javascript
|
{
"resource": ""
}
|
q60245
|
FlashMiddleware
|
validation
|
function FlashMiddleware(req, res, next) {
if (!isObject(req.session)) throw new Error('express-session is required. (npm i express-session)');
if (!req.session[sessionName] || !isArray(req.session[sessionName])) req.session[sessionName] = [];
/**
* Utility used to programmatically add flash notifications
* @method Flash Utility
*/
req[utilityName] = function() {
const argc = arguments.length;
let notification;
let redirect = REDIRECT;
// Parse arguments
if (argc) {
if (argc === 1) {
const arg = arguments[0];
if (isObject(arg)) {
notification = arg;
redirect = (arg.redirect === undefined) ? redirect : arg.redirect;
} else {
notification = {
message: '' + arg
};
}
} else {
notification = {
type: '' + arguments[0],
message: '' + arguments[1]
};
redirect = (arguments[2] === undefined) ? redirect : arguments[2];
}
}
// Queue Notification
if (notification && req.session[sessionName]) {
req.session[sessionName].push(notification);
}
// If redirect is set, refresh or redirect, accordingly. Otherwise, render the
// notifications now since it's on this request where they will be displayed.
if (redirect) {
const redirectUrl = (typeof redirect === 'string') ? redirect : req.originalUrl;
res.redirect(redirectUrl);
} else {
/**
* When there is no redirect, notifications must be rendered now and since
* rendering is async (and this method is sync), a *promise* like function is returned.
* The function can be called with a callback that will be called after all notifcations
* are rendered, otherwise, rendering will be done during the next request.
*/
return function ManualRender(callback) {
render(req, res, callback);
}
}
}
/**
* Process Queued Notifications
*/
render(req, res, next);
}
|
javascript
|
{
"resource": ""
}
|
q60246
|
getFrameworkPath
|
validation
|
function getFrameworkPath({ framework, baseDir }) {
const pkgPath = path.join(baseDir, 'package.json');
assert(fs.existsSync(pkgPath), `${pkgPath} should exist`);
const moduleDir = path.join(baseDir, 'node_modules');
const pkg = utility.readJSONSync(pkgPath);
// 1. pass framework or customEgg
if (framework) {
// 1.1 framework is an absolute path
// framework: path.join(baseDir, 'node_modules/${frameworkName}')
if (path.isAbsolute(framework)) {
assert(fs.existsSync(framework), `${framework} should exist`);
return framework;
}
// 1.2 framework is a npm package that required by application
// framework: 'frameworkName'
return assertAndReturn(framework, moduleDir);
}
// 2. framework is not specified
// 2.1 use framework name from pkg.egg.framework
if (pkg.egg && pkg.egg.framework) {
return assertAndReturn(pkg.egg.framework, moduleDir);
}
// 2.2 use egg by default
return assertAndReturn('egg', moduleDir);
}
|
javascript
|
{
"resource": ""
}
|
q60247
|
getFrameworkOrEggPath
|
validation
|
function getFrameworkOrEggPath(cwd, eggNames) {
eggNames = eggNames || [ 'egg' ];
const moduleDir = path.join(cwd, 'node_modules');
if (!fs.existsSync(moduleDir)) {
return '';
}
// try to get framework
// 1. try to read egg.framework property on package.json
const pkgFile = path.join(cwd, 'package.json');
if (fs.existsSync(pkgFile)) {
const pkg = utility.readJSONSync(pkgFile);
if (pkg.egg && pkg.egg.framework) {
return path.join(moduleDir, pkg.egg.framework);
}
}
// 2. try the module dependencies includes eggNames
const names = fs.readdirSync(moduleDir);
for (const name of names) {
const pkgfile = path.join(moduleDir, name, 'package.json');
if (!fs.existsSync(pkgfile)) {
continue;
}
const pkg = utility.readJSONSync(pkgfile);
if (pkg.dependencies) {
for (const eggName of eggNames) {
if (pkg.dependencies[eggName]) {
return path.join(moduleDir, name);
}
}
}
}
// try to get egg
for (const eggName of eggNames) {
const pkgfile = path.join(moduleDir, eggName, 'package.json');
if (fs.existsSync(pkgfile)) {
return path.join(moduleDir, eggName);
}
}
return '';
}
|
javascript
|
{
"resource": ""
}
|
q60248
|
autoInjectServices
|
validation
|
function autoInjectServices(object, args) {
if(args.length === 0 ) return;
let code = object.constructor.toString();
code = code.match('constructor\\([\\$a-zA-Z0-9\\,\\s]+\\)')[0];
code = code.substring(code.indexOf('(')+1, code.indexOf(')'));
code = code.split(', ');
for (let i = 0; i < code.length; i++) {
Object.defineProperty(object, code[i], {value: args[i]})
}
}
|
javascript
|
{
"resource": ""
}
|
q60249
|
SetterObservable
|
validation
|
function SetterObservable(getter, setter) {
this.setter = setter;
this.observation = new Observation(getter);
this.handler = this.handler.bind(this);
//!steal-remove-start
if (process.env.NODE_ENV !== 'production') {
canReflect.assignSymbols(this, {
"can.getName": function() {
return (
canReflect.getName(this.constructor) +
"<" +
canReflect.getName(getter) +
">"
);
}
});
Object.defineProperty(this.handler, "name", {
value: canReflect.getName(this) + ".handler"
});
}
//!steal-remove-end
}
|
javascript
|
{
"resource": ""
}
|
q60250
|
AsyncObservable
|
validation
|
function AsyncObservable(fn, context, initialValue) {
this.resolve = this.resolve.bind(this);
this.lastSetValue = new SimpleObservable(initialValue);
this.handler = this.handler.bind(this);
function observe() {
this.resolveCalled = false;
// set inGetter flag to avoid calling `resolve` redundantly if it is called
// synchronously in the getter
this.inGetter = true;
var newVal = fn.call(
context,
this.lastSetValue.get(),
this.bound === true ? this.resolve : undefined
);
this.inGetter = false;
// if the getter returned a value, resolve with the value
if (newVal !== undefined) {
this.resolve(newVal);
}
// otherwise, if `resolve` was called synchronously in the getter,
// resolve with the value passed to `resolve`
else if (this.resolveCalled) {
this.resolve(this._value);
}
// if bound, the handlers will be called by `resolve`
// returning here would cause a duplicate event
if (this.bound !== true) {
return newVal;
}
}
//!steal-remove-start
if (process.env.NODE_ENV !== 'production') {
canReflect.assignSymbols(this, {
"can.getName": function() {
return (
canReflect.getName(this.constructor) +
"<" +
canReflect.getName(fn) +
">"
);
}
});
Object.defineProperty(this.handler, "name", {
value: canReflect.getName(this) + ".handler"
});
Object.defineProperty(observe, "name", {
value: canReflect.getName(fn) + "::" + canReflect.getName(this.constructor)
});
}
//!steal-remove-end
this.observation = new Observation(observe, this);
}
|
javascript
|
{
"resource": ""
}
|
q60251
|
load
|
validation
|
function load(dotGraph, appendTo) {
var dotAST = parseDot(dotGraph);
if (dotAST.length > 1 && appendTo !== undefined) {
throw new Error('Dot file contains multiple graphs. Cannot use `saveTo` in this case');
}
if (!appendTo) {
appendTo = require('ngraph.graph')();
}
// by default load will only load first graph:
return loadOne(appendTo, dotAST[0]);
}
|
javascript
|
{
"resource": ""
}
|
q60252
|
validation
|
function() {
var sendTracerInit = function() {
sendObjectToInspectedPage({ content: { type: "MEIOSIS_TRACER_INIT" } })
}
var triggerStreamValue = function(index, value) {
sendObjectToInspectedPage({ content: {
type: "MEIOSIS_TRIGGER_STREAM_VALUE",
index: index,
value: value
} })
}
tracer = window.meiosisTracer({
selector: "#meiosis-tracer",
sendTracerInit: sendTracerInit,
triggerStreamValue: triggerStreamValue,
direction: "auto"
})
}
|
javascript
|
{
"resource": ""
}
|
|
q60253
|
recurse
|
validation
|
function recurse (streams) {
if(streams.length < 2)
return
streams[0].pipe(streams[1])
recurse(streams.slice(1))
}
|
javascript
|
{
"resource": ""
}
|
q60254
|
TemporaryCredentials
|
validation
|
function TemporaryCredentials(params) {
AWS.Credentials.call(this);
this.loadMasterCredentials();
this.expired = true;
this.params = params || {};
if (this.params.RoleArn) {
this.params.RoleSessionName =
this.params.RoleSessionName || 'temporary-credentials';
}
this.service = new AWS.STS({params: this.params});
}
|
javascript
|
{
"resource": ""
}
|
q60255
|
Service
|
validation
|
function Service(config) {
if (!this.loadServiceClass) {
throw AWS.util.error(new Error(),
'Service must be constructed with `new\' operator');
}
var ServiceClass = this.loadServiceClass(config || {});
if (ServiceClass) return new ServiceClass(config);
this.initialize(config);
}
|
javascript
|
{
"resource": ""
}
|
q60256
|
getSignerClass
|
validation
|
function getSignerClass() {
var version;
if (this.config.signatureVersion) {
version = this.config.signatureVersion;
} else {
version = this.api.signatureVersion;
}
return AWS.Signers.RequestSigner.getVersion(version);
}
|
javascript
|
{
"resource": ""
}
|
q60257
|
defineMethods
|
validation
|
function defineMethods(svc) {
AWS.util.each(svc.prototype.api.operations, function iterator(method) {
if (svc.prototype[method]) return;
svc.prototype[method] = function (params, callback) {
return this.makeRequest(method, params, callback);
};
});
}
|
javascript
|
{
"resource": ""
}
|
q60258
|
abort
|
validation
|
function abort() {
this.removeAllListeners('validateResponse');
this.removeAllListeners('extractError');
this.on('validateResponse', function addAbortedError(resp) {
resp.error = AWS.util.error(new Error('Request aborted by user'), {
code: 'RequestAbortedError', retryable: false
});
});
if (this.httpRequest.stream) { // abort HTTP stream
this.httpRequest.stream.abort();
if (this.httpRequest._abortCallback) {
this.httpRequest._abortCallback();
} else {
this.removeAllListeners('send'); // haven't sent yet, so let's not
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q60259
|
eachItem
|
validation
|
function eachItem(callback) {
function wrappedCallback(err, data) {
if (err) return callback(err, null);
if (data === null) return callback(null, null);
var config = this.request.service.paginationConfig(this.request.operation);
var resultKey = config.resultKey;
if (Array.isArray(resultKey)) resultKey = resultKey[0];
var results = AWS.util.jamespath.query(resultKey, data);
AWS.util.arrayEach(results, function(result) {
AWS.util.arrayEach(result, function(item) { callback(null, item); });
});
}
this.eachPage(wrappedCallback);
}
|
javascript
|
{
"resource": ""
}
|
q60260
|
createReadStream
|
validation
|
function createReadStream() {
var streams = AWS.util.nodeRequire('stream');
var req = this;
var stream = null;
var legacyStreams = false;
if (AWS.HttpClient.streamsApiVersion === 2) {
stream = new streams.Readable();
stream._read = function() {};
} else {
stream = new streams.Stream();
stream.readable = true;
}
stream.sent = false;
stream.on('newListener', function(event) {
if (!stream.sent && (event === 'data' || event === 'readable')) {
if (event === 'data') legacyStreams = true;
stream.sent = true;
process.nextTick(function() { req.send(function() { }); });
}
});
this.on('httpHeaders', function streamHeaders(statusCode, headers, resp) {
if (statusCode < 300) {
this.httpRequest._streaming = true;
req.removeListener('httpData', AWS.EventListeners.Core.HTTP_DATA);
req.removeListener('httpError', AWS.EventListeners.Core.HTTP_ERROR);
req.on('httpError', function streamHttpError(error, resp) {
resp.error = error;
resp.error.retryable = false;
});
var httpStream = resp.httpResponse.stream;
if (legacyStreams) {
httpStream.on('data', function(arg) {
stream.emit('data', arg);
});
httpStream.on('end', function() {
stream.emit('end');
});
} else {
httpStream.on('readable', function() {
var chunk;
do {
chunk = httpStream.read();
if (chunk !== null) stream.push(chunk);
} while (chunk !== null);
stream.read(0);
});
httpStream.on('end', function() {
stream.push(null);
});
}
httpStream.on('error', function(err) {
stream.emit('error', err);
});
}
});
this.on('error', function(err) {
stream.emit('error', err);
});
return stream;
}
|
javascript
|
{
"resource": ""
}
|
q60261
|
constructor
|
validation
|
function constructor(service, state) {
this.service = service;
this.state = state;
if (typeof this.state === 'object') {
AWS.util.each.call(this, this.state, function (key, value) {
this.state = key;
this.expectedValue = value;
});
}
this.loadWaiterConfig(this.state);
if (!this.expectedValue) {
this.expectedValue = this.config.successValue;
}
}
|
javascript
|
{
"resource": ""
}
|
q60262
|
checkSuccess
|
validation
|
function checkSuccess(resp) {
if (!this.config.successPath) {
return resp.httpResponse.statusCode < 300;
}
var r = AWS.util.jamespath.find(this.config.successPath, resp.data);
if (this.config.failureValue &&
this.config.failureValue.indexOf(r) >= 0) {
return null; // fast fail
}
if (this.expectedValue) {
return r === this.expectedValue;
} else {
return r ? true : false;
}
}
|
javascript
|
{
"resource": ""
}
|
q60263
|
checkError
|
validation
|
function checkError(resp) {
var value = this.config.successValue;
if (typeof value === 'number') {
return resp.httpResponse.statusCode === value;
} else {
return resp.error && resp.error.code === value;
}
}
|
javascript
|
{
"resource": ""
}
|
q60264
|
SharedIniFileCredentials
|
validation
|
function SharedIniFileCredentials(options) {
AWS.Credentials.call(this);
options = options || {};
this.filename = options.filename;
this.profile = options.profile || process.env.AWS_PROFILE || 'default';
this.get(function() {});
}
|
javascript
|
{
"resource": ""
}
|
q60265
|
getId
|
validation
|
function getId(callback) {
var self = this;
if (typeof self.params.IdentityId === 'string') return callback();
self.cognito.getId(function(err, data) {
if (!err && data.IdentityId) {
self.params.IdentityId = data.IdentityId;
}
callback(err, data);
});
}
|
javascript
|
{
"resource": ""
}
|
q60266
|
validation
|
function(collection, key, ip) {
if (!collection) {
collection = {};
}
if (!collection[key]) {
collection[key] = [];
}
collection[key].push(ip);
}
|
javascript
|
{
"resource": ""
}
|
|
q60267
|
getDataContext
|
validation
|
function getDataContext(ctxOrCanvas) {
if (ctxOrCanvas instanceof HTMLCanvasElement) {
return getDataContext(ctxOrCanvas.getContext('2d'));
}
var ctx = ctxOrCanvas;
if (stubGetDataContext) {
return stubGetDataContext(ctx);
} else {
for (var i = 0; i < getDataContext.cache.length; i++) {
var pair = getDataContext.cache[i];
if (pair[0] == ctx) return pair[1];
}
var dtx = new DataContext(ctx);
getDataContext.cache.push([ctx, dtx]);
return dtx;
}
}
|
javascript
|
{
"resource": ""
}
|
q60268
|
findRecorder
|
validation
|
function findRecorder(div, selector) {
if (!div) {
if (!RecordingContext.recorders) {
throw 'You must call RecordingContext.recordAll() before using other RecordingContext static methods';
} else if (RecordingContext.recorders.length == 0) {
throw 'Called a RecordingContext method, but no canvases are being recorded.';
} else if (RecordingContext.recorders.length > 1) {
throw 'Called a RecordingContext method while multiple canvases were being recorded. Specify one using a div and selector.';
} else {
return RecordingContext.recorders[0][1];
}
} else {
return RecordingContext.recorderForSelector(div, selector);
}
}
|
javascript
|
{
"resource": ""
}
|
q60269
|
ClickTrackingContext
|
validation
|
function ClickTrackingContext(ctx, px, py) {
forward(this, ctx);
var stack = [];
this.hits = [];
this.hit = null;
var that = this;
function recordHit() {
that.hits.unshift(Array.prototype.slice.call(stack));
that.hit = that.hits[0];
}
this.pushObject = function(o) {
stack.unshift(o);
};
this.popObject = function() {
stack.shift();
};
this.reset = function() {
this.hits = [];
this.hit = null;
};
// These are (most of) the canvas methods which draw something.
// TODO: would it make sense to purge existing hits covered by this?
this.clearRect = function(x, y, w, h) { };
this.fillRect = function(x, y, w, h) {
if (px >= x && px <= x + w && py >= y && py <= y + h) recordHit();
};
this.strokeRect = function(x, y, w, h) {
// ...
};
this.fill = function(fillRule) {
// TODO: implement fillRule
if (ctx.isPointInPath(px, py)) recordHit();
};
this.stroke = function() {
if (ctx.isPointInStroke(px, py)) recordHit();
};
this.fillText = function(text, x, y, maxWidth) {
// ...
};
this.strokeText = function(text, x, y, maxWidth) {
// ...
};
}
|
javascript
|
{
"resource": ""
}
|
q60270
|
stringEscape
|
validation
|
function stringEscape (str) {
let stringArray = str.toString().split('');
for (let j = 0; j < stringArray.length; j++) {
for (let i = 0; i < escapeArray.length; i++) {
if (stringArray[j] === escapeArray[i]) {
stringArray[j] = '\\' + escapeArray[i];
}
}
}
return stringArray.join('');
}
|
javascript
|
{
"resource": ""
}
|
q60271
|
get
|
validation
|
function get(czConfig) {
const scopes = [];
if (typeof czConfig.scopes === 'undefined') {
return defaults;
}
for (const scope of czConfig.scopes) {
scopes.push(scope.name);
}
if (typeof czConfig.scopeOverrides === 'undefined') {
return scopes;
}
for (const type of Object.keys(czConfig.scopeOverrides)) {
for (const scope of czConfig.scopeOverrides[type]) {
scopes.push(scope.name);
}
}
return scopes.filter(function (value, index, scope) {
return scope.indexOf(value) === index;
});
}
|
javascript
|
{
"resource": ""
}
|
q60272
|
get
|
validation
|
function get(pathOrCzConfig, defaultConfig) {
const config = Object.assign(cloneDeep(defaults), cloneDeep(defaultConfig) || {});
let czConfig = pathOrCzConfig || {};
if (typeof pathOrCzConfig === 'string') {
czConfig = CzConfig.get(pathOrCzConfig);
}
// Converts the `scopes` and `scopeOverrides` into `scope-enum` rule.
const hasScopeEnum = Object.prototype.hasOwnProperty.call(config.rules, 'scope-enum');
if (
hasScopeEnum &&
(typeof czConfig.scopes !== 'undefined' || typeof czConfig.scopeOverrides !== 'undefined')
) {
config.rules['scope-enum'][2] = Scopes.get(czConfig);
}
// Removes empty `scope-enum` rule.
if (hasScopeEnum && !config.rules['scope-enum'][2].length) {
delete config.rules['scope-enum'];
}
// Converts the `types` into `type-enum` rule.
const hasTypeEnum = Object.prototype.hasOwnProperty.call(config.rules, 'type-enum');
if (hasTypeEnum && typeof czConfig.types !== 'undefined') {
config.rules['type-enum'][2] = Types.get(czConfig);
}
// Removes empty `type-enum` rule.
if (hasTypeEnum && !config.rules['type-enum'][2].length) {
delete config.rules['type-enum'];
}
return config;
}
|
javascript
|
{
"resource": ""
}
|
q60273
|
get
|
validation
|
function get(path) {
let czConfig;
try {
fs.accessSync(path, fs.R_OK);
czConfig = require(path);
} catch (err) {
czConfig = {};
}
return czConfig;
}
|
javascript
|
{
"resource": ""
}
|
q60274
|
get
|
validation
|
function get(czConfig) {
const types = [];
if (typeof czConfig.types === 'undefined') {
return defaults;
}
for (const type of czConfig.types) {
types.push(type.value);
}
return types;
}
|
javascript
|
{
"resource": ""
}
|
q60275
|
use
|
validation
|
function use(code, lightColor) {
return util.format(base, (lightColor === true) ? code + colorLightValueChange : code);
}
|
javascript
|
{
"resource": ""
}
|
q60276
|
text
|
validation
|
function text(message, effect, lightColor) {
return [
use(effect[0], lightColor),
String(message),
use(effect[1], lightColor)
].join('');
}
|
javascript
|
{
"resource": ""
}
|
q60277
|
clearLine
|
validation
|
function clearLine() {
if (process.stdout.clearLine) {
process.stdout.clearLine();
process.stdout.cursorTo(0);
} else {
var str = '\r',
i = 0;
for (i = 0; i < lastLineLength; i++) {
str += ' ';
}
process.stdout.write(str);
}
lastLineLength = 0;
return self;
}
|
javascript
|
{
"resource": ""
}
|
q60278
|
validation
|
function () {
L.DomUtil.empty(this._container);
var legends = this.options.legends;
if (!legends) return;
legends.forEach(function(legend) {
if (!legend.elements) return;
var elements = legend.elements;
var className = 'legend-block';
if (this.options.detectStretched) {
if (elements.length === 3 && elements[0].label !== '' && elements[1].label === '' && elements[2].label !== ''){
legend.type = 'stretched';
}
}
if (legend.type === 'stretched') {
className += ' legend-stretched';
}
var block = L.DomUtil.create('div', className, this._container);
if (this.options.collapseSimple && elements.length == 1 && !elements[0].label){
this._addElement(elements[0].imageData, legend.name, block);
return;
}
if (legend.name) {
var header = L.DomUtil.create('h4', null, block);
L.DomUtil.create('div', 'caret', header);
L.DomUtil.create('span', null, header).innerHTML = legend.name;
L.DomEvent.on(header, 'click', function() {
if (L.DomUtil.hasClass(header, 'closed')) {
L.DomUtil.removeClass(header, 'closed');
}
else {
L.DomUtil.addClass(header, 'closed');
}
}, this);
}
var elementContainer = L.DomUtil.create('div', 'legend-elements', block);
elements.forEach(function (element) {
this._addElement(element.imageData, element.label, elementContainer);
}, this);
}, this);
}
|
javascript
|
{
"resource": ""
}
|
|
q60279
|
updateLocation
|
validation
|
function updateLocation(method) {
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return {
type: _constants.CALL_HISTORY_METHOD,
payload: { method: method, args: args }
};
};
}
|
javascript
|
{
"resource": ""
}
|
q60280
|
getHeader
|
validation
|
function getHeader (data) {
var header = {}
header.umid = data.slice(0, 3)
header.mt_version = data.slice(3, 5)
header.rics = data.slice(5, 9)
header.key_id = data.slice(9, 14)
return header
}
|
javascript
|
{
"resource": ""
}
|
q60281
|
timeOutput
|
validation
|
function timeOutput(difference, timeValue, pluralTimeName) {
let result = '';
if (Math.round(difference / timeValue) === 1) {
result = `1 ${pluralTimeName.substring(0, pluralTimeName.length - 1)} ago`;
} else {
result = `${Math.round(difference / timeValue)} ${pluralTimeName} ago`;
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q60282
|
RestClient
|
validation
|
function RestClient(baseUrl) {
if (typeof baseUrl !== 'string') {
if (typeof document !== 'undefined') {
baseUrl = document.getElementById('baseUrlHolder').getAttribute('data') + '/api/';
} else {
baseUrl = '/api/';
}
}
this.organizations = new OrganizationsClient(baseUrl);
this.projects = new ProjectsClient(baseUrl);
this.user = new UserClient(baseUrl);
this.users = new UsersClient(baseUrl);
/**
* Gets the current user
* @return {Promise} //TODO: How to document the resolved value.
*/
this.getStatus = () => {
return this.user.get(['status']);
};
}
|
javascript
|
{
"resource": ""
}
|
q60283
|
register
|
validation
|
function register(ports, log) {
// Mapped to Storage API: https://developer.mozilla.org/en-US/docs/Web/API/Storage
ports.storageGetItem.subscribe(storageGetItem);
ports.storageSetItem.subscribe(storageSetItem);
ports.storageRemoveItem.subscribe(storageRemoveItem);
ports.storageClear.subscribe(storageClear);
// Not in Storage API
ports.storagePushToSet.subscribe(storagePushToSet);
ports.storageRemoveFromSet.subscribe(storageRemoveFromSet);
// StorageEvent API
storageEventListenerPorts.push(ports);
log = log || function() {};
function storageGetItem(key) {
log('storageGetItem', key);
const response = getLocalStorageItem(key);
log('storageGetItemResponse', key, response);
ports.storageGetItemResponse.send([key, response]);
}
function storageSetItem([key, value]) {
log('storageSetItem', key, value);
setLocalStorageItem(key, value);
}
function storageRemoveItem(key) {
log('storageRemoveItem', key);
window.localStorage.removeItem(key);
}
function storageClear() {
log('storageClear');
window.localStorage.clear();
}
// A Set is a list with only unique values. (No duplication.)
function storagePushToSet([key, value]) {
log('storagePushToSet', key, value);
const item = getLocalStorageItem(key);
const list = Array.isArray(item) ? item : [];
if (list.indexOf(value) === -1) {
list.push(value);
}
setLocalStorageItem(key, list);
}
function storageRemoveFromSet([key, value]) {
log('storageRemoveFromSet', key, value);
const list = getLocalStorageItem(key);
if (!Array.isArray(list)) {
log('storageRemoveFromSet [aborting; not a list]', key, value, list);
return;
}
// Filter based on JSON strings in to ensure equality-by-value instead of equality-by-reference
const jsonValue = JSON.stringify(value);
const updatedSet = list.filter(item => jsonValue !== JSON.stringify(item));
setLocalStorageItem(key, updatedSet);
}
}
|
javascript
|
{
"resource": ""
}
|
q60284
|
run
|
validation
|
function run (options) {
if (options.results) {
return map(options);
}
return fetch(options).then(map.bind(null, options));
}
|
javascript
|
{
"resource": ""
}
|
q60285
|
fetch
|
validation
|
function fetch (options) {
var time, promise, resolve, reject;
time = new Date();
promise = new Promise(function (r1, r2) { resolve = r1; reject = r2; } );
try {
options = normalise(options);
if (options.resultIds) {
wpt.getResults(options, options.resultIds).then(after);
} else {
wpt.runTests(options).then(wpt.getResults.bind(null, options)).then(after);
}
} catch (error) {
reject(error);
}
return promise;
function after (results) {
results = {
data: results,
options: options,
times: {
begin: time,
end: new Date()
}
};
if (options.dump) {
dump(options, results);
}
resolve(results);
}
}
|
javascript
|
{
"resource": ""
}
|
q60286
|
map
|
validation
|
function map (options, results) {
var promise, resolve, reject;
promise = new Promise(function (r1, r2) { resolve = r1; reject = r2; } );
try {
// Song and dance to ensure that map options match fetch options.
results = results || get.results(options);
results.options.log = get.log(options);
results.options.mapper = get.mapper(options);
options = results.options;
resolve(options.mapper.map(options, results));
} catch (error) {
reject(error);
}
return promise;
}
|
javascript
|
{
"resource": ""
}
|
q60287
|
onMessage
|
validation
|
function onMessage(msg, rinfo) {
// if the message starts with the bytes "0x23, 0x02" (i.e. a Z/IP packet) then accept this as our gateway
// TODO: consider checking the sequence number in this packet, to make sure it matches the packet we sent
if (msg.length >= 15 && msg[0] === 0x23 && msg[1] === 0x02 && msg[14] === thisObject.findGatewaySequenceNumber && rinfo.family === "IPv4") {
gatewayFound = true;
resolve(rinfo.address);
}
}
|
javascript
|
{
"resource": ""
}
|
q60288
|
validation
|
function(o) {
function CreatedObject(){}
CreatedObject.prototype = o;
var tmp = new CreatedObject();
tmp.__proto__ = o;
return tmp;
}
|
javascript
|
{
"resource": ""
}
|
|
q60289
|
toRingClass
|
validation
|
function toRingClass(claz) {
if (claz.__classId__)
return;
var proto = ! Object.getOwnPropertyNames ? claz.prototype : (function() {
var keys = {};
(function crawl(p) {
if (p === Object.prototype)
return;
_.extend(keys, _.chain(Object.getOwnPropertyNames(p))
.map(function(el) {return [el, true];})
.fromPairs().value());
crawl(Object.getPrototypeOf(p));
})(claz.prototype);
return _.fromPairs(_.map(_.keys(keys), function(k) {return [k, claz.prototype[k]];}));
})();
proto = _.chain(proto).map(function(v, k) { return [k, v]; })
.filter(function(el) {return el[0] !== "constructor" && el[0] !== "__proto__";})
.fromPairs().value();
var id = classCounter++;
_.extend(claz, {
__mro__: [claz, ring.Object],
__properties__: _.extend({}, proto, {
__ringConstructor__: function() {
this.$super.apply(this, arguments);
var tmp = this.$super;
this.$super = null;
try {
claz.apply(this, arguments);
} finally {
this.$super = tmp;
}
}
}),
__classId__: id,
__parents__: [ring.Object],
__classIndex__: {"1": ring.Object},
__ringConvertedObject__: true
});
claz.__classIndex__[id] = claz;
}
|
javascript
|
{
"resource": ""
}
|
q60290
|
ensureNameForm
|
validation
|
function ensureNameForm(name, i) {
var pos = i || 0; // just to be clear
if (!utils.isArray(name.data.nameForms)) {
name.data.nameForms = [];
}
while (pos >= name.data.nameForms.length) {
name.data.nameForms.push({});
}
return name.data.nameForms[pos];
}
|
javascript
|
{
"resource": ""
}
|
q60291
|
validation
|
function(client){
this.settings = client.settings;
this.client = client;
this.accessTokenInactiveTimer = null;
this.accessTokenCreationTimer = null;
}
|
javascript
|
{
"resource": ""
}
|
|
q60292
|
validation
|
function (object) {
var parts = [];
for (var param in object) {
if (object.hasOwnProperty(param)) {
parts.push(encodeURIComponent(param) + '=' + encodeURIComponent(object[param]));
}
}
return parts.join('&');
}
|
javascript
|
{
"resource": ""
}
|
|
q60293
|
validation
|
function (queryString) {
var pairs = queryString.split('&');
var params = {};
pairs.forEach(function(pair) {
pair = pair.split('=');
params[pair[0]] = decodeURIComponent(pair[1] || '');
});
return params;
}
|
javascript
|
{
"resource": ""
}
|
|
q60294
|
templateMatches
|
validation
|
function templateMatches(template, obj) {
for (var key in template) {
if (template.hasOwnProperty(key) && obj[key] !== template[key]) {
return false;
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q60295
|
liftFeedbackLoop
|
validation
|
function liftFeedbackLoop(loops, mappings) {
return function (outerState, scheduler) {
var embededLoops = loops.map(function (loop) {
return loop(outerState.pipe(map_1.map(mappings.mapState)), scheduler)
.pipe(map_1.map(mappings.mapEvent));
});
return rx.merge.apply(rx, embededLoops);
};
}
|
javascript
|
{
"resource": ""
}
|
q60296
|
system
|
validation
|
function system(initialState, reduce, feedback) {
return rx.defer(function () {
var state = new rx.ReplaySubject(1);
var scheduler = rx.queueScheduler;
var events = feedback.map(function (x) { return x(state, scheduler); });
var mergedEvent = rx.merge.apply(rx, events).pipe(observeOn_1.observeOn(scheduler));
var eventsWithEffects = mergedEvent
.pipe(scan_1.scan(reduce, initialState), tap_1.tap(function (x) {
state.next(x);
}), subscribeOn_1.subscribeOn(scheduler), startWith_1.startWith(initialState), observeOn_1.observeOn(scheduler));
var hackOnSubscribed = rx.defer(function () {
state.next(initialState);
return rx.empty();
});
return rx.merge.apply(rx, [eventsWithEffects, hackOnSubscribed]).pipe(catchError_1.catchError(function (e) {
dispatchError(e);
return rx.throwError(e);
}));
});
}
|
javascript
|
{
"resource": ""
}
|
q60297
|
materializedRetryStrategy
|
validation
|
function materializedRetryStrategy(strategy) {
return function (source) {
switch (strategy.kind) {
case "ignoreErrorJustComplete":
return source.pipe(catchError_1.catchError(function (e) {
dispatchError(e);
return rx.empty();
}));
case "ignoreErrorAndReturn":
return source.pipe(catchError_1.catchError(function (e) {
dispatchError(e);
return rx.of(strategy.value);
}));
case "exponentialBackoff":
return rx.defer(function () {
var counter = 1;
return source.pipe(tap_1.tap(function () {
counter = 1;
}, function () {
if (counter * 2 <= strategy.maxBackoffFactor) {
counter *= 2;
}
}), retryWhen_1.retryWhen(function (e) {
return e.pipe(switchMap_1.switchMap(function (x) {
dispatchError(x);
return rx.of(0).pipe(delay_1.delay(strategy.initialTimeout * counter * 1000));
}));
}));
});
case "catchError":
return source.pipe(catchError_1.catchError(function (e) {
dispatchError(e);
return rx.of(strategy.handle(e));
}));
default:
return js_extensions_1.unhandledCase(strategy);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q60298
|
getElementServices
|
validation
|
function getElementServices (app, name) {
let forecasts = app.get('forecasts')
if (name) {
forecasts = forecasts.filter(forecast => forecast.name === name)
}
// Iterate over configured forecast models
let services = []
for (let forecast of forecasts) {
for (let element of forecast.elements) {
let service = app.getService(forecast.name + '/' + element.name)
if (service) {
services.push(service)
}
}
}
return services
}
|
javascript
|
{
"resource": ""
}
|
q60299
|
fatalError
|
validation
|
function fatalError(stderr) {
return {
errors: [{
message: [{
path: '',
code: 0,
line: 0,
start: 0,
descr: stderr
}]
}]
};
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.