_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q9400
|
rangeBox
|
train
|
function rangeBox(selection, label) {
selection
.classed('form-row', true)
.classed('form-group', true)
.classed('align-items-center', true)
.append('div')
.classed('col-form-label', true)
.classed('col-form-label-sm', true)
.text(label);
const minBox = selection.append('div');
minBox.append('label').text('min');
minBox.append('input').classed('min', true);
const maxBox = selection.append('div');
maxBox.append('label').text('max');
maxBox.append('input').classed('max', true);
selection.selectAll('div')
.classed('form-group', true)
.classed('col-4', true)
.classed('mb-0', true);
selection.selectAll('label')
.classed('col-form-label', true)
.classed('col-form-label-sm', true)
.classed('py-0', true);
selection.selectAll('input')
.classed('form-control', true)
.classed('form-control-sm', true)
.attr('type', 'number');
selection.append('div')
.classed('col-4', true);
selection.append('div')
.call(badge.invalidFeedback)
.classed('col-8', true);
}
|
javascript
|
{
"resource": ""
}
|
q9401
|
getMarketCaps
|
train
|
function getMarketCaps() {
return new Promise(function (resolve, reject) {
scraper
.get(urlMarketCap)
.then(function(tableData) {
const coinmarketcapTable = tableData[0];
resolve(getAllMarketCaps(coinmarketcapTable));
});
});
}
|
javascript
|
{
"resource": ""
}
|
q9402
|
formatResults
|
train
|
function formatResults (results) {
return results.map(function (r) {
return {
fullName: r.fullName,
hz: r.hz,
hzDeviation: r.hzDeviation
}
})
}
|
javascript
|
{
"resource": ""
}
|
q9403
|
formatOutput
|
train
|
function formatOutput (results) {
var date = new Date()
var commit
try {
commit = execSync('git rev-parse HEAD').toString().replace('\n', '')
} catch (e) {
commit = 'commit hash not found'
}
return {
meta: {
title: 'example benchmark',
version: pkg.version,
commit: commit,
date: [
date.toLocaleDateString(),
date.toLocaleTimeString(),
date.toString().match(/\(([A-Za-z\s].*)\)/)[1]
].join(' ')
},
results: results
}
}
|
javascript
|
{
"resource": ""
}
|
q9404
|
getConversationId
|
train
|
function getConversationId(req, res, options) {
var cookieName = options.conversationIdCookieName;
var headerName = options.conversationIdHeader;
var conversationId = req.headers[headerName] || req.cookies && req.cookies[cookieName];
if (!conversationId) {
conversationId = uuid.v1();
}
req.conversationId = conversationId;
res.cookie(cookieName, conversationId, { path: '/' });
return conversationId;
}
|
javascript
|
{
"resource": ""
}
|
q9405
|
makeCallback
|
train
|
function makeCallback(entryCaller, entryStack, shadow = false) {
/**
* This callback should be called when an asynchronous error occurred.
* @param {(string|Error)} messageOrError A message string or an _Error_ object at the point of actual error.
* @returns {Error} An error with the updated stack which includes the callee.
*/
function cb(messageOrError) {
const caller = getCallerFromArguments(arguments)
const { stack: errorStack } = new Error()
const calleeStackLine = getCalleeStackLine(errorStack)
const isError = messageOrError instanceof Error
const message = isError ? messageOrError.message : messageOrError
const stackHeading = getStackHeading(message)
const entryHasCallee = caller !== null && entryCaller === caller
const stackMessage = [
stackHeading,
...(entryHasCallee || shadow ? [entryStack] : [
calleeStackLine,
entryStack,
]),
].join('\n')
const stack = cleanStack(stackMessage)
const properties = { message, stack }
const e = isError ? messageOrError : new Error()
return /** @type {Error} */ (Object.assign(/** @type {!Object} */ (e), properties))
}
return cb
}
|
javascript
|
{
"resource": ""
}
|
q9406
|
train
|
function(duration, easing) {
var newStylesheet = localnwt.node.create('<style type="text/css"></style>');
easing = easing || 'ease-in';
duration = duration || 1;
var trail = ' ' + duration + 's ' + easing,
// Just support all browsers for now
cssTransitionProperties = {
'-webkit-transition': 'all' + trail,
'-moz-transition': ' all' + trail,
'-o-ransition': ' all' + trail,
'ms-transition': ' all' + trail,
'transition': ' all' + trail
},
newContent = '';
for (i in cssTransitionProperties) {
newContent += i + ': ' + cssTransitionProperties[i] + ';';
}
newStylesheet.setHtml('.' + this.animClass + '{' + newContent + '}');
localnwt.one('head').append(newStylesheet);
setTimeout(function(){
newStylesheet.remove()
},
duration*1001)
}
|
javascript
|
{
"resource": ""
}
|
|
q9407
|
train
|
function(node, styles, duration, easing) {
animation.init(duration, easing);
node.fire('anim:start', [styles, duration, easing])
setTimeout(function(){
node.fire('anim:done', [styles, duration, easing])
}, duration*1000)
// Need to be sure to implement the transition function first
node.addClass(animation.animClass);
node.setStyles(styles);
return node;
}
|
javascript
|
{
"resource": ""
}
|
|
q9408
|
NWTEventInstance
|
train
|
function NWTEventInstance (e, attrs) {
this._e = e;
this.target = new NWTNodeInstance(e.target);
for (var i in attrs) {
this[i] = attrs[i];
}
}
|
javascript
|
{
"resource": ""
}
|
q9409
|
train
|
function(attribute, pattern, callback, interaction, maxDepth) {
var classPattern = new RegExp(pattern),
interaction = interaction || 'click',
maxSearch,
dispatcher,
body = localnwt.one('body');
// Currently only search one level for a mouse listener for performance reasons
if (interaction == 'click') {
maxSearch = 100;
} else {
maxSearch = maxDepth || 1;
}
dispatcher =
function(e) {
var originalTarget = e.target,
target = originalTarget,
// Did we find it?
found = true,
// Keep track of how many times we bubble up
depthSearched = 0;
while(target._node && target._node.parentNode) {
if (target._node == localnwt.one('body')._node || depthSearched >= maxSearch) { break; }
if (target.hasAttribute(attribute)) {
var matches = target.getAttribute(attribute).match(pattern);
if (matches) {
callback(originalTarget, target, matches);
// If we found a callback, we usually want to stop the event
// Except for input elements (still want checkboxes to check and stuff)
if( target.get('nodeName').toUpperCase() !== "INPUT") {
e.stop();
}
break;
}
}
depthSearched++;
target = target.parent();
};
return;
};
var enableListener = function() {
body.on(interaction, dispatcher);
};
enableListener();
if (interaction !== 'click') {
// Disable mouseover listeners on scroll
var timer = false;
localnwt.one(document).on('scroll', function() {
body.off(interaction, dispatcher);
if (timer) {
clearTimeout(timer);
timer = false;
}
timer = setTimeout(enableListener, 75);
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9410
|
train
|
function (implementOn, event, callback) {
var stringy = callback.toString();
if (this._cached[stringy]) {
// Iteratre through the cached callbacks and remove the correct one based on reference
for(var i=0,numCbs=this._cached[stringy].length; i < numCbs; i++) {
if (this._cached[stringy][i].raw === callback) {
implementOn.removeEventListener(event, this._cached[stringy][i].fn);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9411
|
getExpressionValue
|
train
|
function getExpressionValue (varName, scssExpression) {
if (is.undef(scssExpression) || is.args.empty(arguments)) {
message('Error: Missing arguments');
return undefined;
}
if (!is.string(varName) || !is.string(scssExpression)) {
message('Error: Check arguments type');
return undefined;
}
if (!~scssExpression.indexOf('$')) {
message('Warning: Check scssExpression to contain valid code')
}
// print the interpolated value in comment string
// /*#{$varName}*/ --> /*varValue*/
const scssContent = `${scssExpression}/*#{$${varName}}*/`;
const sassResult = sass.renderSync({
data: scssContent
});
const cssResult = sassResult.css.toString();
return extractExpressionValue(cssResult);
}
|
javascript
|
{
"resource": ""
}
|
q9412
|
extractExpressionValue
|
train
|
function extractExpressionValue (css) {
// parse the comment string:
// /*varValue*/ --> varValue
const valueRegExp = /(?:\/\*)(.+)(?:\*\/)/;
const value = css.match(valueRegExp)[1];
if (!value) {
message('Warning: empty value');
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q9413
|
getRegion
|
train
|
function getRegion() {
const awsRegion = trim(process.env.AWS_REGION);
return awsRegion !== "undefined" && awsRegion !== "null" ? awsRegion : undefined;
}
|
javascript
|
{
"resource": ""
}
|
q9414
|
configureRegion
|
train
|
function configureRegion(context) {
// Resolve the AWS region, if it is not already defined on the context
if (!context.region) {
context.region = getRegion();
}
const msg = `Using region (${process.env.AWS_REGION}) & context.region (${context.region})`;
context.debug ? context.debug(msg) : console.log(msg);
return context;
}
|
javascript
|
{
"resource": ""
}
|
q9415
|
getOrSetRegionKey
|
train
|
function getOrSetRegionKey(region) {
const regionName = region ? region : getRegion();
let regionKey = regionKeysByRegion.get(regionName);
if (!regionKey) {
regionKey = {region: regionName};
regionKeysByRegion.set(regionName, regionKey);
}
return regionKey;
}
|
javascript
|
{
"resource": ""
}
|
q9416
|
transformConfig
|
train
|
function transformConfig (config) {
if (config === null || typeof config !== 'object') {
config = {};
}
if (!Object.keys(config).length) {
return {
options: {},
files: {
ignore: [ignoreNodeModules()]
}
};
}
let runConfig = {
options: {
showMaxStack: 0
}
};
if (config.noDisabling) {
runConfig.options.noDisabling = true;
}
if (config.formatter) {
runConfig.options.formatter = config.formatter;
}
if (config.showMaxStack >= 0) {
runConfig.options.showMaxStack = config.showMaxStack;
}
if (config.outputFile) {
runConfig.options['output-file'] = config.outputFile;
}
if (Array.isArray(config.ignore)) {
runConfig.files = {
ignore: config.ignore.concat(ignoreNodeModules())
};
} else {
runConfig.files = {
ignore: [ignoreNodeModules()]
};
}
return runConfig;
}
|
javascript
|
{
"resource": ""
}
|
q9417
|
lintMethod
|
train
|
function lintMethod (mtd, file, config, cb, configPath) {
let runConfig = transformConfig(config);
if (typeof cb !== 'function') {
cb = function () {};
}
try {
let results = sassLint[mtd](file, runConfig, configPath);
if (mtd !== 'lintFiles') {
if (!Array.isArray(results)) {
results = [results];
}
}
let data = {
results,
errorCount: sassLint.errorCount(results),
warningCount: sassLint.warningCount(results)
};
cb(null, data);
} catch (err) {
cb(err);
}
}
|
javascript
|
{
"resource": ""
}
|
q9418
|
install
|
train
|
function install(destination, prg, callback) {
prompt.start();
prompt.message = ':'.white.bold.bgBlack;
prompt.delimiter = ': '.white.bold.bgBlack;
var schema = {
properties: {
appName: {
description: 'Application name'.white.bold.bgBlack,
pattern: /^[a-zA-Z0-9\s\-]+$/,
message: 'Application name must be only letters, spaces, or dashes',
default: path.basename(destination),
required: true
},
appEmail: {
description: 'Application email address'.white.bold.bgBlack,
conform: validator.isEmail,
message: 'Enter a valid email',
required: true
},
adminName: {
description: 'Administrator username'.white.bold.bgBlack,
conform: validator.isAlphanumeric,
default: 'admin',
message: 'Enter a valid username e.g. admin',
required: true
},
adminPass: {
description: 'Administrator password (at least 6 characters)'.white.bold.bgBlack,
hidden: true,
conform: function (pass) {
return validator.isLength(pass, 6);
},
message: 'Password must have at least 6 characters.',
required: true
},
adminEmail: {
description: 'Administrator email address'.white.bold.bgBlack,
conform: validator.isEmail,
message: 'Enter a valid email',
required: true
},
database: {
description: 'Database URI'.white.bold.bgBlack,
conform: function(uri) {
return validator.isURL(uri, {
protocols: ['mongodb'],
require_protocol: true,
allow_underscores: true
});
},
default: 'mongodb://localhost/' + path.basename(destination),
message: 'Enter a valid URI for your database e.g. mongodb://localhost/chokoapp',
required: true
}
}
};
prompt.get(schema, function (error, result) {
if (error) {
return console.log('\nInstall aborted, no changes were made.');
}
doInstall({
application: {
name: result.appName,
email: result.appEmail
},
database: result.database,
sessionSecret: crypto.randomBytes(32).toString('base64')
}, destination);
var app = new Application(destination);
app.start(prg.port, function(error, app) {
if (error) {
throw error;
}
createAdminUser(app, result, function(error, newAccount, errors) {
// @todo: handle errors.
util.log('Navigate to http://localhost:' + prg.port + ' to start building your new application.');
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q9419
|
doInstall
|
train
|
function doInstall(settings, destination) {
// Create application directories if they don't exist.
var folders = [
destination,
path.join(destination, '/public'),
path.join(destination, '/extensions')
];
folders.forEach(function(folder) {
if (!fs.existsSync(folder)) {
fs.mkdirSync(folder);
}
});
// Create settings.json.
fs.writeFileSync(path.join(destination, 'settings.json'), JSON.stringify(settings, null, ' '), {flag: 'w'});
}
|
javascript
|
{
"resource": ""
}
|
q9420
|
createAdminUser
|
train
|
function createAdminUser(app, result, callback) {
// Create the admin user.
var User = app.type('user');
var userData = {
username: result.adminName,
password: result.adminPass,
email: result.adminEmail,
roles: ['administrator']
};
User.validateAndSave(userData, callback);
}
|
javascript
|
{
"resource": ""
}
|
q9421
|
train
|
function () {
// Allow using a function or an object
var events = _.result(this, 'dispatcherEvents');
if (_.isUndefined(events) || _.isEmpty(events)) {
// Bug out early if no dispatcherEvents
return;
}
var registrations = {};
_.each(events, function (funcOrName, actionType) {
// Quick sanity check for whether there is a problem with the function/name passed
if (!(_.isFunction(funcOrName) || _.isFunction(this[funcOrName]))) {
console.warn('dispatcherEvent: "' + funcOrName + '" is not a function');
return;
}
if (_.isFunction(funcOrName)) {
registrations[actionType] = funcOrName;
} else {
registrations[actionType] = this[funcOrName];
}
}.bind(this));
this.dispatcherToken = dispatcher.register(registrations, this);
}
|
javascript
|
{
"resource": ""
}
|
|
q9422
|
getActions
|
train
|
function getActions( state, resource ) {
var list = state.actionList[ resource.name ] = [];
_.each( resource.actions, function( action, actionName ) {
list.push( [ resource.name, actionName ].join( '.' ) );
} );
}
|
javascript
|
{
"resource": ""
}
|
q9423
|
getArguments
|
train
|
function getArguments( fn ) {
return _.isFunction( fn ) ? trim( /[(]([^)]*)[)]/.exec( fn.toString() )[ 1 ].split( ',' ) ) : [];
}
|
javascript
|
{
"resource": ""
}
|
q9424
|
loadAll
|
train
|
function loadAll( state, resourcePath ) {
var loadActions = [ loadResources( state, resourcePath ) ] || [];
if ( state.config.modules ) {
_.each( state.config.modules, function( mod ) {
var modPath;
if ( /[\/]/.test( mod ) ) {
modPath = require.resolve( path.resolve( process.cwd(), mod ) );
} else {
modPath = require.resolve( mod );
}
loadActions.push( loadModule( state, modPath ) );
} );
}
loadActions.push( loadModule( state, './ahResource' ) );
return when.all( loadActions );
}
|
javascript
|
{
"resource": ""
}
|
q9425
|
loadModule
|
train
|
function loadModule( state, resourcePath ) {
try {
var key = path.resolve( resourcePath );
delete require.cache[ key ];
var modFn = require( resourcePath );
var args = getArguments( modFn );
args.shift();
if ( args.length ) {
return state.fount.resolve( args )
.then( function( deps ) {
var argList = _.map( args, function( arg ) {
return deps[ arg ];
} );
argList.unshift( state.host );
var mod = modFn.apply( modFn, argList );
attachPath( state, mod, resourcePath );
return mod;
} );
} else {
var mod = modFn( state.host );
attachPath( state, mod, resourcePath );
return when( mod );
}
} catch ( err ) {
console.error( 'Error loading resource module at %s with: %s', resourcePath, err.stack );
return when( [] );
}
}
|
javascript
|
{
"resource": ""
}
|
q9426
|
loadResources
|
train
|
function loadResources( state, filePath ) {
var resourcePath = path.resolve( process.cwd(), filePath );
return getResources( resourcePath )
.then( function( list ) {
return when.all( _.map( _.filter( list ), loadModule.bind( undefined, state ) ) )
.then( function( lists ) {
return _.flatten( lists );
} );
} );
}
|
javascript
|
{
"resource": ""
}
|
q9427
|
train
|
function(other) {
var me = this.region(),
you = other.region();
return !(
me.left > you.right ||
me.right < you.left ||
me.top > you.bottom ||
me.bottom < you.top ||
you.left > me.right ||
you.right < me.left ||
you.top > me.bottom ||
you.bottom < me.top
);
}
|
javascript
|
{
"resource": ""
}
|
|
q9428
|
train
|
function(selector) {
var allMatches = localnwt.all(selector),
testNode = this._node,
ancestor = null,
maxDepth = 0;
if( allMatches.size() == 0 ) {
return null;
}
while( true ) {
// Iterate through all matches for each parent, and exit as soon as we have a match
// Pretty bad performance, but super small. TODO: Omtimize
allMatches.each(function (el) {
if (el._node == testNode) {
ancestor = el;
}
});
var parentNode = testNode.parentNode;
if( ancestor || !parentNode) { break; }
testNode = parentNode;
}
if( ancestor ) {
return ancestor;
} else {
return null;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9429
|
train
|
function(property) {
if( property === 'parentNode' ) {
var node = this._node[property];
if( !node ) { return null; }
return new NWTNodeInstance(node);
}
return this._node[property];
}
|
javascript
|
{
"resource": ""
}
|
|
q9430
|
train
|
function(property) {
if( !this.getAttribute('style') ) {
return '';
}
property = this._jsStyle(property);
var matchedStyle = this._node.style[property];
if( matchedStyle ) {
return matchedStyle;
} else {
return null;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9431
|
train
|
function(props) {
// Default properties to an array
if (typeof props == 'string') {
props = [props];
}
var i,
propsLen = props.length;
for (i = 0; i < propsLen; i += 1) {
this._node.style[props[i]] = '';
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9432
|
train
|
function(newStyles) {
if( !this.getAttribute('style') ) {
this.setAttribute('style', '');
}
var newStyle = '',
// If the style matches one of the following, and we pass in an integer, default the unit
// E.g., 10 becomes 10px
defaultToUnit = {
top: 'px',
left: 'px',
width: 'px',
height: 'px'
},
i,
eachStyleValue,
// Keep track of an array of styles that we need to remove
newStyleKeys = [];
for( i in newStyles ) {
var styleKey = this._jsStyle(i),
eachStyleVal = newStyles[i];
// Default the unit if necessary
if (defaultToUnit[styleKey] && !isNaN(eachStyleVal)) {
eachStyleVal += defaultToUnit[styleKey];
}
this._node.style[styleKey] = eachStyleVal;
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9433
|
train
|
function() {
var retVal = '',
// Getting ALL elements inside of form element
els = this._node.getElementsByTagName('*');
// Looping through all elements inside of form and checking to see if they're "form elements"
for( var i = 0, el; el = els[i]; i++ ) {
if( !el.disabled && el.name && el.name.length > 0 ) {
switch(el.tagName.toLowerCase()) {
case 'input':
switch( el.type ) {
// Note we SKIP Buttons and Submits since there are no reasons as to why we
// should submit those anyway
case 'checkbox':
case 'radio':
if( el.checked ) {
if( retVal.length > 0 ) {
retVal += '&';
}
retVal += el.name + '=' + encodeURIComponent(el.value);
}
break;
case 'hidden':
case 'password':
case 'text':
if( retVal.length > 0 ) {
retVal += '&';
}
retVal += el.name + '=' + encodeURIComponent(el.value);
break;
}
break;
case 'select':
case 'textarea':
if( retVal.length > 0 ) {
retVal += '&';
}
retVal += el.name + '=' + encodeURIComponent(el.value);
break;
}
}
}
return retVal;
}
|
javascript
|
{
"resource": ""
}
|
|
q9434
|
train
|
function(method, criteria) {
// Iterate on the raw node
var node = this._node,
// Method to iterate on
siblingType = method + 'Sibling',
// Filter to test the node
filter,
validItems;
// CSS Selector case
if (typeof criteria == "string") {
validItems = n.all(criteria);
filter = function(rawNode) {
var found = false;
validItems.each(function(el){
if (rawNode == el._node) {
found = true;
}
});
return found;
};
// Default the filter to return true
} else if (!criteria) {
filter = function(){ return true }
} else {
filter = function(rawEl) {
return criteria(new NWTNodeInstance(rawEl));
}
}
while(node) {
node = node[siblingType];
if (node && node.nodeType == 1 && filter(node)) {
break;
}
}
return node ? new NWTNodeInstance(node) : null;
}
|
javascript
|
{
"resource": ""
}
|
|
q9435
|
train
|
function(node) {
var newParent = ( node instanceof NWTNodeInstance ) ? node : localnwt.one(node);
newParent.append(this);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9436
|
train
|
function(node) {
if( node instanceof NWTNodeInstance ) {
node = node._node;
}
var child = this.one('*');
this._node.insertBefore(node, (child._node? child._node : null));
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9437
|
train
|
function(node, position) {
var newParent = ( node instanceof NWTNodeInstance ) ? node : localnwt.one(node);
newParent.insert(this, position);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9438
|
train
|
function(node, position) {
position = position || 'before';
if( position == 'before' ) {
this._node.parentNode.insertBefore(node._node, this._node);
} else if ( position == 'after' ) {
this._node.parentNode.insertBefore(node._node, this.next() ? this.next()._node : null);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9439
|
train
|
function(event, fn, selector, context) {
return localnwt.event.on(this, event, fn, selector,context);
}
|
javascript
|
{
"resource": ""
}
|
|
q9440
|
train
|
function(type, callback, recurse) {
var evt = localnwt.event;
for (var i in evt._cached) {
for(var j=0,numCbs=evt._cached[i].length; j < numCbs; j++) {
var thisEvt = evt._cached[i][j];
if (this._node == thisEvt.obj._node && (!type || type == thisEvt.type)) {
evt.off(thisEvt.obj, thisEvt.type, thisEvt.raw)
}
}
}
if (recurse) {
this.all('*').each(function(el){
el.purge(type, callback, recurse);
})
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9441
|
train
|
function(styles, duration, easing, pushState) {
if (!pushState) {
var styleAttrs = [],
defaultStyles,
animHistory,
i
for (i in styles) {
styleAttrs.push(i)
}
defaultStyles = this.computeCss(styleAttrs)
animHistory = {
from: [defaultStyles, duration, easing, true /* This makes it so we do not push this again */],
to: [styles, duration, easing]
}
fxObj[this.uuid()] = animHistory
this.fire('anim:push', animHistory)
}
return localnwt.anim(this, styles, duration, easing);
}
|
javascript
|
{
"resource": ""
}
|
|
q9442
|
train
|
function(plugin, config) {
config = config || {};
config.node = this;
return localnwt.plugin(plugin, config);
}
|
javascript
|
{
"resource": ""
}
|
|
q9443
|
getArnComponent
|
train
|
function getArnComponent(arn, index) {
const components = isNotBlank(arn) ? trim(arn).split(':') : [];
return components.length > index ? trimOrEmpty(components[index]) : '';
}
|
javascript
|
{
"resource": ""
}
|
q9444
|
getKinesisShardIdFromEventID
|
train
|
function getKinesisShardIdFromEventID(eventID) {
if (eventID) {
const sepPos = eventID.indexOf(':');
return sepPos !== -1 ? eventID.substring(0, sepPos) : '';
}
return '';
}
|
javascript
|
{
"resource": ""
}
|
q9445
|
getKinesisShardIdAndEventNoFromEventID
|
train
|
function getKinesisShardIdAndEventNoFromEventID(eventID) {
if (eventID) {
const sepPos = eventID.indexOf(':');
return sepPos !== -1 ?
[eventID.substring(0, sepPos), eventID.substring(sepPos + 1),] : ['', ''];
}
return ['', ''];
}
|
javascript
|
{
"resource": ""
}
|
q9446
|
getKinesisSequenceNumber
|
train
|
function getKinesisSequenceNumber(record) {
return record && record.kinesis && record.kinesis.sequenceNumber ? record.kinesis.sequenceNumber : '';
}
|
javascript
|
{
"resource": ""
}
|
q9447
|
getDynamoDBSequenceNumber
|
train
|
function getDynamoDBSequenceNumber(record) {
return record && record.dynamodb && record.dynamodb.SequenceNumber ? record.dynamodb.SequenceNumber : '';
}
|
javascript
|
{
"resource": ""
}
|
q9448
|
_validateKinesisStreamEventRecord
|
train
|
function _validateKinesisStreamEventRecord(record) {
if (!record.kinesis) {
throw new Error(`Missing kinesis property for Kinesis stream event record (${record.eventID})`);
}
if (!record.kinesis.data) {
throw new Error(`Missing data property for Kinesis stream event record (${record.eventID})`);
}
if (!record.kinesis.partitionKey) {
throw new Error(`Missing partitionKey property for Kinesis stream event record (${record.eventID})`);
}
if (!record.kinesis.sequenceNumber) {
throw new Error(`Missing sequenceNumber property for Kinesis stream event record (${record.eventID})`);
}
}
|
javascript
|
{
"resource": ""
}
|
q9449
|
isDynamoDBEventNameValid
|
train
|
function isDynamoDBEventNameValid(recordOrEventName) {
const eventName = recordOrEventName.eventName ? recordOrEventName.eventName : recordOrEventName;
return eventName === DynamoDBEventName.INSERT || eventName === DynamoDBEventName.MODIFY || eventName === DynamoDBEventName.REMOVE;
}
|
javascript
|
{
"resource": ""
}
|
q9450
|
_validateDynamoDBStreamEventRecord
|
train
|
function _validateDynamoDBStreamEventRecord(record) {
if (!isDynamoDBEventNameValid(record)) {
throw new Error(`Invalid eventName property (${record.eventName}) for DynamoDB stream event record (${record.eventID})`);
}
if (!record.dynamodb) {
throw new Error(`Missing dynamodb property for DynamoDB stream event record (${record.eventID})`);
}
if (!record.dynamodb.Keys) {
throw new Error(`Missing Keys property for DynamoDB stream event record (${record.eventID})`);
}
if (!record.dynamodb.SequenceNumber) {
throw new Error(`Missing SequenceNumber property for DynamoDB stream event record (${record.eventID})`);
}
if (!record.dynamodb.StreamViewType) {
throw new Error(`Missing StreamViewType property for DynamoDB stream event record (${record.eventID})`);
}
switch (record.dynamodb.StreamViewType) {
case 'KEYS_ONLY':
break;
case 'NEW_IMAGE':
if (!record.dynamodb.NewImage && record.eventName !== 'REMOVE') {
throw new Error(`Missing NewImage property for DynamoDB stream event record (${record.eventID})`);
}
break;
case 'OLD_IMAGE':
if (!record.dynamodb.OldImage && record.eventName !== 'INSERT') {
throw new Error(`Missing OldImage property for DynamoDB stream event record (${record.eventID})`);
}
break;
case 'NEW_AND_OLD_IMAGES':
if ((!record.dynamodb.NewImage && record.eventName !== 'REMOVE') || (!record.dynamodb.OldImage && record.eventName !== 'INSERT')) {
throw new Error(`Missing both NewImage and OldImage properties for DynamoDB stream event record (${record.eventID})`);
}
break;
default:
throw new Error(`Unexpected StreamViewType (${record.dynamodb.StreamViewType}) on DynamoDB stream event record (${record.eventID})`);
}
}
|
javascript
|
{
"resource": ""
}
|
q9451
|
createRenderStream
|
train
|
function createRenderStream(params) {
return new Transform({
decodeStrings: params.decodeStrings || false,
highWaterMark: params.highwaterMark || 16384,
transform(svgStr, encoding, cb) {
const renderBuf = Buffer.alloc(params.width * params.height * 4); // ARGB 8-bit per component
addon.renderSVG(svgStr, renderBuf, params)
.then(t => {
renderBuf.timings = t;
cb(null, renderBuf);
})
.catch(cb);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q9452
|
train
|
function (patterns) {
// External restources have to be 1:1 dest to src, both strings
// Check for external first, otherwise expand the pattern
if (!_.isArray(patterns)) {
if (isExternal(patterns)) {
return [patterns];
}
patterns = [patterns];
}
return grunt.file.expand({filter: 'isFile'}, patterns);
}
|
javascript
|
{
"resource": ""
}
|
|
q9453
|
train
|
function(files) {
var regex;
if (options.webroot instanceof RegExp) {
regex = options.webroot;
} else {
regex = new RegExp('^' + options.webroot);
}
_.each(files, function (value, key) {
files[key] = value.replace(regex, '');
});
return files;
}
|
javascript
|
{
"resource": ""
}
|
|
q9454
|
md5
|
train
|
function md5(files) {
var hash = crypto.createHash('md5');
_.each(files, function(file) {
if (!isExternal(file))
hash.update(grunt.file.read(file), 'utf-8');
});
return hash.digest('hex');
}
|
javascript
|
{
"resource": ""
}
|
q9455
|
train
|
function(command, callback) {
command = 'curl https://api.spark.io/v1/devices/' + this.config.deviceId + '/' + command + '?access_token=' + this.config.token;
this.debug('Running command: ', command);
child = exec(command,
function (error, stdout, stderr) {
this.debug('stdout: ' + stdout);
this.debug('stderr: ' + stderr);
if (error !== null) {
this.debug('exec error: ' + error);
}
if (callback) {
try {
callback(JSON.parse(stdout));
}
catch (err) {
callback(undefined);
}
}
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q9456
|
traverse
|
train
|
function traverse(input, strict) {
if (strict === undefined) strict = true;
if (type(input) === 'object') {
return traverseObject(input, strict);
} else if (type(input) === 'array') {
return traverseArray(input, strict);
} else if (isodate.is(input, strict)) {
return isodate.parse(input);
}
return input;
}
|
javascript
|
{
"resource": ""
}
|
q9457
|
traverseObject
|
train
|
function traverseObject(obj, strict) {
Object.keys(obj).forEach(function(key) {
obj[key] = traverse(obj[key], strict);
});
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q9458
|
traverseArray
|
train
|
function traverseArray(arr, strict) {
arr.forEach(function(value, index) {
arr[index] = traverse(value, strict);
});
return arr;
}
|
javascript
|
{
"resource": ""
}
|
q9459
|
standardizeCols
|
train
|
function standardizeCols(columns) {
/**
* Gets the default column name
*/
function getDefaultFormatter(colName) {
return function(o) {
return o[colName];
};
}
/**
* Gets the default column sorter
*/
function getDefaultSorter(colName) {
return function(a, b, dir){
var
firstRec = dir == 'asc' ? a : b,
secondRec = dir == 'asc' ? b : a,
fA = firstRec[colName].toLowerCase(),
fB = secondRec[colName].toLowerCase();
// Handle numbers
if (fA<fB) return -1
if (fA>fB) return +1
return 0
};
}
for (var i in columns) {
var column = columns[i];
if (typeof column == "string") {
column = {name: column};
}
column.dir = column.sortDir || 'asc';
column.formatter = column.formatter || getDefaultFormatter(column.key || column.name);
column.sorter = column.sorter || getDefaultSorter(column.key || column.name);
columns[i] = column;
}
return columns;
}
|
javascript
|
{
"resource": ""
}
|
q9460
|
getDefaultSorter
|
train
|
function getDefaultSorter(colName) {
return function(a, b, dir){
var
firstRec = dir == 'asc' ? a : b,
secondRec = dir == 'asc' ? b : a,
fA = firstRec[colName].toLowerCase(),
fB = secondRec[colName].toLowerCase();
// Handle numbers
if (fA<fB) return -1
if (fA>fB) return +1
return 0
};
}
|
javascript
|
{
"resource": ""
}
|
q9461
|
JSONDataSource
|
train
|
function JSONDataSource(config) {
// Default to the first col ASC for sorting
this.colSortIdx = config.defaultSortCol || -1
this.data = config.data;
this.columns = standardizeCols(config.columns);
}
|
javascript
|
{
"resource": ""
}
|
q9462
|
IODataSource
|
train
|
function IODataSource(config) {
this.columns = standardizeCols(config.columns);
this.io = config.data;
this.node = config.node;
this.fetch = config.fetch || function(io, sort, dir) {
io.post('sort=' + sort + '&dir=' + dir);
}
// Default to the first col ASC for sorting
this.colSortIdx = config.defaultSortCol || -1
}
|
javascript
|
{
"resource": ""
}
|
q9463
|
ElementDataSource
|
train
|
function ElementDataSource(config) {
var newData = [],
newColumns = [];
var headings = config.data.all('tr th');
headings.each(function(th){
newColumns.push(th.getHtml());
});
config.data.all('tr').each(function(tr){
var newRow = {},
populated = false;
for (var i = 0, numCols = headings.size(); i < numCols; i++) {
if (!tr.all('td').item(i)) { continue; }
newRow[headings.item(i).getHtml()] = tr.all('td').item(i).getHtml();
populated = true;
}
if (populated) {
newData.push(newRow);
}
});
config.columns = newColumns;
config.data = newData;
return new JSONDataSource(config);
}
|
javascript
|
{
"resource": ""
}
|
q9464
|
train
|
function(el) {
var mythis = this;
this.source.colSortIdx = el.data('col-idx');
this.source.columns[el.data('col-idx')].dir = this.source.columns[el.data('col-idx')].dir == 'asc' ? 'desc' : 'asc';
this.source.update(function() {
mythis.render();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9465
|
train
|
function() {
var self = this;
// Populate table html
var content = ['<table class="' + this.tableClass + '" data-instance="' + this.instanceCount + '"><thead>',
'<tr>'];
for (var i in this.source.columns) {
var sortContent = this.source.columns[i].name,
colDir = self.source.columns[i].dir;
if (self.source.colSortIdx == i) {
sortContent = self.formatSortHeader(this.source.columns[i].name, colDir)
}
content.push('<th class="col-' + i + '"><a data-col-idx="' + i + '" data-sort="sort" href="#" title="' + this.source.columns[i].name +'">' + sortContent + '</a></th>');
}
content.push('</tr></thead><tbody>');
for (var i = 0, rows = this.source.data.length; i < rows; i++) {
var datum = this.source.data[i];
// Add in a reference to the data
dataLookup[this.instanceCount][i] = datum
content.push('<tr class="row-' + i + '"">');
for (var j in this.source.columns) {
content.push('<td class="col-' + j +'">' + this.source.columns[j].formatter(datum) + '</td>');
}
content.push('</tr>');
}
content.push('</tbody></table>');
this.node.setHtml(content.join(''));
this.node.one('table thead').on('click', function(e) {
if (e.target.data('sort')) {
self.sort(e.target);
self.node.all('th a').item(e.target.data('col-idx'))._node.focus()
e.stop();
}
});
this.node.fire('render')
}
|
javascript
|
{
"resource": ""
}
|
|
q9466
|
train
|
function (el) {
var opts = {}, ii, p,
opts_arr = (el.attr('data-options') || ':').split(';'),
opts_len = opts_arr.length;
function isNumber (o) {
return ! isNaN (o-0) && o !== null && o !== "" && o !== false && o !== true;
}
function trim(str) {
if (typeof str === 'string') return $.trim(str);
return str;
}
// parse options
for (ii = opts_len - 1; ii >= 0; ii--) {
p = opts_arr[ii].split(':');
if (/true/i.test(p[1])) p[1] = true;
if (/false/i.test(p[1])) p[1] = false;
if (isNumber(p[1])) p[1] = parseInt(p[1], 10);
if (p.length === 2 && p[0].length > 0) {
opts[trim(p[0])] = trim(p[1]);
}
}
return opts;
}
|
javascript
|
{
"resource": ""
}
|
|
q9467
|
getAllItems
|
train
|
function getAllItems() {
return new Promise(resolve => {
const res = [];
return instance.pkgs.then(db => {
db.transaction(db.name)
.objectStore(db.name).openCursor()
.onsuccess = event => {
const cursor = event.target.result;
if (cursor) {
res.push(cursor.value);
cursor.continue();
} else {
resolve(res);
}
};
});
});
}
|
javascript
|
{
"resource": ""
}
|
q9468
|
getItem
|
train
|
function getItem(id) {
return new Promise((resolve, reject) => {
return instance.pkgs.then(db => {
const req = db.transaction(db.name)
.objectStore(db.name).get(id);
req.onsuccess = event => resolve(event.target.result);
req.onerror = event => reject(event);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q9469
|
putItem
|
train
|
function putItem(value) {
return new Promise((resolve, reject) => {
return instance.pkgs.then(db => {
const obj = db.transaction(db.name, 'readwrite')
.objectStore(db.name);
const req = obj.put(value);
req.onerror = event => reject(event);
req.onsuccess = () => resolve();
});
});
}
|
javascript
|
{
"resource": ""
}
|
q9470
|
updateItem
|
train
|
function updateItem(id, updater) {
return new Promise((resolve, reject) => {
return instance.pkgs.then(db => {
const obj = db.transaction(db.name, 'readwrite')
.objectStore(db.name);
const req = obj.get(id);
req.onerror = event => reject(event);
req.onsuccess = event => {
const res = event.target.result;
updater(res);
const upd = obj.put(res);
upd.onsuccess = () => resolve();
upd.onerror = event => reject(event);
};
});
});
}
|
javascript
|
{
"resource": ""
}
|
q9471
|
deleteItem
|
train
|
function deleteItem(id) {
return new Promise((resolve, reject) => {
return instance.pkgs.then(db => {
const req = db.transaction(db.name, 'readwrite')
.objectStore(db.name).delete(id);
req.onerror = event => reject(event);
req.onsuccess = () => resolve();
});
});
}
|
javascript
|
{
"resource": ""
}
|
q9472
|
getView
|
train
|
function getView(id, viewID) {
return getItem(id)
.then(pkg => pkg.views.find(e => e.viewID === viewID));
}
|
javascript
|
{
"resource": ""
}
|
q9473
|
appendView
|
train
|
function appendView(id, viewID, viewObj) {
return updateItem(id, item => {
const pos = item.views.findIndex(e => e.viewID === viewID);
item.views.splice(pos + 1, 0, viewObj);
});
}
|
javascript
|
{
"resource": ""
}
|
q9474
|
deleteView
|
train
|
function deleteView(id, viewID) {
return updateItem(id, item => {
const pos = item.views.findIndex(e => e.viewID === viewID);
item.views.splice(pos, 1);
// prune orphaned collections
const bin = {};
item.dataset.forEach(e => { bin[e.collectionID] = 0; });
item.views.forEach(view => {
['rows', 'items', 'nodes', 'edges']
.filter(e => view.hasOwnProperty(e))
.forEach(e => { bin[view[e]] += 1; });
});
Object.entries(bin).forEach(entry => {
if (!entry[1]) {
const i = item.dataset.findIndex(e => e.collectionID === entry[0]);
item.dataset.splice(i, 1);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q9475
|
getAllCollections
|
train
|
function getAllCollections() {
return getAllItems()
.then(items => _.flatten(
items.map(item => {
return item.dataset.map(coll => {
coll.instance = item.id;
return coll;
});
})
));
}
|
javascript
|
{
"resource": ""
}
|
q9476
|
getCollection
|
train
|
function getCollection(id, collID) {
return getItem(id)
.then(pkg => pkg.dataset.find(e => e.collectionID === collID));
}
|
javascript
|
{
"resource": ""
}
|
q9477
|
newNetwork
|
train
|
function newNetwork(instance, nodesID, nodesName, response) {
const viewID = misc.uuidv4().slice(0, 8);
const edgesID = response.workflowID.slice(0, 8);
return updateItem(instance, item => {
item.views.push({
$schema: "https://mojaie.github.io/kiwiii/specs/network_v1.0.json",
viewID: viewID,
name: `${nodesName}_${response.name}`,
viewType: 'network',
nodes: nodesID,
edges: edgesID,
minConnThld: response.query.params.threshold
});
item.dataset.push({
$schema: "https://mojaie.github.io/kiwiii/specs/collection_v1.0.json",
collectionID: edgesID,
name: response.name,
contents: [response]
});
}).then(() => viewID);
}
|
javascript
|
{
"resource": ""
}
|
q9478
|
getAsset
|
train
|
function getAsset(key) {
return new Promise((resolve, reject) => {
return instance.assets.then(db => {
const req = db.transaction(db.name)
.objectStore(db.name).get(key);
req.onsuccess = event => {
const undef = event.target.result === undefined;
const value = undef ? undefined : event.target.result.value;
resolve(value);
};
req.onerror = event => reject(event);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q9479
|
putAsset
|
train
|
function putAsset(key, content) {
return new Promise((resolve, reject) => {
return instance.assets.then(db => {
const obj = db.transaction(db.name, 'readwrite')
.objectStore(db.name);
const req = obj.put({key: key, value: content});
req.onerror = event => reject(event);
req.onsuccess = () => resolve();
});
});
}
|
javascript
|
{
"resource": ""
}
|
q9480
|
updateLegendGroup
|
train
|
function updateLegendGroup(selection, viewBox, orient) {
const widthFactor = 0.2;
const scaleF = viewBox.right * widthFactor / 120;
const o = orient.split('-');
const viewW = viewBox.right;
const viewH = viewBox.bottom;
const legW = viewW * widthFactor;
const legH = legW * 50 / 120;
const posX = {left: legW / 10, right: viewW - legW - (legW / 10)}[o[1]];
const posY = {top: legH / 10, bottom: viewH - legH - (legH / 10)}[o[0]];
selection.attr('transform',
`translate(${posX}, ${posY}) scale(${scaleF})`);
}
|
javascript
|
{
"resource": ""
}
|
q9481
|
loadKeyValueCSV
|
train
|
function loadKeyValueCSV (filename, callback) {
var out = {}
csv()
.from.path(filename, {
delimiter: '\t'
})
.on('record', function (data, index) {
if (data[0].match(/^[\w\d]/)) {
out[data[0]] = data[1]
}
})
.on('end', function (count) {
callback(null, out)
})
.on('error', function (err) {
callback(err)
})
}
|
javascript
|
{
"resource": ""
}
|
q9482
|
loadStructureCSV
|
train
|
function loadStructureCSV (filename, callback) {
var out = {}
csv()
.from.path(filename, {
delimiter: '\t'
})
.transform(function (data) {
// hex values to decimal
if (!data[0].match(/^[0-9A-Fa-f]/)) { return false } // comment
var ret = {
field: parseInt(data[3]),
type: data[2].substr(0, 3)
}
if (ret.type === 'sel') {
if (data[2].length === 3) {
ret.selection = ret.field
} else {
ret.selection = parseInt(data[2].replace(/^sel:/, ''))
}
}
if (data[1].length > 0) {
ret.from = parseInt(data[0], 16)
ret.to = parseInt(data[1], 16)
} else {
ret.where = parseInt(data[0], 16)
}
return ret
})
.on('record', function (data, index) {
if (data) {
var field = data.field
delete data.field
out[field] = data
}
})
.on('end', function (count) {
callback(null, out)
})
.on('error', function (err) {
callback(err)
})
}
|
javascript
|
{
"resource": ""
}
|
q9483
|
initializeClickimages
|
train
|
function initializeClickimages() {
var elements = document.querySelectorAll('[data-pins]');
for(var i = 0; i < elements.length; i++) {
/*
try/catch so it continues with the next element without breaking
out of the loop, when any syntax error occurs.
*/
try {
clickimagePins(elements[i]);
}
catch(err) {
console.error(err);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q9484
|
train
|
function (events, context) {
if (!_.isObject(events)) {
console.warn('Only registration objects can be passed to dispatcher.register()');
return;
}
return this.dispatcher.register(function (payload) {
// Switch statements be damned...
if (events[payload.type]) {
events[payload.type].apply(context || null, [payload.data]);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9485
|
train
|
function (type, data) {
if (!_.isString(type)) {
console.warn('Action types are required when calling dispatcher.dispatch()');
return;
}
this.dispatcher.dispatch({
type: type,
data: data
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9486
|
train
|
function (token) {
var tokens = token;
if (!_.isArray(tokens)) {
tokens = [tokens];
}
tokens = tokens.map(function (token) {
// Allow passing stores straight and we grab the dispatcherToken
return token.dispatcherToken || token;
});
return this.dispatcher.waitFor(tokens);
}
|
javascript
|
{
"resource": ""
}
|
|
q9487
|
_ensureArray
|
train
|
function _ensureArray (model, property) {
const propertyKey = property.getKey();
let array = model.data[propertyKey];
if (!array) {
model.data[propertyKey] = array = [];
ArrayType.flagAsArrayType(array);
}
return array;
}
|
javascript
|
{
"resource": ""
}
|
q9488
|
train
|
function() {
//io = socket(process.env.PORT || process.env.NODE_PORT || 3333);
io = socket(http);
io.on('connection', function(socket){
console.log('connection happened');
//Logic for handeling a new connection here.
//ie. registering a user or something similar.
//The new connection can send commands.
socket.on('keydown', function(data) {
var index = keysToPress.indexOf(data.key);
if(index === -1) {
keysToPress.push(data.key);
}
});
socket.on('keyup', function(data) {
var index = keysToPress.indexOf(data.key);
if(index !== -1) {
keysToPress.splice(index, 1);
}
});
socket.on('restart', function(data) {
gameboy_instance.loadROM(rom);
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9489
|
configureHandlerContext
|
train
|
function configureHandlerContext(createContext, createSettings, createOptions, event, awsContext) {
// Configure the context as a standard context
let context = typeof createContext === 'function' ? createContext() :
createContext && typeof createContext === 'object' ? copy(createContext, deep) : {};
if (!context) context = {};
const settings = typeof createSettings === 'function' ? copy(createSettings(), deep) :
createSettings && typeof createSettings === 'object' ? copy(createSettings, deep) : undefined;
const options = typeof createOptions === 'function' ? copy(createOptions(), deep) :
createOptions && typeof createOptions === 'object' ? copy(createOptions, deep) : undefined;
// Configure the context as a standard context
contexts.configureStandardContext(context, settings, options, event, awsContext, false);
// Merge the handler options into the handler settings and finally merge their result into context.handler
const handlerOptions = (options && options.handler) || {};
const handlerSettings = settings && settings.handler ?
mergeHandlerOpts(handlerOptions, settings.handler) : handlerOptions;
context.handler = context.handler ? mergeHandlerOpts(handlerSettings, context.handler) : handlerSettings;
return context;
}
|
javascript
|
{
"resource": ""
}
|
q9490
|
succeedLambdaCallback
|
train
|
function succeedLambdaCallback(callback, response, event, context) {
return Promises.try(() => {
const handler = context && context.handler;
if (handler && handler.useLambdaProxy) {
const statusCode = response && isNotBlank(response.statusCode) ? response.statusCode : 200;
const body = (response && response.body) || response || {};
const proxyResponse = toLambdaProxyResponse(statusCode, response && response.headers, body, handler.defaultHeaders);
return executePreSuccessCallback(proxyResponse, event, context)
.then(() => callback(null, proxyResponse))
.catch(err => {
console.error(`Unexpected failure after executePreSuccessCallback`, err);
return callback(null, proxyResponse);
});
} else {
return executePreSuccessCallback(response, event, context)
.then(() => callback(null, response))
.catch(err => {
console.error(`Unexpected failure after executePreSuccessCallback`, err);
return callback(null, response);
});
}
}).catch(err => {
console.error(`Unexpected failure during succeedLambdaCallback`, err);
return callback(null, response);
});
}
|
javascript
|
{
"resource": ""
}
|
q9491
|
toLambdaProxyResponse
|
train
|
function toLambdaProxyResponse(statusCode, headers, body, defaultHeaders) {
const proxyResponse = {statusCode: statusCode};
const headersWithDefaults = headers && defaultHeaders ? merge(defaultHeaders, copy(headers)) :
headers || (defaultHeaders && copy(defaultHeaders));
if (headersWithDefaults) {
proxyResponse.headers = headersWithDefaults;
}
proxyResponse.body = isString(body) ? body : stringify(body);
return proxyResponse;
}
|
javascript
|
{
"resource": ""
}
|
q9492
|
toDefaultErrorResponseBody
|
train
|
function toDefaultErrorResponseBody(error) {
const json = error && error.toJSON();
if (json) {
if (json.httpStatus) {
delete json.httpStatus; // don't really need `httpStatus` inside `body` too, since have it in response as `statusCode`
}
if (json.headers) {
delete json.headers; // don't want error's `headers` inside `body`, since have more comprehensive `headers` in response
}
}
return json;
}
|
javascript
|
{
"resource": ""
}
|
q9493
|
train
|
function(expression) {
if (this.hasClipboard()) {
var key = this._getKey();
localStorage[key] = json.stringify(expression.toJson());
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9494
|
train
|
function(expression) {
var pastedExpression = new Expression();
var key = this._getKey();
pastedExpression.fromJson(json.parse(localStorage[key]));
var newExpression;
if (expression) {
var expressionClone = new Expression({
operator : 'and',
expressionList : [expression, pastedExpression]
}).toJson();
//converting the same instance
expression.fromJson(expressionClone);
newExpression = expression;
} else {
newExpression = pastedExpression;
}
var parentBuilder = this.get('filterBuilder');
parentBuilder.set('expression', newExpression, true /* preventChange Undo State
* */);
}
|
javascript
|
{
"resource": ""
}
|
|
q9495
|
getArguments
|
train
|
function getArguments() {
var port = 3000;
var path = '.';
var args = process.argv.slice(2);
while (args.length) {
var arg = args.shift();
switch (arg) {
case '-p':
port = args.shift();
break;
default:
path = arg || path;
}
}
return {
port: port,
path: path
};
}
|
javascript
|
{
"resource": ""
}
|
q9496
|
train
|
function (discount, cb) {
Discount.destroy(discount.id)
.exec(function (err, destroyedDiscounts){
if (err) return cb(err);
if (!destroyedDiscounts) return cb(null, null);
Discount.afterStripeCustomerDiscountDeleted(destroyedDiscounts[0], function(err, discount){
cb(err, discount);
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9497
|
ShimCache
|
train
|
function ShimCache(state, name, options) {
this._callbacks = []
AbstractCache.call(this, state, name, options)
}
|
javascript
|
{
"resource": ""
}
|
q9498
|
train
|
function(when, operation) {
return function(values, callback) {
var callbackName = when + operation;
// Call type callback.
if (callbackName in settings) {
return settings[callbackName](settings, values, function() {
// Invoke hook on all extensions.
application.invoke(callbackName, name, values, callback);
});
}
// Invoke hook on all extensions.
application.invoke(callbackName, name, values, callback);
};
}
|
javascript
|
{
"resource": ""
}
|
|
q9499
|
collectDeclarations
|
train
|
function collectDeclarations (filePath) {
const declarationRegexp = /(?:\$)([\w-]+)(?:[\s\n\r\t])*(?::)(?:[\s\n\r\t])*(.+)(?:[\s\n\r\t])*(?:;)/gm;
const fileSource = fs.readFileSync(filePath, 'utf8');
return fileSource.match(declarationRegexp);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.