_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q42200 | promisify | train | function promisify(original, self = null) {
if (typeof original !== 'function') {
throw new TypeError('original must be a function')
}
/**
* Wrapped original function.
* @typedef {function} wrapper
* @param {...*} args - Arguments to apply to the original function.
* @returns {Promise.<*>} - Promise that gets resolved when the original function calls the callback.
*/
function wrapper(...args) {
let thisArg = self
if (this !== global) {
// called with bound this object
thisArg = this
}
if (typeof args[args.length - 1] === 'function') {
// called with callback
return original.call(thisArg, ...args)
}
// promisified
return new Promise((resolve, reject) => {
/**
* Callback for the original function.
* @typedef {function} cb
* @param {?Error} error - Error if one occured.
* @param {*} result - Result of the original function.
*/
function cb(error, result) {
if (error) {
return reject(error)
}
resolve(result)
}
args.push(cb)
original.call(thisArg, ...args)
})
}
return wrapper
} | javascript | {
"resource": ""
} |
q42201 | generateCardDocument | train | function generateCardDocument(options, callback) {
var DB = require('../index').db,
elementId = Cuid();
// defaults
options = _.defaultsDeep(options, {
directory: '.',
css: true,
js: false,
clientStateSupport: false,
clientProxySupport: false,
clientAnalyticsSupport: false,
viewModel: {
link: options.link,
card: {
id: elementId,
name: options.cardName,
pack: options.packName
}
},
clientLocals: {
title: options.title,
card: {
id: elementId,
key: options.key,
name: options.cardName,
pack: options.packName,
url: options.url
}
}
});
Async.waterfall([
function (cb) {
stylesToString(options, function (css) {
cb(null, css);
});
},
function (css, cb) {
if (options.clientStateSupport || options.clientAnalyticsSupport || options.clientProxySupport) {
// generate a one-time #Do API key.
DB.issueAPIKey(options.key, function (err, apiKey) {
if (apiKey) {
options.clientLocals.card.apiKey = apiKey;
}
cb(null, css);
});
}
else {
cb(null, css);
}
},
function (css, cb) {
jsToString(options, function (js) {
cb(null, css, js);
});
},
function (css, js, cb) {
viewToString(css, js, options, function (html) {
cb(null, html || '');
});
}
],
// done
function (err, html) {
callback && callback(Minify(html, {
collapseWhitespace: true,
removeComments: true,
removeCommentsFromCDATA: true,
removeAttributeQuotes: true,
removeRedundantAttributes: true,
removeEmptyAttributes: true,
minifyJS: process.env.NODE_ENV === 'production',
minifyCSS: process.env.NODE_ENV === 'production'
}));
}
);
} | javascript | {
"resource": ""
} |
q42202 | train | function (packName, cardName, inputValues, callback) {
var DB = require('../index').db;
// Go through the input values and base64 them if they aren't already.
var allBase64 = true;
_.each(_.keys(inputValues), function (key) {
if (!/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/.test(inputValues[key])) {
allBase64 = false;
}
});
// If not all inputs are base64, then we'll convert them for the user (backward compatibility).
if (!allBase64) {
_.each(_.keys(inputValues), function (key) {
inputValues[key] = Base64.encode(inputValues[key]);
});
}
DB.lock(packName, cardName, inputValues, process.env.LOCK_KEY, function (err, token) {
if (!err) {
callback && callback(null, token);
}
else {
callback && callback(err);
}
});
} | javascript | {
"resource": ""
} | |
q42203 | train | function (cb) {
// card key
var url = options.url.replace(/light=true/i, ''),
params = {
legacyCardKey: Utils.getLegacyCardKey(url, process.env.CARD_SECRET),
cardKey: Utils.getCardKey(url, process.env.CARD_SECRET)
};
// extract input values
_.each(_.keys(options.inputValues), function (key) {
params[key] = options.inputValues[key];
});
if (options.inputValues.token) {
// retrieve previously saved parameters. Add or replace params
DB.unlock(options.packName, options.cardName, options.inputValues.token, process.env.LOCK_KEY, function (err, payload) {
if (err) {
// Ignore error and just return the params.
cb(null, params);
}
else {
if (payload && _.isObject(payload)) {
_.each(_.keys(Card.inputs), function (key) {
if (payload[key]) {
params[key] = Base64.decode(payload[key]);
}
});
}
cb(null, params);
}
});
}
else {
cb(null, params);
}
} | javascript | {
"resource": ""
} | |
q42204 | train | function (params, cb) {
// validate input requirements vs what came back in params
var errorMessage = null;
_.forEach(Card.inputs, function (input, key) {
if (input.required && !params[key]) {
if (!errorMessage) {
errorMessage = '';
}
else {
errorMessage += ' | ';
}
errorMessage += 'No value provided for required input: ' + key;
}
});
cb(errorMessage, params);
} | javascript | {
"resource": ""
} | |
q42205 | train | function (err, params) {
if (!err) {
callback && callback(null, params);
}
else {
callback && callback(err.message || err);
}
} | javascript | {
"resource": ""
} | |
q42206 | train | function (params, cb) {
DB.getCardState(params.cardKey, params.legacyCardKey, function (err, state) {
cb(null, params, state);
});
} | javascript | {
"resource": ""
} | |
q42207 | train | function (params, state, cb) {
state = state || {};
if (Card.getCardData) {
Card.getCardData(params, state, function (err, viewModel, clientLocals) {
cb(err, params, state, viewModel, clientLocals);
});
}
else {
cb(null, params, state, null, null);
}
} | javascript | {
"resource": ""
} | |
q42208 | train | function (params, state, viewModel, clientLocals, cb) {
// don't save if nothing came back, just forward the call
if (!_.isEmpty(state)) {
DB.saveCardState(params.cardKey, state, function (err) {
cb(err, params, viewModel, clientLocals);
});
}
else {
cb(null, params, viewModel, clientLocals);
}
} | javascript | {
"resource": ""
} | |
q42209 | train | function (params, viewModel, clientLocals, cb) {
viewModel = viewModel || {};
clientLocals = clientLocals || {};
var generateOptions = {
directory: options.directory,
packName: options.packName,
cardName: options.cardName,
url: options.url,
key: params.cardKey,
title: viewModel.title || '',
link: viewModel.link,
css: params.light !== true,
client$Support: Card.client$Support || false,
clientStateSupport: Card.clientStateSupport || false,
clientProxySupport: Card.clientProxySupport || false,
clientAnalyticsSupport: Card.clientAnalyticsSupport || false,
viewModel: viewModel,
clientLocals: clientLocals
};
generateCardDocument(generateOptions, function (html) {
cb(null, html);
});
} | javascript | {
"resource": ""
} | |
q42210 | train | function (err, html) {
if (!err) {
callback && callback(null, html);
}
else {
console.log('CARD: Error rendering HashDo card ' + options.packName + '-' + options.cardName + '.', err);
callback && callback(err.message || err);
}
} | javascript | {
"resource": ""
} | |
q42211 | train | function (options, callback) {
if (!options) {
throw new Error('You must provide an options object to .');
}
if (!options.packName) {
throw new Error('You must provide a pack name the card belongs to.');
}
if (!options.cardName) {
throw new Error('You must provide a card name of the card to render.');
}
var packPath = Path.join(options.directory, 'hashdo-' + options.packName.replace('hashdo-', '')),
cardFile = Path.join(packPath, options.cardName) + '.js';
// check for card pack
FS.stat(packPath, function (err) {
if (!err) {
// check for card
FS.stat(cardFile, function (err) {
if (!err) {
// Remove card from cache to ease development by reloading from disk each time.
if (process.env.NODE_ENV !== 'production') {
delete require.cache[require.resolve(Path.join(packPath, options.cardName))];
}
var Card = require(Path.join(packPath, options.cardName));
// If this card has a web hook function then let's call it.
if (Card.webHook) {
var DB = require('../index').db;
Card.webHook(options.payload, function (err, urlParams, state) {
if (!err) {
if (state) {
var cardKey = Utils.getCardKey('/' + options.packName + '/' + options.cardName + objectToQueryString(urlParams), process.env.CARD_SECRET),
firebaseUrl = 'card/' + cardKey;
if (Card.clientStateSupport && process.env.FIREBASE_URL) {
Firebase.set(firebaseUrl, state);
}
DB.getCardState(cardKey, null, function (err, currentCardState) {
DB.saveCardState(cardKey, Utils.deepMerge(true, true, currentCardState || {}, state));
});
}
}
callback && callback(null);
});
}
else {
// No web hook function.
callback && callback('Web hook not available.');
}
}
else {
callback && callback('No card found.');
}
});
}
else {
// No card pack.
callback && callback('Pack not found.');
}
});
} | javascript | {
"resource": ""
} | |
q42212 | nextTick | train | function nextTick (next, err) {
return process.nextTick(function () {
try {
next(err)
} catch (e) {
// istanbul ignore next
next(e)
}
})
} | javascript | {
"resource": ""
} |
q42213 | compose | train | function compose () {
// the function required by the server
function middlewareF (req, res, end) {
var index = 0
// inject stats middleware
if (middlewareF.options && middlewareF.options.stats) {
middlewareF.stack = middlewareF.stack.map(function (mw) {
var fn
if (typeof mw === 'object') {
var key = Object.keys(mw)[0]
if (!mw[key].stats) {
fn = {}
fn[key] = middlewareF.options.stats(mw[key])
}
} else {
if (!mw.stats) {
fn = middlewareF.options.stats(mw)
}
}
return fn
})
}
// looping over all middleware functions defined by stack
;(function next (err) {
var arity
var middleware = middlewareF.stack[index++] // obtain the current middleware from the stack
if (!middleware) {
// we are at the end of the stack
end && end(err)
return
} else {
// extract middleware from object
if (typeof (middleware) === 'object') {
var name = Object.keys(middleware)[0]
if (typeof (middleware[name]) === 'function') {
middleware = middleware[name]
} else {
middleware = function (req, res, next) {
next(new Error('missing middleware'))
}
}
}
try {
arity = middleware.length // number of arguments function middleware requires
// handle errors
if (err) {
// If the middleware function contains 4 arguments than this will act as an "error trap"
if (arity === 4) {
middleware(err, req, res, function (err) {
nextTick(next, err)
})
} else {
// otherwise check the next middleware
next(err)
}
} else if (arity < 4) {
// process non "error trap" stack
middleware(req, res, function (err) {
nextTick(next, err)
})
} else {
// loop over "error traps" if no error `err` is set.
next()
}
} catch (e) {
next(e)
}
}
})()
}
middlewareF.stack = []
middlewareF.options = compose.options || {}
;[].slice.call(arguments).forEach(function (a) {
middlewareF.stack = middlewareF.stack.concat(compose.decompose(a))
})
// extends
;[ 'before', 'after', 'replace', 'remove', 'push', 'unshift', 'clone' ].forEach(function (p) {
middlewareF[p] = compose[p]
})
// inject stats middleware
if (compose.options.stats) {
middlewareF.options = {}
middlewareF.options.stats = compose.options.stats
}
return middlewareF
} | javascript | {
"resource": ""
} |
q42214 | middlewareF | train | function middlewareF (req, res, end) {
var index = 0
// inject stats middleware
if (middlewareF.options && middlewareF.options.stats) {
middlewareF.stack = middlewareF.stack.map(function (mw) {
var fn
if (typeof mw === 'object') {
var key = Object.keys(mw)[0]
if (!mw[key].stats) {
fn = {}
fn[key] = middlewareF.options.stats(mw[key])
}
} else {
if (!mw.stats) {
fn = middlewareF.options.stats(mw)
}
}
return fn
})
}
// looping over all middleware functions defined by stack
;(function next (err) {
var arity
var middleware = middlewareF.stack[index++] // obtain the current middleware from the stack
if (!middleware) {
// we are at the end of the stack
end && end(err)
return
} else {
// extract middleware from object
if (typeof (middleware) === 'object') {
var name = Object.keys(middleware)[0]
if (typeof (middleware[name]) === 'function') {
middleware = middleware[name]
} else {
middleware = function (req, res, next) {
next(new Error('missing middleware'))
}
}
}
try {
arity = middleware.length // number of arguments function middleware requires
// handle errors
if (err) {
// If the middleware function contains 4 arguments than this will act as an "error trap"
if (arity === 4) {
middleware(err, req, res, function (err) {
nextTick(next, err)
})
} else {
// otherwise check the next middleware
next(err)
}
} else if (arity < 4) {
// process non "error trap" stack
middleware(req, res, function (err) {
nextTick(next, err)
})
} else {
// loop over "error traps" if no error `err` is set.
next()
}
} catch (e) {
next(e)
}
}
})()
} | javascript | {
"resource": ""
} |
q42215 | _write | train | function _write(dest, source, callback) {
var itemPath = path.join(dest, source.name);
// switch according to type of the current root item
switch(source.type) {
case TYPE_FILE:
if (source.data instanceof stream.Readable) {
// stream data => pipe it to destination stream
source.data.pipe(fs.createWriteStream(itemPath));
source.data.on('end', callback);
return;
}
// write data to the file as a string or a buffer
return fs.writeFile(
itemPath,
(typeof source.data === 'undefined' || source.data === null) ? '' : source.data,
callback
);
case TYPE_FOLDER:
return fs.mkdir(itemPath, _folderWritten.bind(null, itemPath, source, callback));
case TYPE_ALIAS:
return fs.symlink(source.orig, itemPath, callback);
default:
// ignore unknown type
return callback();
}
} | javascript | {
"resource": ""
} |
q42216 | _folderWritten | train | function _folderWritten(dest, source, callback, err) {
if (err) return callback(err);
async.each(source.children, _write.bind(null, dest), callback);
} | javascript | {
"resource": ""
} |
q42217 | _read | train | function _read(stat, source, callback) {
stat(source, _pathStated.bind(null, {}, stat, source, callback));
} | javascript | {
"resource": ""
} |
q42218 | _pathStated | train | function _pathStated(item, stat, stated, callback, err, stats) {
if (err) return callback(err);
item.name = path.basename(stated);
if (stats.isFile()) {
item.type = TYPE_FILE;
// TODO set encoding according to the read file content or user preferences
return fs.readFile(stated, {encoding: 'utf8'}, _fileRead.bind(null, item, callback));
}
if (stats.isDirectory()) {
item.type = TYPE_FOLDER;
return fs.readdir(stated, _folderRead.bind(null, item, stat, stated, callback));
}
if (stats.isSymbolicLink()) {
item.type = TYPE_ALIAS;
return fs.readlink(stated, _aliasRead.bind(null, item, callback));
}
// not supported type
item.type = TYPE_UNKNOWN;
callback(null, item);
} | javascript | {
"resource": ""
} |
q42219 | _fileRead | train | function _fileRead(item, callback, err, data) {
if (err) return callback(err);
item.data = data;
callback(null, item);
} | javascript | {
"resource": ""
} |
q42220 | _folderRead | train | function _folderRead(item, stat, dirpath, callback, err, files) {
if (err) return callback(err);
async.map(
files,
_readChild.bind(null, stat, dirpath),
_childrenRead.bind(null, item, callback)
);
} | javascript | {
"resource": ""
} |
q42221 | _readChild | train | function _readChild(stat, dirpath, name, callback) {
_read(stat, path.join(dirpath, name), callback);
} | javascript | {
"resource": ""
} |
q42222 | _aliasRead | train | function _aliasRead(item, callback, err, orig) {
if (err) return callback(err);
item.orig = orig;
callback(null, item);
} | javascript | {
"resource": ""
} |
q42223 | _store | train | function _store(dest, source, callback) {
fs.writeFile(dest, JSON.stringify(source), callback);
} | javascript | {
"resource": ""
} |
q42224 | _load | train | function _load(source, callback) {
fs.readFile(source, {encoding: 'utf8'}, _jsonLoaded.bind(null, callback));
} | javascript | {
"resource": ""
} |
q42225 | _jsonLoaded | train | function _jsonLoaded(callback, err, data) {
if (err) return callback(err);
var parsed;
try {
parsed = JSON.parse(data);
} catch(jerr) {
return callback(jerr);
}
callback(null, parsed);
} | javascript | {
"resource": ""
} |
q42226 | _load2write | train | function _load2write(dest, source, callback) {
_load(source, _pipe.bind(null, _write.bind(null, dest), callback));
} | javascript | {
"resource": ""
} |
q42227 | _read2store | train | function _read2store(stat, dest, source, callback) {
_read(stat, source, _pipe.bind(null, _store.bind(null, dest), callback));
} | javascript | {
"resource": ""
} |
q42228 | _pipe | train | function _pipe(out, callback, err, iresult) {
if (err) return callback(err);
out(iresult, callback);
} | javascript | {
"resource": ""
} |
q42229 | _handleConvert | train | function _handleConvert(stat, dest, source, callback) {
// "dest" arg is optional
if (typeof source === 'function') {
callback = source;
source = dest;
dest = null;
}
// assert input params
assert.ok(
dest === null || typeof dest === 'string',
'Invalid type of argument "dest", expected "null" or "string", ' +
'but is "' + (typeof dest) + '"'
);
assert.equal(
typeof(callback),
'function',
'Invalid type of argument "callback", expected "function", ' +
'but is "' + (typeof callback) + '"'
);
// perform an action according to "source" and "dest"
switch(typeof source) {
case 'string':
// source is a path
if (_isJsonPath(source)) {
// source is meant to be a json file
if (typeof dest === 'string') {
// destination is meant to be a directory
return _load2write(dest, source, callback);
}
// destination is meant to be a local object
return _load(source, callback);
}
// source is meant to be a directory
if (typeof dest === 'string') {
// destination is meant to be a json file
return _read2store(stat, dest, source, callback);
}
// destination is meant to be a local object
return _read(stat, source, callback);
case 'object':
// source is an object
if (_isJsonPath(dest)) {
// destination is meant to be a json file
return _store(dest, source, callback);
}
// destination is meant to be a directory
return _write(dest, source, callback);
default:
// invalid source
assert.ok(
false,
'Invalid type of argument "source", expected "string" or "object", ' +
'but is "' + (typeof source) + '"'
);
}
} | javascript | {
"resource": ""
} |
q42230 | Entity | train | function Entity(param) {
EventEmitter2.apply(this, arguments);
Entity.prototype.init.apply(this, arguments);
} | javascript | {
"resource": ""
} |
q42231 | validator | train | function validator (data, schema) {
const result = Object.assign({}, data)
Object.keys(schema).map(key => {
let value = schema[key]
const type = typeof value
if (type !== 'object') {
value = {
transform: value
}
}
validate(value, result, key)
})
return result
} | javascript | {
"resource": ""
} |
q42232 | coerce | train | function coerce (type, field, value) {
let result
if (type === 'string') {
result = String(value).trim()
} else if (type === 'number') {
result = Number(value)
if (isNaN(result)) throw new Error(`field ${field} can not be converted to a number`)
} else if (type === 'array') {
result = [].concat(value)
} else if (type === 'date') {
result = Date.parse(value)
if (isNaN(result)) throw new Error(`field ${field} can not be converted into a date`)
} else if (type === 'boolean') {
result = Boolean(value)
} else if (type === 'object') {
if (typeof value !== 'object') throw new Error(`field ${field} is not an object`)
result = value
}
return result
} | javascript | {
"resource": ""
} |
q42233 | SplitLine | train | function SplitLine (options) {
if (!(this instanceof SplitLine)) {
return new SplitLine(options)
}
this.options = options || {}
Transform.call(this, _omit(this.options, ['matcher', 'chomp']))
this.offset = 0
this.options.matcher = (typeof this.options.matcher === 'string'
? this.options.matcher.charCodeAt(0)
: this.options.matcher || 0x0a)
this.options.chomp = (this.options.chomp === true ? 0 : 1) // chomp newline
this.buffer = Buffer.from('') // this.unshift cannot be used if options.highWaterMark is quite low!
// That's why an own buffer is required here :/
return this
} | javascript | {
"resource": ""
} |
q42234 | lookup | train | function lookup(version, migrations) {
var regex = RegExp('^' + version + '.*$');
for (var m in migrations)
if (migrations.hasOwnProperty(m) && m.match(regex)) return m;
return null;
} | javascript | {
"resource": ""
} |
q42235 | relative | train | function relative(path){
var startX = 0
var startY = 0
var x = 0
var y = 0
return path.map(function(seg){
seg = seg.slice()
var type = seg[0]
var command = type.toLowerCase()
// is absolute
if (type != command) {
seg[0] = command
switch (type) {
case 'A':
seg[6] -= x
seg[7] -= y
break
case 'V':
seg[1] -= y
break
case 'H':
seg[1] -= x
break
default:
for (var i = 1; i < seg.length;) {
seg[i++] -= x
seg[i++] -= y
}
}
}
// update cursor state
switch (command) {
case 'z':
x = startX
y = startY
break
case 'h':
x += seg[1]
break
case 'v':
y += seg[1]
break
case 'm':
x += seg[1]
y += seg[2]
startX += seg[1]
startY += seg[2]
break
default:
x += seg[seg.length - 2]
y += seg[seg.length - 1]
}
return seg
})
} | javascript | {
"resource": ""
} |
q42236 | postGetTags | train | function postGetTags(id, cb) {
var q =
'SELECT * FROM tags t ' +
'JOIN posts_tags pt ON t.id = pt.tag_id AND pt.post_id = $1';
db.getClient(function(err, client, done) {
client.query(q, [id], function(err, r) {
if(err) {
cb(err);
done(err);
} else {
cb(null, r.rows);
done();
}
});
});
} | javascript | {
"resource": ""
} |
q42237 | postSetTags | train | function postSetTags(post_id, tags, cb) {
var ids = _.pluck(tags, 'id')
, q1 = 'DELETE FROM posts_tags WHERE post_id = $1'
, q2 = 'INSERT INTO posts_tags (post_id, tag_id) VALUES ' +
ids.map(function(id) {
return '(' + post_id + ',' + id + ')';
}).join(', ');
db.getClient(function(err, client, done) {
client.query(q1, [post_id], function(err, r) {
if(err) { return cb(err); }
client.query(q2, function(err, r) {
if(err) {
cb(err);
done(err);
} else {
cb(null, r.rowCount);
done();
}
});
});
});
} | javascript | {
"resource": ""
} |
q42238 | checkMouse | train | function checkMouse( mouse ) {
that.debug.groupStart( 'CheckMouse' ); // %REMOVE_LINE%
that.debug.startTimer(); // %REMOVE_LINE%
that.mouse = mouse;
that.trigger = null;
checkMouseTimer = null;
updateWindowSize( that );
if ( checkMouseTimeoutPending // -> There must be an event pending.
&& !that.hiddenMode // -> Can't be in hidden mode.
&& editor.focusManager.hasFocus // -> Editor must have focus.
&& !that.line.mouseNear() // -> Mouse pointer can't be close to the box.
&& ( that.element = elementFromMouse( that, true ) ) ) // -> There must be valid element.
{
// If trigger exists, and trigger is correct -> show the box.
// Don't show the line if trigger is a descendant of some tabu-list element.
if ( ( that.trigger = triggerEditable( that ) || triggerEdge( that ) || triggerExpand( that ) ) &&
!isInTabu( that, that.trigger.upper || that.trigger.lower ) ) {
that.line.attach().place();
}
// Otherwise remove the box
else {
that.trigger = null;
that.line.detach();
}
that.debug.showTrigger( that.trigger ); // %REMOVE_LINE%
that.debug.mousePos( mouse.y, that.element ); // %REMOVE_LINE%
checkMouseTimeoutPending = false;
}
that.debug.stopTimer(); // %REMOVE_LINE%
that.debug.groupEnd(); // %REMOVE_LINE%
} | javascript | {
"resource": ""
} |
q42239 | boxTrigger | train | function boxTrigger( triggerSetup ) {
this.upper = triggerSetup[ 0 ];
this.lower = triggerSetup[ 1 ];
this.set.apply( this, triggerSetup.slice( 2 ) );
} | javascript | {
"resource": ""
} |
q42240 | getAscendantTrigger | train | function getAscendantTrigger( that ) {
var node = that.element,
trigger;
if ( node && isHtml( node ) ) {
trigger = node.getAscendant( that.triggers, true );
// If trigger is an element, neither editable nor editable's ascendant.
if ( trigger && that.editable.contains( trigger ) ) {
// Check for closest editable limit.
// Don't consider trigger as a limit as it may be nested editable (includeSelf=false) (#12009).
var limit = getClosestEditableLimit( trigger );
// Trigger in nested editable area.
if ( limit.getAttribute( 'contenteditable' ) == 'true' )
return trigger;
// Trigger in non-editable area.
else if ( limit.is( that.triggers ) )
return limit;
else
return null;
return trigger;
} else
return null;
}
return null;
} | javascript | {
"resource": ""
} |
q42241 | train | function() {
that.debug.groupStart( 'mouseNear' ); // %REMOVE_LINE%
updateSize( that, this );
var offset = that.holdDistance,
size = this.size;
// Determine neighborhood by element dimensions and offsets.
if ( size && inBetween( that.mouse.y, size.top - offset, size.bottom + offset ) && inBetween( that.mouse.x, size.left - offset, size.right + offset ) ) {
that.debug.logEnd( 'Mouse is near.' ); // %REMOVE_LINE%
return true;
}
that.debug.logEnd( 'Mouse isn\'t near.' ); // %REMOVE_LINE%
return false;
} | javascript | {
"resource": ""
} | |
q42242 | isChildBetweenPointerAndEdge | train | function isChildBetweenPointerAndEdge( that, parent, edgeBottom ) {
var edgeChild = parent[ edgeBottom ? 'getLast' : 'getFirst' ]( function( node ) {
return that.isRelevant( node ) && !node.is( DTD_TABLECONTENT );
} );
if ( !edgeChild )
return false;
updateSize( that, edgeChild );
return edgeBottom ? edgeChild.size.top > that.mouse.y : edgeChild.size.bottom < that.mouse.y;
} | javascript | {
"resource": ""
} |
q42243 | expandSelector | train | function expandSelector( that, node ) {
return !( isTextNode( node )
|| isComment( node )
|| isFlowBreaker( node )
|| isLine( that, node )
|| ( node.type == CKEDITOR.NODE_ELEMENT && node.$ && node.is( 'br' ) ) );
} | javascript | {
"resource": ""
} |
q42244 | expandFilter | train | function expandFilter( that, trigger ) {
that.debug.groupStart( 'expandFilter' ); // %REMOVE_LINE%
var upper = trigger.upper,
lower = trigger.lower;
if ( !upper || !lower // NOT: EDGE_MIDDLE trigger ALWAYS has two elements.
|| isFlowBreaker( lower ) || isFlowBreaker( upper ) // NOT: one of the elements is floated or positioned
|| lower.equals( upper ) || upper.equals( lower ) // NOT: two trigger elements, one equals another.
|| lower.contains( upper ) || upper.contains( lower ) ) { // NOT: two trigger elements, one contains another.
that.debug.logEnd( 'REJECTED. No upper or no lower or they contain each other.' ); // %REMOVE_LINE%
return false;
}
// YES: two trigger elements, pure siblings.
else if ( isTrigger( that, upper ) && isTrigger( that, lower ) && areSiblings( that, upper, lower ) ) {
that.debug.logElementsEnd( [ upper, lower ], // %REMOVE_LINE%
[ 'upper', 'lower' ], 'APPROVED EDGE_MIDDLE' ); // %REMOVE_LINE%
return true;
}
that.debug.logElementsEnd( [ upper, lower ], // %REMOVE_LINE%
[ 'upper', 'lower' ], 'Rejected unknown pair' ); // %REMOVE_LINE%
return false;
} | javascript | {
"resource": ""
} |
q42245 | verticalSearch | train | function verticalSearch( that, stopCondition, selectCriterion, startElement ) {
var upper = startElement,
lower = startElement,
mouseStep = 0,
upperFound = false,
lowerFound = false,
viewPaneHeight = that.view.pane.height,
mouse = that.mouse;
while ( mouse.y + mouseStep < viewPaneHeight && mouse.y - mouseStep > 0 ) {
if ( !upperFound )
upperFound = stopCondition( upper, startElement );
if ( !lowerFound )
lowerFound = stopCondition( lower, startElement );
// Still not found...
if ( !upperFound && mouse.y - mouseStep > 0 )
upper = selectCriterion( that, { x: mouse.x, y: mouse.y - mouseStep } );
if ( !lowerFound && mouse.y + mouseStep < viewPaneHeight )
lower = selectCriterion( that, { x: mouse.x, y: mouse.y + mouseStep } );
if ( upperFound && lowerFound )
break;
// Instead of ++ to reduce the number of invocations by half.
// It's trades off accuracy in some edge cases for improved performance.
mouseStep += 2;
}
return new boxTrigger( [ upper, lower, null, null ] );
} | javascript | {
"resource": ""
} |
q42246 | addListener | train | function addListener(event, callback) {
checkEventValid(event);
if (listeners[event]) {
listeners[event].push(callback);
} else {
listeners[event] = [callback];
}
} | javascript | {
"resource": ""
} |
q42247 | removeListener | train | function removeListener(event, eventHandler) {
checkEventValid(event);
if (listeners[event] && listeners[event].length) {
var indexOfListener = listeners[event].indexOf(eventHandler);
if (indexOfListener > -1) {
listeners[event].splice(indexOfListener, 1);
}
}
} | javascript | {
"resource": ""
} |
q42248 | processSize | train | function processSize(targetSize, origSize) {
var match = (targetSize.match(r_percentage) || [])[1];
if (match /= 100) {
return {
width: origSize.width * match,
height: 0
};
} else {
return {
width: (targetSize.match(r_width) || [])[1] || 0,
height: (targetSize.match(r_height) || [])[1] || 0
};
}
} | javascript | {
"resource": ""
} |
q42249 | convertSizes | train | function convertSizes(sizes) {
var tmp = [];
for (var size in sizes) {
tmp.push({
size: size,
settings: _.extend({suffix: '', prefix: ''}, sizes[size])
});
}
return tmp;
} | javascript | {
"resource": ""
} |
q42250 | getPhantomExitCb | train | function getPhantomExitCb (specId, allSpecs, cfg, done) {
var spawnCb = function (error, result, code) {
if (error) {
ok = false;
if (cfg.debug) {
console.log("PhantomJS exited with code " + code);
}
}
var nextSpecId = specId + 1;
if (nextSpecId == allSpecs.length) { // last spec
done(ok);
} else {
startSpec (nextSpecId, allSpecs, cfg, done);
}
};
return spawnCb;
} | javascript | {
"resource": ""
} |
q42251 | startPhantom | train | function startPhantom (specPath, cfg, cb) {
var args = [specPath];
if (cfg.verbose) {
args.push("--verbose"); // custom, to be handled by spec runner
}
if (cfg.debug) {
args.push("--debug"); // custom, to be handled by spec runner
}
if (cfg.color) {
args.push("--color"); // custom, to be handled by spec runner
}
args.push("--xunitName=" + cfg.xunitName);
var phantomProcess = grunt.util.spawn({
cmd : 'phantomjs',
args : args
}, cb);
phantomProcess.stdout.pipe(process.stdout);
phantomProcess.stderr.pipe(process.stderr);
return phantomProcess;
} | javascript | {
"resource": ""
} |
q42252 | startSpec | train | function startSpec (n, allSpecs, cfg, done) {
var printId = n + 1;
var specPath = allSpecs[n];
var nSpecs = allSpecs.length;
var msg = "Running spec file " + specPath + " [" + printId + "/" + nSpecs + "]";
var bar = Array(process.stdout.columns).join("*");
console.log("\n" + bar.cyan);
console.log(alignCenter(msg).cyan);
console.log(bar.cyan + "\n");
var cb = getPhantomExitCb(n, allSpecs, cfg, done);
startPhantom(specPath, cfg, cb);
} | javascript | {
"resource": ""
} |
q42253 | train | function(inSender, e) {
// if a scroll event originated here, pass it to our strategy to handle
if (this.$.strategy.domScroll && e.originator == this) {
this.$.strategy.scroll(inSender, e);
}
this.doScroll(e);
return true;
} | javascript | {
"resource": ""
} | |
q42254 | train | function() {
var fileIndex;
if (stop_loop) {
return false;
}
// Check to see if are in queue mode
if (opts.queuefiles > 0 && processingQueue.length >= opts.queuefiles) {
return pause(opts.queuewait);
} else {
// Take first thing off work queue
fileIndex = workQueue[0];
workQueue.splice(0, 1);
// Add to processing queue
processingQueue.push(fileIndex);
}
try {
if (beforeEach(files[fileIndex]) !== false) {
if (fileIndex === files_count) {
return;
}
var reader = new FileReader(),
max_file_size = 1048576 * opts.maxfilesize;
reader.index = fileIndex;
if (files[fileIndex].size > max_file_size) {
opts.error(errors[2], files[fileIndex], fileIndex);
// Remove from queue
processingQueue.forEach(function(value, key) {
if (value === fileIndex) {
processingQueue.splice(key, 1);
}
});
filesRejected++;
return true;
}
reader.onloadend = !opts.beforeSend ? send : function (e) {
opts.beforeSend(files[fileIndex], fileIndex, function () { send(e); });
};
reader.readAsBinaryString(files[fileIndex]);
} else {
filesRejected++;
}
} catch (err) {
// Remove from queue
processingQueue.forEach(function(value, key) {
if (value === fileIndex) {
processingQueue.splice(key, 1);
}
});
opts.error(errors[0]);
return false;
}
// If we still have work to do,
if (workQueue.length > 0) {
process();
}
} | javascript | {
"resource": ""
} | |
q42255 | ratio | train | function ratio(options) {
const { width, height } = options;
if ((width || height) && !(width && height)) {
if (width) {
options.height = width;
}
if (height) {
options.width = height;
}
}
return options;
} | javascript | {
"resource": ""
} |
q42256 | loginRequired | train | function loginRequired(fn) {
return function(req, res, next) {
if(isLoggedIn(req)) {
fn(req, res, next);
} else {
next(new exceptions.PermissionRequired());
}
}
} | javascript | {
"resource": ""
} |
q42257 | settingsPercentage | train | function settingsPercentage(projectJshintSettings) {
verify.object(projectJshintSettings, 'expected jshint object');
//console.log('looking at jshint settings\n' +
// JSON.stringify(projectJshintSettings, null, 2));
var allSettings = getAllSettings();
verify.object(allSettings, 'could not get all jshint settings');
var totalSettings = Object.keys(allSettings).length;
verify.positiveNumber(totalSettings, 'epected all settings to have properties');
Object.keys(projectJshintSettings).forEach(function (key) {
if (key === 'predef') { return; }
if (typeof allSettings[key] === 'undefined') {
console.error('unknown setting', key, projectJshintSettings[key]);
}
});
var specifiedSettings = Object.keys(projectJshintSettings).length;
return +(specifiedSettings / totalSettings * 100).toPrecision(2);
} | javascript | {
"resource": ""
} |
q42258 | train | function() {
var ret = Backbone.Collection.prototype.set.apply(this, arguments);
this.each(function(model) {
// Assign `db` to all models in the collection
if (this.db) {
model.db = this.db;
}
// Assign `user` to all models in the collection
if (this.user) {
model.user = this.user;
}
}.bind(this));
return ret;
} | javascript | {
"resource": ""
} | |
q42259 | writeJSON | train | function writeJSON(filename, obj) {
return new Promise(function (resolve, reject) {
if (!Object.is(obj)) resolve(new Error('writeJSON requires the second argument to be an object'));
_fs2['default'].writeFile(filename, JSON.stringify(obj, null, 2) + '\n', function (err) {
if (err) reject(err);
resolve(obj);
});
});
} | javascript | {
"resource": ""
} |
q42260 | encode | train | function encode(position_array){
if(!_.isArray(position_array) || position_array.length<=0){
throw new Error('Array of tree positions required');
}
var left_position_array = _.map(position_array, function(v){return v;});
var right_position_array = _.map(position_array, function(v){return v;});
// lets modify the last position in the right hand sequence so it is one more than the left
var last_position = right_position_array.pop();
last_position++;
right_position_array.push(last_position);
return {
left:calculate_encoding_from_tree_position(left_position_array),
right:calculate_encoding_from_tree_position(right_position_array)
}
} | javascript | {
"resource": ""
} |
q42261 | get_parsed_encodings | train | function get_parsed_encodings(data){
return {
numerator:data.numerator,
denominator:data.denominator,
encoding:get_big_division(data.numerator, data.denominator)
};
} | javascript | {
"resource": ""
} |
q42262 | calculate_encoding_from_tree_position | train | function calculate_encoding_from_tree_position(position_array){
// if we have only one position then it means we have a root element (i.e. one at the top of the tree)
// and this is an easy fraction to calculate (i.e. x / 1)
if(position_array.length==1){
return get_parsed_encodings({
// the numerator is the position of the root element
numerator:position_array[0],
// the denominator is always 1
denominator:1
});
}
// initialize the data array we will work with
var data = {
parts:_.map(position_array, function(v){return v;}),
unityparts:[]
};
// lets insert the alternate unity into the position array
for(var i=0; i<data.parts.length; i++)
{
// add the next element into the array
// and as long as we are not the last element, insert unity
data.unityparts.push(data.parts[i]);
if(i<data.parts.length-1)
{
data.unityparts.push(1);
}
}
// There will always be AT LEAST 3 elements in the array at this point
// initialize values by purging the last element from the array as the initial numerator
// the denominator will always start off as null because the first fraction will be just the last_element (i.e. last_element / 1)
data.numerator = data.unityparts.pop();
data.denominator = 1;
// the integer starts off as 0 to deal with the not-possible event of if we only had 1 or 2 array elements
data.integer = 0;
// now lets start reducing the continued fraction!
while(data.unityparts.length>0)
{
data.integer = data.unityparts.pop();
data = reduce_continued_fraction_step(data);
// this has just performed:
// a,b -> a + 1 / b
}
return get_parsed_encodings(data);
} | javascript | {
"resource": ""
} |
q42263 | builder | train | function builder() {
// make the arguments one string
var args = stringify.apply(null, arguments);
// make the final styles object
builder._curStyles.forEach(function (thisStyle) {
objectAssign(builder._curStyle, thisStyle);
});
loggerInstance._inputsBuffer.push({
arg: args,
style: builder._curStyle
});
// reset the state
builder._curStyle = objectAssign({}, defaults.style);
builder._curStyles = [];
return builder;
} | javascript | {
"resource": ""
} |
q42264 | trimToMaxWidth | train | function trimToMaxWidth (width, text) {
var truncated = text.split('\n').map(function (line) {
return line.substring(0, width);
});
return truncated.join('\n');
} | javascript | {
"resource": ""
} |
q42265 | getContainer | train | function getContainer() {
if (container) {
return container;
}
body.insertAdjacentHTML('afterbegin', mustache.render(containerTemplate));
container = document.querySelector('.js-feedback-queue');
return container;
} | javascript | {
"resource": ""
} |
q42266 | train | function (store, type, record, addId) {
var json;
type = this._parseModelOrType(store, type);
json = record.serialize({includeId: true});
if (!json.id && addId) {
json.id = this.generateId(store, type);
}
type.eachRelationship(function (key, meta) {
var records;
if (!meta.async && meta.kind === 'hasMany' && (records = record.get(key)) && !json[key]) {
json[key] = records.mapBy('id').filter(Boolean);
}
});
return json;
} | javascript | {
"resource": ""
} | |
q42267 | train | function (store, type/*, record*/) {
var key, counters;
key = dasherize(this._parseModelOrType(store, type).typeKey);
counters = this.get('_generatedCounterId');
if (!counters[key]) {
counters[key] = 1;
}
return 'fixture-' + key + '-' + (counters[key]++);
} | javascript | {
"resource": ""
} | |
q42268 | train | function (store, type, id) {
id = coerceId(id);
return this.fixturesForType(store, type).find(function (record) {
return coerceId(record.id) === id;
});
} | javascript | {
"resource": ""
} | |
q42269 | train | function (response, statusCode, statusText) {
var adapter = this, responseFunction, isOk, shouldCopy, isInvalid;
statusCode = statusCode || 200;
statusText = statusText || HTTP_STATUS_MESSAGES[statusCode];
isOk = Math.round(statusCode / 100) === 2;
if (typeof response === 'function') {
shouldCopy = true;
responseFunction = bind(this, response);
}
else {
isInvalid = response instanceof DS.InvalidError;
if (isInvalid) {
response = new DS.InvalidError(response.errors);
}
else {
response = copy(response, true);
}
responseFunction = function () {
return response;
};
}
return new Ember.RSVP.Promise(function (resolve, reject) {
var value, func, data;
func = isOk ? resolve : reject;
data = responseFunction();
if (shouldCopy) {
data = copy(data, true);
}
value = isOk ? data : (isInvalid ? data : {
response: data || {error: statusText},
responseJSON: data || {error: statusText},
status: statusCode,
statusText: statusText
});
Ember.runInDebug(function () {
console[isOk ? 'log' : 'error'](
fmt('[dev-fixtures] Simulating %@ response:', isOk ? 'success' : 'error'),
copy(response, true)
);
});
if (adapter.get('simulateRemoteResponse')) {
// Schedule with setTimeout
later(null, func, value, adapter.get('latency'));
}
else {
// Asynchronous, but at the of the run-loop with zero latency
schedule('actions', null, func, value);
}
}, "DS: DevFixtureAdapter#simulateRemoteCall");
} | javascript | {
"resource": ""
} | |
q42270 | train | function (store, json) {
var handledRecords = [], key, records, handleRecord, Model;
handleRecord = function (record) {
this.completeJsonForRecord(store, record, Model, json, handledRecords);
};
for (key in json) {
if (json.hasOwnProperty(key)) {
records = json[key];
Model = store.modelFor(singularize(key));
forEach(records, handleRecord, this);
}
}
return json;
} | javascript | {
"resource": ""
} | |
q42271 | train | function (store, record, Model, json, handledRecords) {
if (handledRecords.indexOf(record) === -1) {
handledRecords.push(record);
Model.eachRelationship(function (name, meta) {
var related, fixtures, relatedTypeKey, ids;
if (!meta.async && record[name]) {
fixtures = Ember.A(this.fixturesForType(store, meta.type));
ids = coerceId(record[name]);
if (meta.kind === 'hasMany') {
if (ids && ids.length) {
related = fixtures.filter(function (r) {
return ids.indexOf(coerceId(r.id)) !== -1;
});
}
}
else if (meta.kind === 'belongsTo') {
related = fixtures.find(function (r) {
return coerceId(r.id) === ids;
});
if (related) {
related = [related];
}
}
if (related) {
relatedTypeKey = pluralize(meta.type.typeKey);
if (!json[relatedTypeKey]) {
json[relatedTypeKey] = [];
}
related.forEach(function (record) {
if (json[relatedTypeKey].indexOf(record) === -1) {
json[relatedTypeKey].push(record);
}
this.completeJsonForRecord(store, record, meta.type, json, handledRecords);
}, this);
}
}
}, this);
}
} | javascript | {
"resource": ""
} | |
q42272 | train | function (store, type, records) {
var json = {};
type = this._parseModelOrType(store, type);
json[pluralize(type.typeKey)] = records;
this._injectFixturesInResponse.apply(this, [store, json].concat(slice.call(arguments, 3)));
return this.completeJsonResponse(store, json);
} | javascript | {
"resource": ""
} | |
q42273 | train | function (errors) {
if (typeof errors === 'string' || errors instanceof Error) {
errors = {'*': '' + errors};
}
else if (errors == null) {
errors = {'*': 'Unknown error'};
}
return new DS.InvalidError(errors);
} | javascript | {
"resource": ""
} | |
q42274 | train | function (store, type, fixtureRecord) {
var fixture;
if (fixtureRecord.id) {
type = this._parseModelOrType(store, type);
// lookup for a fixture
fixture = this.fixtureForId(store, type, fixtureRecord.id);
if (fixture) {
Ember.merge(fixture, fixtureRecord);
this._touchDateAttr(store, type, fixture, 'updatedAt');
return fixture;
}
}
else {
throw new Error('Updating a fixture requires an ID.');
}
// new fixture
this._touchDateAttr(store, type, fixtureRecord, 'createdAt', 'updatedAt');
this.fixturesForType(store, type).pushObject(fixtureRecord);
return fixtureRecord;
} | javascript | {
"resource": ""
} | |
q42275 | train | function (store, type, fixtureRecord) {
var fixture = fixtureRecord || {};
type = this._parseModelOrType(store, type);
if (!fixtureRecord.id) {
fixtureRecord.id = this.generateId(store, type);
}
if (this.fixtureForId(store, type, fixture.id)) {
throw new Error('Fixture `' + type.typeKey + '` with id `' + fixture.id + '` already exists.');
}
return this.updateFixtures(store, type, fixture);
} | javascript | {
"resource": ""
} | |
q42276 | train | function (store, type, fixtureRecord) {
var fixture, fixturesArray;
if (fixtureRecord.id) {
fixture = this.fixtureForId(store, type, fixtureRecord.id);
if (fixture) {
fixturesArray = this.fixturesForType(store, type);
fixturesArray.splice(fixturesArray.indexOf(fixtureRecord), 1);
}
}
else {
throw new Error('Deleting a fixture requires an ID.');
}
return null;
} | javascript | {
"resource": ""
} | |
q42277 | train | function (store, json) {
var i, args = slice.call(arguments, 2), len = args.length, records, typeKey;
for (i = 0; i < len; i += 2) {
records = args[i + 1];
records = records ? (isArray(records) ? records.slice() : [records]) : [];
typeKey = pluralize(this._parseModelOrType(store, args[i]).typeKey);
if (!json[typeKey]) {
json[typeKey] = records;
}
else {
injectNoConflict(json[typeKey], records);
}
}
return json;
} | javascript | {
"resource": ""
} | |
q42278 | artery | train | function artery(pw, iv, meds) {
if (!iv.artery) iv.artery = new Artery();
plet.props(iv.artery, sprops, meds || iv, true);
iv.artery.count = iv.count;
iv.artery.data = iv.data;
iv.artery.passes = iv.passes;
iv.artery.pass = iv.pass;
return iv.artery;
} | javascript | {
"resource": ""
} |
q42279 | Pulse | train | function Pulse(pw, iv, drip) {
var pulse = this;
plet.merge(pulse, drip.pulse);
pulse.count = drip.cbCount + 1;
pulse.event = drip.pulse.event;
} | javascript | {
"resource": ""
} |
q42280 | assertlet | train | function assertlet(obj, other, objName, otherName) {
plet.props(obj, sprops, other, false, false, objName || '1st', otherName || '2nd');
} | javascript | {
"resource": ""
} |
q42281 | pulselet | train | function pulselet(artery, event, endEvent) {
return (new Drip(null, artery, event, endEvent)).pulse;
} | javascript | {
"resource": ""
} |
q42282 | emits | train | function emits(pw, iv, i) {
for (var ci = i, a; iv[ci] && (ci === i || iv[ci].cbCount < iv[ci].repeat); ci++) iv[ci].emit(pw, iv);
} | javascript | {
"resource": ""
} |
q42283 | Drip | train | function Drip(pw, iv, evt, endEvent, emit) {
var ieo = typeof evt === 'object', eo = ieo ? evt : null, pulse = { event: ieo ? evt.event : evt };
if (!pulse.event) throw new Error('Event is required');
if (eo && eo.id) pulse.id = eo.id; // IDs are not inherited because iv/pulse IDs are non-transferable
this.pulse = plet.props(plet.props(pulse, sprops, eo, true, true), sprops, iv); // pulse should only contain values from the event or inherited from the iv
this.cbCount = 0;
if (emit) this.emit(pw, iv);
} | javascript | {
"resource": ""
} |
q42284 | inlet | train | function inlet(pw, iv, drip) {
var ib = drip ? drip.pulse.inbound : iv.inbound;
if (!ib) return true;
var tgs = ib.selector && typeof iv.target.querySelectorAll === 'function' ? iv.target.querySelectorAll(ib.selector) : [iv.target];
var ttl = tgs.length;
var fn = function inboundListener() {
if (arguments.length) iv.pass.push.apply(iv.pass, arguments);
if (++ib.count >= ib.repeat) {
plet.event(ib.event, tgs, fn, ib.useCapture, true); // remove listener
if (drip) drip.emit(pw, iv, true);
// TODO : no drip should continue i.v. emission
}
};
plet.event(ib.event, tgs, fn, ib.useCapture);
} | javascript | {
"resource": ""
} |
q42285 | commonErrorHandler | train | function commonErrorHandler(err, req, res, next) { // jshint ignore:line
debug(err);
// if we got here without an error, it's a 404 case
if (!err) {
err = new NotFoundError();
}
// here we've got an error, it could be a different one than
// the one we've constructed, so provide defaults to be safe
err.message = err.message || 'Internal Server Error';
res
.status(err.code || err.statusCode || 500)
.type('application/json')
.send(stringify(err));
} | javascript | {
"resource": ""
} |
q42286 | train | function( newRules, featureName, overrideCustom ) {
// Check arguments and constraints. Clear cache.
if ( !beforeAddingRule( this, newRules, overrideCustom ) )
return false;
var i, ret;
if ( typeof newRules == 'string' )
newRules = parseRulesString( newRules );
else if ( newRules instanceof CKEDITOR.style ) {
// If style has the cast method defined, use it and abort.
if ( newRules.toAllowedContentRules )
return this.allow( newRules.toAllowedContentRules( this.editor ), featureName, overrideCustom );
newRules = convertStyleToRules( newRules );
} else if ( CKEDITOR.tools.isArray( newRules ) ) {
for ( i = 0; i < newRules.length; ++i )
ret = this.allow( newRules[ i ], featureName, overrideCustom );
return ret; // Return last status.
}
addAndOptimizeRules( this, newRules, featureName, this.allowedContent, this._.allowedRules );
return true;
} | javascript | {
"resource": ""
} | |
q42287 | train | function( newRules ) {
// Check arguments and constraints. Clear cache.
// Note: we pass true in the 3rd argument, because disallow() should never
// be blocked by custom configuration.
if ( !beforeAddingRule( this, newRules, true ) )
return false;
if ( typeof newRules == 'string' )
newRules = parseRulesString( newRules );
addAndOptimizeRules( this, newRules, null, this.disallowedContent, this._.disallowedRules );
return true;
} | javascript | {
"resource": ""
} | |
q42288 | train | function( feature ) {
if ( this.disabled )
return true;
if ( !feature )
return true;
// Some features may want to register other features.
// E.g. a button may return a command bound to it.
if ( feature.toFeature )
feature = feature.toFeature( this.editor );
// If default configuration (will be checked inside #allow()),
// then add allowed content rules.
this.allow( feature.allowedContent, feature.name );
this.addTransformations( feature.contentTransformations );
this.addContentForms( feature.contentForms );
// If custom configuration or any DACRs, then check if required content is allowed.
if ( feature.requiredContent && ( this.customConfig || this.disallowedContent.length ) )
return this.check( feature.requiredContent );
return true;
} | javascript | {
"resource": ""
} | |
q42289 | train | function( transformations ) {
if ( this.disabled )
return;
if ( !transformations )
return;
var optimized = this._.transformations,
group, i;
for ( i = 0; i < transformations.length; ++i ) {
group = optimizeTransformationsGroup( transformations[ i ] );
if ( !optimized[ group.name ] )
optimized[ group.name ] = [];
optimized[ group.name ].push( group.rules );
}
} | javascript | {
"resource": ""
} | |
q42290 | train | function( test, applyTransformations, strictCheck ) {
if ( this.disabled )
return true;
// If rules are an array, expand it and return the logical OR value of
// the rules.
if ( CKEDITOR.tools.isArray( test ) ) {
for ( var i = test.length ; i-- ; ) {
if ( this.check( test[ i ], applyTransformations, strictCheck ) )
return true;
}
return false;
}
var element, result, cacheKey;
if ( typeof test == 'string' ) {
cacheKey = test + '<' + ( applyTransformations === false ? '0' : '1' ) + ( strictCheck ? '1' : '0' ) + '>';
// Check if result of this check hasn't been already cached.
if ( cacheKey in this._.cachedChecks )
return this._.cachedChecks[ cacheKey ];
// Create test element from string.
element = mockElementFromString( test );
} else {
// Create test element from CKEDITOR.style.
element = mockElementFromStyle( test );
}
// Make a deep copy.
var clone = CKEDITOR.tools.clone( element ),
toBeRemoved = [],
transformations;
// Apply transformations to original element.
// Transformations will be applied to clone by the filter function.
if ( applyTransformations !== false && ( transformations = this._.transformations[ element.name ] ) ) {
for ( i = 0; i < transformations.length; ++i )
applyTransformationsGroup( this, element, transformations[ i ] );
// Transformations could modify styles or classes, so they need to be copied
// to attributes object.
updateAttributes( element );
}
// Filter clone of mocked element.
processElement( this, clone, toBeRemoved, {
doFilter: true,
doTransform: applyTransformations !== false,
skipRequired: !strictCheck,
skipFinalValidation: !strictCheck
} );
// Element has been marked for removal.
if ( toBeRemoved.length > 0 ) {
result = false;
// Compare only left to right, because clone may be only trimmed version of original element.
} else if ( !CKEDITOR.tools.objectCompare( element.attributes, clone.attributes, true ) ) {
result = false;
} else {
result = true;
}
// Cache result of this test - we can build cache only for string tests.
if ( typeof test == 'string' )
this._.cachedChecks[ cacheKey ] = result;
return result;
} | javascript | {
"resource": ""
} | |
q42291 | applyAllowedRule | train | function applyAllowedRule( rule, element, status, skipRequired ) {
// This rule doesn't match this element - skip it.
if ( rule.match && !rule.match( element ) )
return;
// If element doesn't have all required styles/attrs/classes
// this rule doesn't match it.
if ( !skipRequired && !hasAllRequired( rule, element ) )
return;
// If this rule doesn't validate properties only mark element as valid.
if ( !rule.propertiesOnly )
status.valid = true;
// Apply rule only when all attrs/styles/classes haven't been marked as valid.
if ( !status.allAttributes )
status.allAttributes = applyAllowedRuleToHash( rule.attributes, element.attributes, status.validAttributes );
if ( !status.allStyles )
status.allStyles = applyAllowedRuleToHash( rule.styles, element.styles, status.validStyles );
if ( !status.allClasses )
status.allClasses = applyAllowedRuleToArray( rule.classes, element.classes, status.validClasses );
} | javascript | {
"resource": ""
} |
q42292 | applyDisallowedRule | train | function applyDisallowedRule( rule, element, status ) {
// This rule doesn't match this element - skip it.
if ( rule.match && !rule.match( element ) )
return;
// No properties - it's an element only rule so it disallows entire element.
// Early return is handled in filterElement.
if ( rule.noProperties )
return false;
// Apply rule to attributes, styles and classes. Switch hadInvalid* to true if method returned true.
status.hadInvalidAttribute = applyDisallowedRuleToHash( rule.attributes, element.attributes ) || status.hadInvalidAttribute;
status.hadInvalidStyle = applyDisallowedRuleToHash( rule.styles, element.styles ) || status.hadInvalidStyle;
status.hadInvalidClass = applyDisallowedRuleToArray( rule.classes, element.classes ) || status.hadInvalidClass;
} | javascript | {
"resource": ""
} |
q42293 | convertStyleToRules | train | function convertStyleToRules( style ) {
var styleDef = style.getDefinition(),
rules = {},
rule,
attrs = styleDef.attributes;
rules[ styleDef.element ] = rule = {
styles: styleDef.styles,
requiredStyles: styleDef.styles && CKEDITOR.tools.objectKeys( styleDef.styles )
};
if ( attrs ) {
attrs = copy( attrs );
rule.classes = attrs[ 'class' ] ? attrs[ 'class' ].split( /\s+/ ) : null;
rule.requiredClasses = rule.classes;
delete attrs[ 'class' ];
rule.attributes = attrs;
rule.requiredAttributes = attrs && CKEDITOR.tools.objectKeys( attrs );
}
return rules;
} | javascript | {
"resource": ""
} |
q42294 | filterElement | train | function filterElement( that, element, opts ) {
var name = element.name,
privObj = that._,
allowedRules = privObj.allowedRules.elements[ name ],
genericAllowedRules = privObj.allowedRules.generic,
disallowedRules = privObj.disallowedRules.elements[ name ],
genericDisallowedRules = privObj.disallowedRules.generic,
skipRequired = opts.skipRequired,
status = {
// Whether any of rules accepted element.
// If not - it will be stripped.
valid: false,
// Objects containing accepted attributes, classes and styles.
validAttributes: {},
validClasses: {},
validStyles: {},
// Whether all are valid.
// If we know that all element's attrs/classes/styles are valid
// we can skip their validation, to improve performance.
allAttributes: false,
allClasses: false,
allStyles: false,
// Whether element had (before applying DACRs) at least one invalid attribute/class/style.
hadInvalidAttribute: false,
hadInvalidClass: false,
hadInvalidStyle: false
},
i, l;
// Early return - if there are no rules for this element (specific or generic), remove it.
if ( !allowedRules && !genericAllowedRules )
return null;
// Could not be done yet if there were no transformations and if this
// is real (not mocked) object.
populateProperties( element );
// Note - this step modifies element's styles, classes and attributes.
if ( disallowedRules ) {
for ( i = 0, l = disallowedRules.length; i < l; ++i ) {
// Apply rule and make an early return if false is returned what means
// that element is completely disallowed.
if ( applyDisallowedRule( disallowedRules[ i ], element, status ) === false )
return null;
}
}
// Note - this step modifies element's styles, classes and attributes.
if ( genericDisallowedRules ) {
for ( i = 0, l = genericDisallowedRules.length; i < l; ++i )
applyDisallowedRule( genericDisallowedRules[ i ], element, status );
}
if ( allowedRules ) {
for ( i = 0, l = allowedRules.length; i < l; ++i )
applyAllowedRule( allowedRules[ i ], element, status, skipRequired );
}
if ( genericAllowedRules ) {
for ( i = 0, l = genericAllowedRules.length; i < l; ++i )
applyAllowedRule( genericAllowedRules[ i ], element, status, skipRequired );
}
return status;
} | javascript | {
"resource": ""
} |
q42295 | mockElementFromString | train | function mockElementFromString( str ) {
var element = parseRulesString( str ).$1,
styles = element.styles,
classes = element.classes;
element.name = element.elements;
element.classes = classes = ( classes ? classes.split( /\s*,\s*/ ) : [] );
element.styles = mockHash( styles );
element.attributes = mockHash( element.attributes );
element.children = [];
if ( classes.length )
element.attributes[ 'class' ] = classes.join( ' ' );
if ( styles )
element.attributes.style = CKEDITOR.tools.writeCssText( element.styles );
return element;
} | javascript | {
"resource": ""
} |
q42296 | mockElementFromStyle | train | function mockElementFromStyle( style ) {
var styleDef = style.getDefinition(),
styles = styleDef.styles,
attrs = styleDef.attributes || {};
if ( styles ) {
styles = copy( styles );
attrs.style = CKEDITOR.tools.writeCssText( styles, true );
} else {
styles = {};
}
var el = {
name: styleDef.element,
attributes: attrs,
classes: attrs[ 'class' ] ? attrs[ 'class' ].split( /\s+/ ) : [],
styles: styles,
children: []
};
return el;
} | javascript | {
"resource": ""
} |
q42297 | optimizeRule | train | function optimizeRule( rule ) {
var validatorName,
requiredProperties,
i;
for ( validatorName in validators )
rule[ validatorName ] = validatorFunction( rule[ validatorName ] );
var nothingRequired = true;
for ( i in validatorsRequired ) {
validatorName = validatorsRequired[ i ];
requiredProperties = optimizeRequiredProperties( rule[ validatorName ] );
// Don't set anything if there are no required properties. This will allow to
// save some memory by GCing all empty arrays (requiredProperties).
if ( requiredProperties.length ) {
rule[ validatorName ] = requiredProperties;
nothingRequired = false;
}
}
rule.nothingRequired = nothingRequired;
rule.noProperties = !( rule.attributes || rule.classes || rule.styles );
} | javascript | {
"resource": ""
} |
q42298 | optimizeRules | train | function optimizeRules( optimizedRules, rules ) {
var elementsRules = optimizedRules.elements,
genericRules = optimizedRules.generic,
i, l, rule, element, priority;
for ( i = 0, l = rules.length; i < l; ++i ) {
// Shallow copy. Do not modify original rule.
rule = copy( rules[ i ] );
priority = rule.classes === true || rule.styles === true || rule.attributes === true;
optimizeRule( rule );
// E.g. "*(xxx)[xxx]" - it's a generic rule that
// validates properties only.
// Or '$1': { match: function() {...} }
if ( rule.elements === true || rule.elements === null ) {
// Add priority rules at the beginning.
genericRules[ priority ? 'unshift' : 'push' ]( rule );
}
// If elements list was explicitly defined,
// add this rule for every defined element.
else {
// We don't need elements validator for this kind of rule.
var elements = rule.elements;
delete rule.elements;
for ( element in elements ) {
if ( !elementsRules[ element ] )
elementsRules[ element ] = [ rule ];
else
elementsRules[ element ][ priority ? 'unshift' : 'push' ]( rule );
}
}
}
} | javascript | {
"resource": ""
} |
q42299 | processProtectedElement | train | function processProtectedElement( that, comment, protectedRegexs, filterOpts ) {
var source = decodeURIComponent( comment.value.replace( /^\{cke_protected\}/, '' ) ),
protectedFrag,
toBeRemoved = [],
node, i, match;
// Protected element's and protected source's comments look exactly the same.
// Check if what we have isn't a protected source instead of protected script/noscript.
if ( protectedRegexs ) {
for ( i = 0; i < protectedRegexs.length; ++i ) {
if ( ( match = source.match( protectedRegexs[ i ] ) ) &&
match[ 0 ].length == source.length // Check whether this pattern matches entire source
// to avoid '<script>alert("<? 1 ?>")</script>' matching
// the PHP's protectedSource regexp.
)
return true;
}
}
protectedFrag = CKEDITOR.htmlParser.fragment.fromHtml( source );
if ( protectedFrag.children.length == 1 && ( node = protectedFrag.children[ 0 ] ).type == CKEDITOR.NODE_ELEMENT )
processElement( that, node, toBeRemoved, filterOpts );
// If protected element has been marked to be removed, return 'false' - comment was rejected.
return !toBeRemoved.length;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.