_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q36800 | validateReQL | train | function validateReQL (reql, reqlOpts, whitelist) {
var args = assertArgs(arguments, {
'reql': '*',
'[reqlOpts]': 'object',
'whitelist': 'array'
})
reql = args.reql
reqlOpts = args.reqlOpts
whitelist = args.whitelist
var firstErr
var errCount = 0
var promises = whitelist.map(function (reqlValidator) {
return validate(reql, reqlOpts, reqlValidator)
.catch(function (err) {
firstErr = firstErr || err
errCount++
})
})
return Promise.all(promises).then(function () {
if (errCount === whitelist.length) {
throw firstErr
} else {
return true
}
})
} | javascript | {
"resource": ""
} |
q36801 | do_plain | train | function do_plain(url, opts) {
opts = do_args(url, opts);
if(opts.redirect_loop_counter === undefined) {
opts.redirect_loop_counter = 10;
}
var buffer;
var d = Q.defer();
var req = require(opts.protocol).request(opts.url, function(res) {
var buffer = "";
res.setEncoding('utf8');
function collect_chunks(chunk) {
buffer += chunk;
}
res.on('data', collect_chunks);
res.once('end', function() {
res.removeListener('data', collect_chunks);
var content_type = res.headers['content-type'] || undefined;
//debug.log('content_type = ' , content_type);
d.resolve( Q.fcall(function() {
//debug.log('buffer = ', buffer);
//debug.log('res.headers = ', res.headers);
if(res.headers && res.headers['set-cookie']) {
_cookies.set(opts.url, res.headers['set-cookie']);
}
if( (res.statusCode >= 301) && (res.statusCode <= 303) ) {
if(opts.redirect_loop_counter < 0) {
throw new Error('Redirect loop detected');
}
opts.redirect_loop_counter -= 1;
//debug.log('res.statusCode = ', res.statusCode);
//debug.log('res.headers.location = ', res.headers.location);
return do_plain(res.headers.location, {
'method': 'GET',
'headers': {
'accept': opts.url.headers && opts.url.headers.accept
}
});
}
if(!((res.statusCode >= 200) && (res.statusCode < 400))) {
throw new HTTPError(res.statusCode, ((content_type === 'application/json') ? JSON.parse(buffer) : buffer) );
}
return buffer;
}) );
});
}).once('error', function(e) {
d.reject(new TypeError(''+e));
});
if(opts.body && (url.method !== 'GET')) {
buffer = is.string(opts.body) ? opts.body : JSON.stringify(opts.body);
//debug.log('Writing buffer = ', buffer);
req.end( buffer, 'utf8' );
} else {
req.end();
}
return d.promise;
} | javascript | {
"resource": ""
} |
q36802 | do_js | train | function do_js(url, opts) {
opts = opts || {};
if(is.object(opts) && is['function'](opts.body)) {
opts.body = FUNCTION(opts.body).stringify();
} else if(is.object(opts) && is.string(opts.body)) {
} else {
throw new TypeError('opts.body is not function nor string');
}
opts.headers = opts.headers || {};
if(opts.body) {
opts.headers['Content-Type'] = 'application/javascript;charset=utf8';
}
// Default method should be POST since JavaScript code usually might change something.
if(!opts.method) {
opts.method = 'post';
}
opts.headers.Accept = 'application/json';
return do_plain(url, opts).then(function(buffer) {
return JSON.parse(buffer);
});
} | javascript | {
"resource": ""
} |
q36803 | entrify | train | function entrify(dir, options = {}) {
if (!dir) {
throw new Error('the path is required')
}
if (typeof dir !== 'string') {
throw new Error('the path must be a string')
}
options = Object.assign({}, defaults, options)
return entrifyFromPkg(dir, options)
} | javascript | {
"resource": ""
} |
q36804 | entrifyFromPkg | train | function entrifyFromPkg(dir, options) {
// Find package.json files.
const pkgPaths = glob.sync('**/package.json', { cwd: dir, nodir: true, absolute: true })
pkgPaths.forEach((pkgPath) => {
console.log('[entrify]', 'Found:', pkgPath)
const pkg = require(pkgPath)
// A package.json file should have a main entry.
if (!pkg.main) {
console.warn('[entrify]', pkgPath, 'does not have a main entry.')
return
}
// The main entry should not point to an index.js file.
if (pkg.main === 'index.js' || pkg.main === './index.js') {
console.warn('[entrify]', pkgPath, 'main entry is index.js.')
return
}
// Ensure the index.js file to create doesn't already exist.
const pkgDir = path.dirname(pkgPath)
const indexPath = `${pkgDir}/index.js`
if (fs.existsSync(indexPath)) {
console.warn('[entrify]', indexPath, 'already exists.')
return
}
// Create an index.js file alongside the package.json.
const name = camelize(path.basename(pkgDir))
const main = pkg.main.startsWith('./') ? pkg.main : `./${pkg.main}`
fs.writeFileSync(indexPath, indexTemplate(options.format, { name, main }))
console.log('[entrify]', indexPath, 'created!')
// Delete the package.json file.
fs.unlinkSync(pkgPath)
console.log('[entrify]', pkgPath, 'deleted!')
})
} | javascript | {
"resource": ""
} |
q36805 | indexTemplate | train | function indexTemplate(format, data) {
if (format === 'cjs') {
return `module.exports = require('${data.main}')`
}
if (format === 'esm') {
return `import ${data.name} from '${data.main}'
export default ${data.name}`
}
} | javascript | {
"resource": ""
} |
q36806 | camelize | train | function camelize(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w)/g, (letter, index) => {
return index === 0 ? letter.toLowerCase() : letter.toUpperCase()
}).replace(/[\s\-_]+/g, '')
} | javascript | {
"resource": ""
} |
q36807 | getOperationResponseHeaders | train | function getOperationResponseHeaders(operation) {
var headers = [];
if (operation) {
_.each(operation.responses, function(response, responseCode) {
// Convert responseCode to a numeric value for sorting ("default" comes last)
responseCode = parseInt(responseCode) || 999;
_.each(response.headers, function(header, name) {
// We only care about headers that have a default value defined
if (header.default !== undefined) {
headers.push({
order: responseCode,
name: name.toLowerCase(),
value: header.default
});
}
});
});
}
return _.sortBy(headers, 'order');
} | javascript | {
"resource": ""
} |
q36808 | cast | train | function cast(string) {
var result = String(string);
switch (result) {
case 'null':
result = null;
break;
case 'true':
case 'false':
result = result === 'true';
break;
default:
if (String(parseInt(result, 10)) === result) {
result = parseInt(result, 10);
} else if (String(parseFloat(result)) === result) {
result = parseFloat(result);
}
break;
}
return result === '' ? true : result;
} | javascript | {
"resource": ""
} |
q36809 | train | function (srcpath) {
return fs.readdirSync(srcpath).filter(function(file) {
return fs.statSync(path.join(srcpath, file)).isDirectory();
});
} | javascript | {
"resource": ""
} | |
q36810 | train | function (csprojFilePath, success, error) {
var parser = new xml2js.Parser(),
projectGuid;
fs.readFile(csprojFilePath, function(err, data) {
if (typeof(data) !== 'undefined') {
parser.parseString(data, function (err, result) {
if (typeof(result) !== 'undefined') {
projectGuid = JSON.stringify(result.Project.PropertyGroup[0].ProjectGuid[0].toString());
projectGuid = projectGuid.replace(/"/g, '');
success(projectGuid);
} else {
error(err);
}
});
} else {
error(err);
}
});
} | javascript | {
"resource": ""
} | |
q36811 | train | function () {
fs.writeFile(solutionFile, solutionFileContents, function(err) {
if (err) {
grunt.fail.warning('Failed to update solution file.');
}
done();
});
} | javascript | {
"resource": ""
} | |
q36812 | storeActors | train | function storeActors() {
test.actorsStored = 0;
for (var i = 0; i < test.actorsInfo.length; i++) {
test.actor.set('ID', null);
test.actor.set('name', test.actorsInfo[i][0]);
test.actor.set('born', test.actorsInfo[i][1]);
test.actor.set('isMale', test.actorsInfo[i][2]);
storeBeingTested.putModel(test.actor, actorStored);
}
} | javascript | {
"resource": ""
} |
q36813 | actorStored | train | function actorStored(model, error) {
if (typeof error != 'undefined') {
callback(error);
return;
}
if (++test.actorsStored >= test.actorsInfo.length) {
getAllActors();
}
} | javascript | {
"resource": ""
} |
q36814 | getAllActors | train | function getAllActors() {
try {
storeBeingTested.getList(test.list, {}, function (list, error) {
if (typeof error != 'undefined') {
callback(error);
return;
}
test.shouldBeTrue(list._items.length == 20, '20');
getTomHanks();
});
}
catch (err) {
callback(err);
}
} | javascript | {
"resource": ""
} |
q36815 | getTomHanks | train | function getTomHanks() {
try {
storeBeingTested.getList(test.list, {name: "Tom Hanks"}, function (list, error) {
if (typeof error != 'undefined') {
callback(error);
return;
}
test.shouldBeTrue(list._items.length == 1, ('1 not ' + list._items.length));
getD();
});
}
catch (err) {
callback(err);
}
} | javascript | {
"resource": ""
} |
q36816 | getAlphabetical | train | function getAlphabetical() {
try {
storeBeingTested.getList(test.list, {}, {name: 1}, function (list, error) {
if (typeof error != 'undefined') {
callback(error);
return;
}
// Verify each move returns true when move succeeds
test.shouldBeTrue(list.moveFirst(), 'moveFirst');
test.shouldBeTrue(!list.movePrevious(), 'movePrevious');
test.shouldBeTrue(list.get('name') == 'Al Pacino', 'AP');
test.shouldBeTrue(list.moveLast(), 'moveLast');
test.shouldBeTrue(!list.moveNext(), 'moveNext');
test.shouldBeTrue(list.get('name') == 'Tom Hanks', 'TH');
callback(true);
});
}
catch (err) {
callback(err);
}
} | javascript | {
"resource": ""
} |
q36817 | storeStooges | train | function storeStooges() {
self.log(self.oldStoogesFound);
self.log(self.oldStoogesKilled);
spec.integrationStore.putModel(self.moe, stoogeStored);
spec.integrationStore.putModel(self.larry, stoogeStored);
spec.integrationStore.putModel(self.shemp, stoogeStored);
} | javascript | {
"resource": ""
} |
q36818 | stoogeRetrieved | train | function stoogeRetrieved(model, error) {
if (typeof error != 'undefined') {
callback(error);
return;
}
self.stoogesRetrieved.push(model);
if (self.stoogesRetrieved.length == 3) {
self.shouldBeTrue(true,'here');
// Now we have stored and retrieved (via IDs into new objects). So verify the stooges made it
self.shouldBeTrue(self.stoogesRetrieved[0] !== self.moe && // Make sure not a reference but a copy
self.stoogesRetrieved[0] !== self.larry && self.stoogesRetrieved[0] !== self.shemp,'copy');
var s = []; // get list of names to see if all stooges made it
for (var i = 0; i < 3; i++) s.push(self.stoogesRetrieved[i].get('name'));
self.log(s);
self.shouldBeTrue(contains(s, 'Moe') && contains(s, 'Larry') && contains(s, 'Shemp'));
// Replace Shemp with Curly
var didPutCurly = false;
for (i = 0; i < 3; i++) {
if (self.stoogesRetrieved[i].get('name') == 'Shemp') {
didPutCurly = true;
self.stoogesRetrieved[i].set('name', 'Curly');
try {
spec.integrationStore.putModel(self.stoogesRetrieved[i], stoogeChanged);
}
catch (err) {
callback(err);
}
}
}
if (!didPutCurly) {
callback(Error("Can't find Shemp!"));
}
}
} | javascript | {
"resource": ""
} |
q36819 | stoogeChanged | train | function stoogeChanged(model, error) {
if (typeof error != 'undefined') {
callback(error);
return;
}
self.shouldBeTrue(model.get('name') == 'Curly','Curly');
var curly = new self.Stooge();
curly.set('id', model.get('id'));
try {
spec.integrationStore.getModel(curly, storeChangedShempToCurly);
}
catch (err) {
callback(err);
}
} | javascript | {
"resource": ""
} |
q36820 | storeChangedShempToCurly | train | function storeChangedShempToCurly(model, error) {
if (typeof error != 'undefined') {
callback(error);
return;
}
self.shouldBeTrue(model.get('name') == 'Curly','Curly');
// Now test delete
self.deletedModelId = model.get('id'); // Remember this
spec.integrationStore.deleteModel(model, stoogeDeleted);
} | javascript | {
"resource": ""
} |
q36821 | stoogeDeleted | train | function stoogeDeleted(model, error) {
if (typeof error != 'undefined') {
callback(error);
return;
}
// model parameter is what was deleted
self.shouldBeTrue(undefined === model.get('id')); // ID removed
self.shouldBeTrue(model.get('name') == 'Curly'); // the rest remains
// Is it really dead?
var curly = new self.Stooge();
curly.set('id', self.deletedModelId);
spec.integrationStore.getModel(curly, hesDeadJim);
} | javascript | {
"resource": ""
} |
q36822 | hesDeadJim | train | function hesDeadJim(model, error) {
if (typeof error != 'undefined') {
if ((error != 'Error: id not found in store') && (error != 'Error: model not found in store')) {
callback(error);
return;
}
} else {
callback(Error('no error deleting stooge when expected'));
return;
}
// Skip List test if subclass can't do
if (!spec.integrationStore.getServices().canGetList) {
callback(true);
} else {
// Now create a list from the stooge store
var list = new List(new self.Stooge());
try {
spec.integrationStore.getList(list, {}, {name:1}, listReady);
}
catch (err) {
callback(err);
}
}
} | javascript | {
"resource": ""
} |
q36823 | generateDocs | train | function generateDocs(specjs) {
var docs = GENERATE_MODULE(specjs.MODULE, '');
GENERATE_TYPE = (function(enums) {
return function(type) {
return (_.contains(enums, type) ? ('Enum ' + type) : type);
}
})(_.keys(specjs.ENUMS_BY_GROUP));
docs = _.reduce(specjs.METHODS, function(memo, methodSpec, methodName) {
return memo += GENERATE_METHOD(methodName, methodSpec);
}, docs);
docs = _.reduce(specjs.ENUMS, function(memo, enumSpec, enumName) {
return memo += GENERATE_ENUM(enumName, enumSpec);
}, docs);
if (_.isEmpty(specjs.CLASSGROUPS)) {
docs += GENERATE_CLASSES(specjs.CLASSES);
} else {
docs += GENERATE_MODULE('common', '');
var grouped = _.flatten(_.pluck(_.values(specjs.CLASSGROUPS), 'classes'));
var ungrouped = _.difference(_.keys(specjs.CLASSES), grouped);
docs += GENERATE_CLASSES(_.pick(specjs.CLASSES, ungrouped), 'common');
_.each(specjs.CLASSGROUPS, function(groupSpec, groupName) {
docs += GENERATE_CLASSES(_.pick(specjs.CLASSES, groupSpec.classes), groupName);
});
// TODO: figure out why yuidoc won't associate the class with the right module if module definitions are interspersed
_.each(specjs.CLASSGROUPS, function(groupSpec, groupName) {
docs += GENERATE_MODULE(groupName, groupSpec.description);
});
}
return docs;
} | javascript | {
"resource": ""
} |
q36824 | GENERATE_CLASSES | train | function GENERATE_CLASSES(classes, parent) {
return _.reduce(classes, function(memo, classSpec, className) {
return memo
+ GENERATE_CLASS(className, classSpec.description, parent, classSpec.parent)
+ _.reduce(classSpec.methods, function(memo, methodSpec, methodName) {
return memo += GENERATE_METHOD(methodName, methodSpec, className);
}, '')
+ _.reduce(classSpec.variables, function(memo, variableSpec, variableName) {
return memo += GENERATE_VAR(variableName, variableSpec, className);
}, '')
+ _.reduce(classSpec.enums, function(memo, enumSpec, enumName) {
return memo += GENERATE_ENUM(enumName, enumSpec, className);
}, '');
}, '');
} | javascript | {
"resource": ""
} |
q36825 | GENERATE_CLASS | train | function GENERATE_CLASS(name, description, namespace, parent) {
return GENERATE_DOC(description + '\n'
+ '@class ' + name + '\n'
+ (namespace ? ('@module ' + namespace + '\n') : '')
/*
TODO: leave out until figure out what swig does with inheritance
+ (parent ? ('@extends ' + parent + '\n') : '')
*/
);
} | javascript | {
"resource": ""
} |
q36826 | GENERATE_ENUM | train | function GENERATE_ENUM(name, spec, parent) {
return GENERATE_DOC(spec.description + '\n'
+ '@property ' + name + '\n'
+ '@type Enum ' + spec.type + '\n'
+ '@for ' + (parent ? parent : 'common') + '\n');
} | javascript | {
"resource": ""
} |
q36827 | GENERATE_VAR | train | function GENERATE_VAR(name, spec, parent) {
return GENERATE_DOC(spec.description + '\n'
+ '@property ' + name + '\n'
+ '@type ' + spec.type + '\n'
+ '@for ' + parent + '\n');
} | javascript | {
"resource": ""
} |
q36828 | train | function(lDigits, rDigits) {
var difference = [];
// assert: lDigits.length >= rDigits.length
var carry = 0, i;
for (i = 0; i < rDigits.length; i += 1) {
difference[i] = lDigits[i] - rDigits[i] + carry;
if (difference[i] < 0) {
difference[i] += 2;
carry = -1;
}
else {
carry = 0;
}
}
for (; i < lDigits.length; i += 1) {
difference[i] = lDigits[i] + carry;
if (difference[i] < 0) {
difference[i] += 2;
carry = -1;
}
else {
carry = 0;
}
}
if (carry !== 0) {
throw new Error('never goes here');
}
return difference;
} | javascript | {
"resource": ""
} | |
q36829 | train | function(normalizedLeft, normalizedRight) {
if (normalizedLeft.length !== normalizedRight.length) {
return normalizedLeft.length - normalizedRight.length;
}
for (var i = normalizedLeft.length - 1; i >= 0; i -= 1) {
if (normalizedLeft[i] !== normalizedRight[i]) {
return normalizedLeft[i] - normalizedRight[i];
}
}
return 0;
} | javascript | {
"resource": ""
} | |
q36830 | SocketProxy | train | function SocketProxy() {
// the socket we are paired with
this.pair = null;
// internal sockets have fd -1
this._handle = {fd: -1};
// mimic a remote address / remote port
this.remoteAddress = '0.0.0.0';
this.remotePort = '0';
// give the client some time to listen
// for the connect event
function onNextTick() {
this.emit('connect');
}
process.nextTick(onNextTick.bind(this));
} | javascript | {
"resource": ""
} |
q36831 | gatherPopulateParams | train | function gatherPopulateParams (populate, pointers, model, deepPath) {
var modelName = model.modelName;
var paths = model.schema.paths;
var path = '';
var options;
var params;
var ref;
var deep = false;
while (deepPath.length) {
path += (path ? '.' : '')+deepPath.shift();
options = paths[path] && (
paths[path].caster && paths[path].caster.options
|| paths[path].options
);
if (!options) {
continue;
}
params = pointers[path] || (pointers[path] = {});
ref = options.ref || options.type[0] && options.type[0].ref;
if (!ref) {
if (selectPointers(params)) {
deep = true;
}
continue;
}
if (!params.path) {
params.path = path;
params.model = ref;
params.populate = [];
params.pointers = {};
populate.push(params);
}
if (gatherPopulateParams(
params.populate,
params.pointers,
model.model(ref),
deepPath
)) {
deep = true;
}
if (selectPointers(params)) {
deep = true;
}
}
return deep;
} | javascript | {
"resource": ""
} |
q36832 | selectPointers | train | function selectPointers (params) {
if (params.pointers) {
delete params.pointers['-_id'];
params.select = Object.keys(params.pointers).join(' ');
} else {
delete params.select;
}
return params.select;
} | javascript | {
"resource": ""
} |
q36833 | firstBite | train | function firstBite(dir) {
targetDir = dir || path.join(__dirname, '../../..');
if (targetDir.substring(targetDir.length - 1) === '/') {
targetDir = targetDir.substring(0, targetDir.length - 1);
}
} | javascript | {
"resource": ""
} |
q36834 | eventuallyEqual | train | function eventuallyEqual(promise, expected, done) {
all([
promise.should.be.fulfilled,
promise.should.eventually.deep.equal(expected)
], done);
} | javascript | {
"resource": ""
} |
q36835 | eventuallyRejectedWith | train | function eventuallyRejectedWith(promise, expected, done) {
all([
promise.should.be.rejectedWith(expected)
], done);
} | javascript | {
"resource": ""
} |
q36836 | train | function (updated) {
// When the stream passes a new values, save a reference to it and call
// the compute's internal `updated` method (which ultimately calls `get`)
streamHandler = function (val) {
lastValue = val;
updated();
};
unsubscribe = valueStream[on](streamHandler);
} | javascript | {
"resource": ""
} | |
q36837 | setRoot | train | function setRoot(mountpath) {
// mount to root if not mountpath
let root=mountpath?mountpath:"";
// add leading slash if needed
root=root.match(/^\/.*/)?root:`/${root}`;
// chop off trailing slash
root=root.match(/^.*\/$/)?root.substring(0,root.length-1):root;
// if root is just slash then mountpath is empty (load on root of site)
root=root.length>1?root:"";
return root;
} | javascript | {
"resource": ""
} |
q36838 | popupClick | train | function popupClick(e) {
var editor = this,
popup = e.data.popup,
target = e.target;
// Check for message and prompt popups
if (popup === popups.msg || $(popup).hasClass(PROMPT_CLASS))
return;
// Get the button info
var buttonDiv = $.data(popup, BUTTON),
buttonName = $.data(buttonDiv, BUTTON_NAME),
button = buttons[buttonName],
command = button.command,
value,
useCSS = editor.options.useCSS;
// Get the command value
if (buttonName == "font")
// Opera returns the fontfamily wrapped in quotes
value = target.style.fontFamily.replace(/"/g, "");
else if (buttonName == "size") {
if (target.tagName == "DIV")
target = target.children[0];
value = target.innerHTML;
}
else if (buttonName == "style")
value = "<" + target.tagName + ">";
else if (buttonName == "color")
value = hex(target.style.backgroundColor);
else if (buttonName == "highlight") {
value = hex(target.style.backgroundColor);
if (ie) command = 'backcolor';
else useCSS = true;
}
// Fire the popupClick event
var data = {
editor: editor,
button: buttonDiv,
buttonName: buttonName,
popup: popup,
popupName: button.popupName,
command: command,
value: value,
useCSS: useCSS
};
if (button.popupClick && button.popupClick(e, data) === false)
return;
// Execute the command
if (data.command && !execCommand(editor, data.command, data.value, data.useCSS, buttonDiv))
return false;
// Hide the popup and focus the editor
hidePopups();
focus(editor);
} | javascript | {
"resource": ""
} |
q36839 | createPopup | train | function createPopup(popupName, options, popupTypeClass, popupContent, popupHover) {
// Check if popup already exists
if (popups[popupName])
return popups[popupName];
// Create the popup
var $popup = $(DIV_TAG)
.hide()
.addClass(POPUP_CLASS)
.appendTo("body");
// Add the content
// Custom popup
if (popupContent)
$popup.html(popupContent);
// Color
else if (popupName == "color") {
var colors = options.colors.split(" ");
if (colors.length < 10)
$popup.width("auto");
$.each(colors, function(idx, color) {
$(DIV_TAG).appendTo($popup)
.css(BACKGROUND_COLOR, "#" + color);
});
popupTypeClass = COLOR_CLASS;
}
// Font
else if (popupName == "font")
$.each(options.fonts.split(","), function(idx, font) {
$(DIV_TAG).appendTo($popup)
.css("fontFamily", font)
.html(font);
});
// Size
else if (popupName == "size")
$.each(options.sizes.split(","), function(idx, size) {
$(DIV_TAG).appendTo($popup)
.html("<font size=" + size + ">" + size + "</font>");
});
// Style
else if (popupName == "style")
$.each(options.styles, function(idx, style) {
$(DIV_TAG).appendTo($popup)
.html(style[1] + style[0] + style[1].replace("<", "</"));
});
// URL
else if (popupName == "url") {
$popup.html('Enter URL:<br><input type=text value="http://" size=35><br><input type=button value="Submit">');
popupTypeClass = PROMPT_CLASS;
}
// Paste as Text
else if (popupName == "pastetext") {
$popup.html('Paste your content here and click submit.<br /><textarea cols=40 rows=3></textarea><br /><input type=button value=Submit>');
popupTypeClass = PROMPT_CLASS;
}
// Add the popup type class name
if (!popupTypeClass && !popupContent)
popupTypeClass = LIST_CLASS;
$popup.addClass(popupTypeClass);
// Add the unselectable attribute to all items
if (ie) {
$popup.attr(UNSELECTABLE, "on")
.find("div,font,p,h1,h2,h3,h4,h5,h6")
.attr(UNSELECTABLE, "on");
}
// Add the hover effect to all items
if ($popup.hasClass(LIST_CLASS) || popupHover === true)
$popup.children().hover(hoverEnter, hoverLeave);
// Add the popup to the array and return it
popups[popupName] = $popup[0];
return $popup[0];
} | javascript | {
"resource": ""
} |
q36840 | disable | train | function disable(editor, disabled) {
// Update the textarea and save the state
if (disabled) {
editor.$area.attr(DISABLED, DISABLED);
editor.disabled = true;
}
else {
editor.$area.removeAttr(DISABLED);
delete editor.disabled;
}
// Switch the iframe into design mode.
// ie6 does not support designMode.
// ie7 & ie8 do not properly support designMode="off".
try {
if (ie) editor.doc.body.contentEditable = !disabled;
else editor.doc.designMode = !disabled ? "on" : "off";
}
// Firefox 1.5 throws an exception that can be ignored
// when toggling designMode from off to on.
catch (err) {}
// Enable or disable the toolbar buttons
refreshButtons(editor);
} | javascript | {
"resource": ""
} |
q36841 | execCommand | train | function execCommand(editor, command, value, useCSS, button) {
// Restore the current ie selection
restoreRange(editor);
// Set the styling method
if (!ie) {
if (useCSS === undefined || useCSS === null)
useCSS = editor.options.useCSS;
editor.doc.execCommand("styleWithCSS", 0, useCSS.toString());
}
// Execute the command and check for error
var success = true, description;
if (ie && command.toLowerCase() == "inserthtml")
getRange(editor).pasteHTML(value);
else {
try { success = editor.doc.execCommand(command, 0, value || null); }
catch (err) { description = err.description; success = false; }
if (!success) {
if ("cutcopypaste".indexOf(command) > -1)
showMessage(editor, "For security reasons, your browser does not support the " +
command + " command. Try using the keyboard shortcut or context menu instead.",
button);
else
showMessage(editor,
(description ? description : "Error executing the " + command + " command."),
button);
}
}
// Enable the buttons
refreshButtons(editor);
return success;
} | javascript | {
"resource": ""
} |
q36842 | focus | train | function focus(editor) {
setTimeout(function() {
if (sourceMode(editor)) editor.$area.focus();
else editor.$frame[0].contentWindow.focus();
refreshButtons(editor);
}, 0);
} | javascript | {
"resource": ""
} |
q36843 | hidePopups | train | function hidePopups() {
$.each(popups, function(idx, popup) {
$(popup)
.hide()
.unbind(CLICK)
.removeData(BUTTON);
});
} | javascript | {
"resource": ""
} |
q36844 | imagesPath | train | function imagesPath() {
var cssFile = "jquery.cleditor.css",
href = $("link[href$='" + cssFile +"']").attr("href");
return href.substr(0, href.length - cssFile.length) + "images/";
} | javascript | {
"resource": ""
} |
q36845 | refreshButtons | train | function refreshButtons(editor) {
// Webkit requires focus before queryCommandEnabled will return anything but false
if (!iOS && $.browser.webkit && !editor.focused) {
editor.$frame[0].contentWindow.focus();
window.focus();
editor.focused = true;
}
// Get the object used for checking queryCommandEnabled
var queryObj = editor.doc;
if (ie) queryObj = getRange(editor);
// Loop through each button
var inSourceMode = sourceMode(editor);
$.each(editor.$toolbar.find("." + BUTTON_CLASS), function(idx, elem) {
var $elem = $(elem),
button = $.cleditor.buttons[$.data(elem, BUTTON_NAME)],
command = button.command,
enabled = true;
// Determine the state
if (editor.disabled)
enabled = false;
else if (button.getEnabled) {
var data = {
editor: editor,
button: elem,
buttonName: button.name,
popup: popups[button.popupName],
popupName: button.popupName,
command: button.command,
useCSS: editor.options.useCSS
};
enabled = button.getEnabled(data);
if (enabled === undefined)
enabled = true;
}
else if (((inSourceMode || iOS) && button.name != "source") ||
(ie && (command == "undo" || command == "redo")))
enabled = false;
else if (command && command != "print") {
if (ie && command == "hilitecolor")
command = "backcolor";
// IE does not support inserthtml, so it's always enabled
if (!ie || command != "inserthtml") {
try {enabled = queryObj.queryCommandEnabled(command);}
catch (err) {enabled = false;}
}
}
// Enable or disable the button
if (enabled) {
$elem.removeClass(DISABLED_CLASS);
$elem.removeAttr(DISABLED);
}
else {
$elem.addClass(DISABLED_CLASS);
$elem.attr(DISABLED, DISABLED);
}
});
} | javascript | {
"resource": ""
} |
q36846 | selectedHTML | train | function selectedHTML(editor) {
restoreRange(editor);
var range = getRange(editor);
if (ie)
return range.htmlText;
var layer = $("<layer>")[0];
layer.appendChild(range.cloneContents());
var html = layer.innerHTML;
layer = null;
return html;
} | javascript | {
"resource": ""
} |
q36847 | selectedText | train | function selectedText(editor) {
restoreRange(editor);
if (ie) return getRange(editor).text;
return getSelection(editor).toString();
} | javascript | {
"resource": ""
} |
q36848 | showMessage | train | function showMessage(editor, message, button) {
var popup = createPopup("msg", editor.options, MSG_CLASS);
popup.innerHTML = message;
showPopup(editor, popup, button);
} | javascript | {
"resource": ""
} |
q36849 | showPopup | train | function showPopup(editor, popup, button) {
var offset, left, top, $popup = $(popup);
// Determine the popup location
if (button) {
var $button = $(button);
offset = $button.offset();
left = --offset.left;
top = offset.top + $button.height();
}
else {
var $toolbar = editor.$toolbar;
offset = $toolbar.offset();
left = Math.floor(($toolbar.width() - $popup.width()) / 2) + offset.left;
top = offset.top + $toolbar.height() - 2;
}
// Position and show the popup
hidePopups();
$popup.css({left: left, top: top})
.show();
// Assign the popup button and click event handler
if (button) {
$.data(popup, BUTTON, button);
$popup.bind(CLICK, {popup: popup}, $.proxy(popupClick, editor));
}
// Focus the first input element if any
setTimeout(function() {
$popup.find(":text,textarea").eq(0).focus().select();
}, 100);
} | javascript | {
"resource": ""
} |
q36850 | updateFrame | train | function updateFrame(editor, checkForChange) {
var code = editor.$area.val(),
options = editor.options,
updateFrameCallback = options.updateFrame,
$body = $(editor.doc.body);
// Check for textarea change to avoid unnecessary firing
// of potentially heavy updateFrame callbacks.
if (updateFrameCallback) {
var sum = checksum(code);
if (checkForChange && editor.areaChecksum == sum)
return;
editor.areaChecksum = sum;
}
// Convert the textarea source code into iframe html
var html = updateFrameCallback ? updateFrameCallback(code) : code;
// Prevent script injection attacks by html encoding script tags
html = html.replace(/<(?=\/?script)/ig, "<");
// Update the iframe checksum
if (options.updateTextArea)
editor.frameChecksum = checksum(html);
// Update the iframe and trigger the change event
if (html != $body.html()) {
$body.html(html);
$(editor).triggerHandler(CHANGE);
}
} | javascript | {
"resource": ""
} |
q36851 | updateTextArea | train | function updateTextArea(editor, checkForChange) {
var html = $(editor.doc.body).html(),
options = editor.options,
updateTextAreaCallback = options.updateTextArea,
$area = editor.$area;
// Check for iframe change to avoid unnecessary firing
// of potentially heavy updateTextArea callbacks.
if (updateTextAreaCallback) {
var sum = checksum(html);
if (checkForChange && editor.frameChecksum == sum)
return;
editor.frameChecksum = sum;
}
// Convert the iframe html into textarea source code
var code = updateTextAreaCallback ? updateTextAreaCallback(html) : html;
// Update the textarea checksum
if (options.updateFrame)
editor.areaChecksum = checksum(code);
// Update the textarea and trigger the change event
if (code != $area.val()) {
$area.val(code);
$(editor).triggerHandler(CHANGE);
}
} | javascript | {
"resource": ""
} |
q36852 | send | train | function send(err, reply, cb) {
// invoke before function, used to end a slowlog
// timer before sending output
if(this.before) this.before();
if(this.cb) {
return this.cb(err, reply);
}
this.conn.write(err || reply, cb);
} | javascript | {
"resource": ""
} |
q36853 | genCap | train | function genCap(point, ux, uy, v1i, v2i, pushVert, pushIndices) {
if (!point.cap) {
genRoundedCap(point, ux, uy, v1i, v2i, pushVert, pushIndices);
} else {
switch (point.cap.type) {
case LineCaps.LINECAP_TYPE_ARROW:
genArrowCap(point, ux, uy, v1i, v2i, pushVert, pushIndices);
break;
case LineCaps.LINECAP_TYPE_ROUNDED:
genRoundedCap(point, ux, uy, v1i, v2i, pushVert, pushIndices);
break;
case LineCaps.LINECAP_TYPE_HALF_ARROW_A:
genHalfArrowACap(point, ux, uy, v1i, v2i, pushVert, pushIndices);
break;
default:
// default to no cap
break;
}
}
} | javascript | {
"resource": ""
} |
q36854 | train | function(db) {
var views_uuid = uuid();
debug.assert(views_uuid).is('uuid');
return db.query('CREATE SEQUENCE views_seq')
.query(['CREATE TABLE IF NOT EXISTS views (',
" id uuid PRIMARY KEY NOT NULL default uuid_generate_v5('"+views_uuid+"', nextval('views_seq'::regclass)::text),",
' types_id uuid REFERENCES types,',
' type text NOT NULL,',
' name text NOT NULL,',
' meta json NOT NULL,',
' active BOOLEAN NOT NULL DEFAULT TRUE,',
' created timestamptz NOT NULL default now(),',
' modified timestamptz NOT NULL default now()',
')'
].join('\n'))
.query('ALTER SEQUENCE views_seq OWNED BY views.id')
.query('CREATE INDEX views_types_id ON views (types_id)')
.query('CREATE INDEX views_types_id_name ON views (types_id,name)')
.query('CREATE INDEX views_type ON views (type)')
.query('CREATE INDEX views_type_name ON views (type,name)')
.query('CREATE UNIQUE INDEX ON views USING btree(types_id, name);')
.query('CREATE TRIGGER views_modified BEFORE UPDATE ON views FOR EACH ROW EXECUTE PROCEDURE moddatetime (modified)')
;
} | javascript | {
"resource": ""
} | |
q36855 | train | function (target, eventName, listener, useCapture) {
var ver = System.utils.UserAgent.IE.getVersion();
if (is(target, System.EventEmitter)) {
target.on(eventName, listener, useCapture);
} else if ((ver != -1 && ver <= 8) || is(target, Element)) {
if (ver != -1 && ver < 11) {
target.attachEvent("on" + eventName, listener, useCapture);
} else target.addEventListener(eventName, listener, useCapture);
}
return target;
} | javascript | {
"resource": ""
} | |
q36856 | combineRules | train | async function combineRules(rulesList) {
return Object.keys(rulesList)
.reduce(async (collection, definitions) => {
const isEnabled = rulesList[definitions];
let { default: rules } = await import(`../rules/${definitions}`);
if (!isEnabled) rules = await disableRules(rules);
const previousRules = await collection;
return {
...previousRules,
...rules,
};
}, Promise.resolve({}));
} | javascript | {
"resource": ""
} |
q36857 | reqToJSON | train | function reqToJSON (req, additional) {
additional = additional || []
if (additional === true) {
additional = [
'rawHeaders',
'rawTrailers',
// express/koa
'fresh',
'cookies',
'ip',
'ips',
'stale',
'subdomains'
]
}
var keys = [
'body',
'headers',
'httpVersion',
'method',
'trailers',
'url',
'socket.remoteAddress',
// express/koa
'originalUrl',
'params',
'query'
].concat(additional).sort()
var json = pick(req, keys)
defaults(json, getParsedUrl(req))
return json
} | javascript | {
"resource": ""
} |
q36858 | Join | train | function Join(name) {
this.name = name;
this.criteria = null;
this.table = null;
this.map = null;
this.type = this.ONE_TO_ONE;
this.default = false;
} | javascript | {
"resource": ""
} |
q36859 | compileDEP | train | function compileDEP( project, src, watch ) {
const
moduleName = src.name(),
depFilename = Util.replaceExtension( moduleName, '.dep' );
if ( !project.srcOrLibPath( depFilename ) ) return '';
const depFile = new Source( project, depFilename );
let code = '';
try {
const depJSON = ToloframeworkPermissiveJson.parse( depFile.read() );
code = processAttributeVar( project, depJSON, watch, depFile.getAbsoluteFilePath() );
} catch ( ex ) {
Fatal.fire( `Unable to parse JSON dependency file!\n${ex}`, depFile.getAbsoluteFilePath() );
}
/*
* List of files to watch. If one of those files is newer
* that the JS file, we have to recompile.
*/
src.tag( 'watch', watch );
return code;
} | javascript | {
"resource": ""
} |
q36860 | processAttributeVar | train | function processAttributeVar( project, depJSON, watch, depAbsPath ) {
if ( typeof depJSON.var === 'undefined' ) return '';
let
head = 'const GLOBAL = {',
firstItem = true;
Object.keys( depJSON.var ).forEach( function forEachVarName( varName ) {
const
varFilename = depJSON.var[ varName ],
folder = Path.dirname( depAbsPath ),
srcVar = project.srcOrLibPath( Path.join( folder, varFilename ) ) ||
project.srcOrLibPath( `mod/${varFilename}` ) ||
project.srcOrLibPath( varFilename );
if ( !srcVar ) {
Fatal.fire(
`Unable to find dendency file "${varFilename}" nor "mod/${varFilename}"!`,
depAbsPath
);
}
Util.pushUnique( watch, srcVar );
if ( firstItem ) {
firstItem = false;
} else {
head += ',';
}
const source = new Source( project, srcVar );
head += `\n ${JSON.stringify(varName)}: ${JSON.stringify(source.read())}`;
} );
head += "};\n";
return head;
} | javascript | {
"resource": ""
} |
q36861 | filtered | train | function filtered(js) {
return js.substr(1).split('|').reduce(function(js, filter){
var parts = filter.split(':')
, name = parts.shift()
, args = parts.shift() || '';
if (args) args = ', ' + args;
return 'filters.' + name + '(' + js + args + ')';
});
} | javascript | {
"resource": ""
} |
q36862 | resolveInclude | train | function resolveInclude(name, filename) {
var path = join(dirname(filename), name);
var ext = extname(name);
if (!ext) path += '.ejs';
return path;
} | javascript | {
"resource": ""
} |
q36863 | suiteFinished | train | function suiteFinished(suite, status, results) {
suite.finished = true;
suite.status = status;
suite.duration = new Date() - suite.startTime;
suite.results = results;
delete suite.startTime;
if (suite.index == finishedIndex) {
for (var i = finishedIndex; i < suites.length; i++) {
if (suites[i].finished) {
while(suites[i].queuedTestResults.length) {
output.testDone(suites[i], suites[i].queuedTestResults.shift());
}
output.suiteDone(suites[i]);
}
else {
break;
}
}
finishedIndex = i;
}
if (finishedIndex >= suites.length) {
output.allDone();
}
startNextSuite();
} | javascript | {
"resource": ""
} |
q36864 | train | function ( config, actual ) {
// In this way, if any topic declare the compilerOptions this will not
// include in the tsconfig.json
if ( actual.compilerOptions !== undefined ) {
if ( config.compilerOptions === undefined ) {
// Attach an empty object
config.compilerOptions = {};
}
// In the case that a descendant set a option already set,
// the option will set at the value of descendant.
if ( actual.compilerOptions.module !== undefined ) {
config.compilerOptions.module = actual.compilerOptions.module;
} if ( actual.compilerOptions.target !== undefined ) {
config.compilerOptions.target = actual.compilerOptions.target;
} if ( actual.compilerOptions.moduleResolution !== undefined ) {
config.compilerOptions.moduleResolution =
actual.compilerOptions.moduleResolution;
} if ( actual.compilerOptions.noImplicitAny !== undefined ) {
config.compilerOptions.noImplicitAny =
actual.compilerOptions.noImplicitAny;
} if ( actual.compilerOptions.removeComments !== undefined ) {
config.compilerOptions.removeComments =
actual.compilerOptions.removeComments;
} if ( actual.compilerOptions.preserveConstEnums !== undefined ) {
config.compilerOptions.preserveConstEnums =
actual.compilerOptions.preserveConstEnums;
} if ( actual.compilerOptions.outDir !== undefined ) {
config.compilerOptions.outDir =
// Append a slash at the end of path because node return relative path
// but tsconfig want the path with the slah final
relative( actual.compilerOptions.outDir ) + "/";
} if ( actual.compilerOptions.outFile !== undefined ) {
config.compilerOptions.outFile =
relative( actual.compilerOptions.outFile );
} if ( actual.compilerOptions.sourceMap !== undefined ) {
config.compilerOptions.sourceMap =
actual.compilerOptions.sourceMap;
} if ( actual.compilerOptions.declaration !== undefined ) {
config.compilerOptions.declaration =
actual.compilerOptions.declaration;
} if ( actual.compilerOptions.noEmitOnError !== undefined ) {
config.compilerOptions.noEmitOnError =
actual.compilerOptions.noEmitOnError;
} if ( actual.compilerOptions.jsx !== undefined ) {
config.compilerOptions.jsx =
actual.compilerOptions.jsx;
}
} if ( actual.include !== undefined ) {
if ( config.include === undefined ) {
// Attach an empty array
config.include = [];
}
// Push all relative path
config.include = config.include.concat(
// Apply the transformation function
actual.include.map( relative )
);
} if ( actual.exclude !== undefined ) {
config.exclude = actual.exclude;
}
} | javascript | {
"resource": ""
} | |
q36865 | proxy | train | function proxy(req, res) {
var method = req.db[req.cmd]
, args;
// append the request object to the args
// required so that database events can pass
// request and thereby connection information
// when emitting events by key, this allows
// transactional semantics
args = req.args.slice(0).concat(req);
return method.apply(req.db, args);
} | javascript | {
"resource": ""
} |
q36866 | execute | train | function execute(req, res) {
var proxy = req.exec ? req.exec.proxy : this.proxy;
res.send(null, proxy(req, res));
} | javascript | {
"resource": ""
} |
q36867 | train | function (model, values, functionPrefix) {
// for a string, see if it has parameter matches, and if so, try to make the substitutions.
var getValue = function (fromString) {
var matches = fromString.match(/(\${.*?})/g);
if (matches != null) {
for (var i = 0; i < matches.length; i++) {
var val = values[matches[i].substring(2, matches[i].length - 1)] || "";
if (val != null) {
fromString = fromString.replace(matches[i], val);
}
}
}
return fromString;
},
// process one entry.
_one = function (d) {
if (d != null) {
if (_iss(d)) {
return getValue(d);
}
else if (_isf(d) && (functionPrefix == null || (d.name || "").indexOf(functionPrefix) === 0)) {
return d(values);
}
else if (_isa(d)) {
var r = [];
for (var i = 0; i < d.length; i++)
r.push(_one(d[i]));
return r;
}
else if (_iso(d)) {
var s = {};
for (var j in d) {
s[j] = _one(d[j]);
}
return s;
}
else {
return d;
}
}
};
return _one(model);
} | javascript | {
"resource": ""
} | |
q36868 | barbe | train | function barbe(text, arr, data) {
if (!Array.isArray(arr)) {
data = arr;
arr = ["{", "}"];
}
if (!data || data.constructor !== Object) {
return text;
}
arr = arr.map(regexEscape);
let deep = (obj, path) => {
iterateObject(obj, (value, c) => {
path.push(c);
if (typpy(value, Object)) {
deep(value, path);
path.pop();
return;
}
text = text.replace(
new RegExp(arr[0] + path.join(".") + arr[1], "gm")
, typpy(value, Function) ? value : String(value)
);
path.pop();
});
};
deep(data, []);
return text;
} | javascript | {
"resource": ""
} |
q36869 | pad | train | function pad(n, s) {
var before = Array(n + 1).join(' ')
return s.split(/\r\n|\r|\n/)
.map(function(a){ return before + a })
.join('\n')
} | javascript | {
"resource": ""
} |
q36870 | maybeRenderSuite | train | function maybeRenderSuite(signal) { return function(a) {
return a.cata({
Suite: function(){ return Just([signal.path.length, a.name]) }
, Case: Nothing
})
}} | javascript | {
"resource": ""
} |
q36871 | logs | train | function logs(a) {
return a.isIgnored? ''
: a.log.length === 0? ''
: /* otherwise */ '\n' + pad( 2
, '=== Captured logs:\n'
+ a.log.map(function(x){
return faded('- ' + show(x.log))})
.join('\n') + '\n---\n')
} | javascript | {
"resource": ""
} |
q36872 | _filesToFile | train | function _filesToFile (files, target, separator, callback) {
if ("undefined" === typeof files) {
throw new ReferenceError("missing \"files\" argument");
}
else if ("object" !== typeof files || !(files instanceof Array)) {
throw new TypeError("\"files\" argument is not an Array");
}
else if ("undefined" === typeof target) {
throw new ReferenceError("missing \"target\" argument");
}
else if ("string" !== typeof target) {
throw new TypeError("\"target\" argument is not a string");
}
else if ("undefined" === typeof callback && "undefined" === typeof separator) {
throw new ReferenceError("missing \"callback\" argument");
}
else if ("function" !== typeof callback && "function" !== typeof separator) {
throw new TypeError("\"callback\" argument is not a function");
}
else {
const _target = target.trim();
if ("" === _target) {
throw new Error("\"target\" argument is empty");
}
else {
const _callback = "undefined" === typeof callback ? separator : callback;
Promise.resolve().then(() => {
return isFileProm(_target);
}).then((exists) => {
return !exists ? Promise.resolve() : new Promise((resolve, reject) => {
fs.unlink(_target, (err) => {
return err ? reject(err) : resolve();
});
});
}).then(() => {
if (!files.length) {
return new Promise((resolve, reject) => {
fs.writeFile(_target, "", (err) => {
return err ? reject(err) : resolve();
});
});
}
else {
return filesToStreamProm(files, "string" === typeof separator ? separator : " ").then((readStream) => {
return new Promise((resolve, reject) => {
let error = false;
readStream.once("error", (_err) => {
error = true; reject(_err);
}).pipe(fs.createWriteStream(_target, { "flags": "a" }).once("error", (_err) => {
error = true; reject(_err);
}).once("close", () => {
if (!error) {
resolve();
}
}));
});
});
}
}).then(() => {
_callback(null);
}).catch(_callback);
}
}
} | javascript | {
"resource": ""
} |
q36873 | _removeDirectoryContentProm | train | function _removeDirectoryContentProm (contents) {
const content = contents.shift();
return isDirectoryProm(content).then((exists) => {
return exists ? new Promise((resolve, reject) => {
_rmdirp(content, (err) => {
return err ? reject(err) : resolve();
});
}) : new Promise((resolve, reject) => {
unlink(content, (err) => {
return err ? reject(err) : resolve();
});
});
}).then(() => {
return contents.length ? _removeDirectoryContentProm(contents) : Promise.resolve();
});
} | javascript | {
"resource": ""
} |
q36874 | _emptyDirectoryProm | train | function _emptyDirectoryProm (directory) {
return new Promise((resolve, reject) => {
readdir(directory, (err, files) => {
return err ? reject(err) : resolve(files);
});
}).then((files) => {
const result = [];
for (let i = 0; i < files.length; ++i) {
result.push(join(directory, files[i]));
}
return Promise.resolve(result);
}).then((files) => {
return files.length ? _removeDirectoryContentProm(files) : Promise.resolve();
});
} | javascript | {
"resource": ""
} |
q36875 | parseEndTag | train | function parseEndTag(tag, tagName) {
// If no tag name is provided, clean shop
if (!tagName)
var pos = 0;
// Find the closest opened tag of the same type
else {
tagName = tagName.toLowerCase();
for (var pos = stack.length - 1; pos >= 0; pos--)
if (stack[pos] == tagName)
break;
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (var i = stack.length - 1; i >= pos; i--)
results += "</" + stack[i] + ">";
// Remove the open elements from the stack
stack.length = pos;
}
} | javascript | {
"resource": ""
} |
q36876 | Profile | train | function Profile(options) {
this.path = node_path.resolve(profile.resolveHomePath(options.path));
this.schema = options.schema;
this.context = options.context || null;
this.raw_data = {};
this.codec = this._get_codec(options.codec);
this.options = options;
} | javascript | {
"resource": ""
} |
q36877 | train | function(name, force, callback) {
var err = null;
var profiles = this.all();
if (~profiles.indexOf(name)) {
err = 'Profile "' + name + '" already exists.';
} else if (!force && ~RESERVED_PROFILE_NAME.indexOf(name)) {
err = 'Profile name "' + name + '" is reserved by `multi-profile`';
} else if (/^_/.test(name)) {
err = 'Profile name "' + name + '" should not begin with `_`';
} else {
profiles.push(name);
this.attr.set('profiles', profiles);
}
var data = {
err: err,
name: name
};
this.emit('add', data);
callback && callback(err, data);
} | javascript | {
"resource": ""
} | |
q36878 | train | function(name) {
this.profile = trait(Object.create(this.schema), {
context: this.context
});
var profile_dir = this.profile_dir = node_path.join(this.path, name);
if (!fs.isDir(profile_dir)) {
fs.mkdir(profile_dir);
}
var profile_file = this.profile_file = node_path.join(profile_dir, 'config');
if (!fs.isFile(profile_file)) {
fs.write(profile_file, '');
} else {
this.reload();
}
} | javascript | {
"resource": ""
} | |
q36879 | discover | train | function discover(pattern, callback) {
glob(pattern, function (err, filepaths) {
if (err) callback(err);
callback(null, filepaths);
});
} | javascript | {
"resource": ""
} |
q36880 | registerPartials | train | function registerPartials(filepaths, callback) {
async.map(filepaths, registerPartial, function (err) {
if (err) callback(err);
callback(null);
});
} | javascript | {
"resource": ""
} |
q36881 | registerPartial | train | function registerPartial(filepath, callback) {
fs.readFile(filepath, 'utf8', function (err, data) {
if (err) callback(err);
hbs.registerPartial(path.parse(filepath).name, data);
callback(null);
});
} | javascript | {
"resource": ""
} |
q36882 | registerTemplates | train | function registerTemplates(filepaths, callback) {
async.map(filepaths, registerTemplate, function (err, templates) {
if (err) callback(err);
callback(null, templates);
});
} | javascript | {
"resource": ""
} |
q36883 | registerTemplate | train | function registerTemplate(filepath, callback) {
fs.readFile(filepath, 'utf8', function (err, data) {
if (err) callback(err);
callback(null, {
name: path.parse(filepath).name,
template: hbs.compile(data)
});
});
} | javascript | {
"resource": ""
} |
q36884 | satisfies | train | function satisfies(version, range) {
range = range.trim();
// Range '<=99.999.99999' means "all versions", but fails on "2014.10.20-1"
if (range === '<=99.999.99999') return true;
// If semver satisfies, we return true
if (semver.satisfies(version, range)) return true;
// If range is a specific version, return eq
if (semver.valid(range)) return semver.eq(version, range);
if (range.includes('||')) {
// Multiple ranges, "or"
return range.split('||').some(sub => satisfies(version, sub.trim()));
}
if (range.includes(' ')) {
// Multiple ranges, "and"
return range.split(' ')
.map(x => x.trim())
.filter(x => x)
.every(sub => satisfies(version, sub));
}
// Comparison
if (range.startsWith('>=')) {
const sub = range.slice(2).trim();
if (semver.valid(sub)) return semver.gte(version, sub);
} else if (range.startsWith('<=')) {
const sub = range.slice(2).trim();
if (semver.valid(sub)) return semver.lte(version, sub);
} else if (range.startsWith('>')) {
const sub = range.slice(1).trim();
if (semver.valid(sub)) return semver.gt(version, sub);
} else if (range.startsWith('<')) {
const sub = range.slice(1).trim();
if (semver.valid(sub)) return semver.lt(version, sub);
}
console.error(`Unprocessed version/range: ${version}, ${JSON.stringify(range)}`);
return false;
} | javascript | {
"resource": ""
} |
q36885 | explode | train | function explode( target, mappings ){
if (!mappings ){
mappings = target;
target = {};
}
bmoor.iterate( mappings, function( val, mapping ){
bmoor.set( target, mapping, val );
});
return target;
} | javascript | {
"resource": ""
} |
q36886 | mask | train | function mask( obj ){
if ( Object.create ){
var T = function Masked(){};
T.prototype = obj;
return new T();
}else{
return Object.create( obj );
}
} | javascript | {
"resource": ""
} |
q36887 | merge | train | function merge( to ){
var from,
i, c,
m = function( val, key ){
to[ key ] = merge( to[key], val );
};
for( i = 1, c = arguments.length; i < c; i++ ){
from = arguments[i];
if ( to === from ){
continue;
}else if ( to && to.merge ){
to.merge( from );
}else if ( !bmoor.isObject(from) ){
to = from;
}else if ( !bmoor.isObject(to) ){
to = merge( {}, from );
}else{
bmoor.safe( from, m );
}
}
return to;
} | javascript | {
"resource": ""
} |
q36888 | equals | train | function equals( obj1, obj2 ){
var t1 = typeof obj1,
t2 = typeof obj2,
c,
i,
keyCheck;
if ( obj1 === obj2 ){
return true;
}else if ( obj1 !== obj1 && obj2 !== obj2 ){
return true; // silly NaN
}else if ( obj1 === null || obj1 === undefined || obj2 === null || obj2 === undefined ){
return false; // undefined or null
}else if ( obj1.equals ){
return obj1.equals( obj2 );
}else if ( obj2.equals ){
return obj2.equals( obj1 ); // because maybe somene wants a class to be able to equal a simple object
}else if ( t1 === t2 ){
if ( t1 === 'object' ){
if ( bmoor.isArrayLike(obj1) ){
if ( !bmoor.isArrayLike(obj2) ){
return false;
}
if ( (c = obj1.length) === obj2.length ){
for( i = 0; i < c; i++ ){
if ( !equals(obj1[i], obj2[i]) ) {
return false;
}
}
return true;
}
}else if ( !bmoor.isArrayLike(obj2) ){
keyCheck = {};
for( i in obj1 ){
if ( obj1.hasOwnProperty(i) ){
if ( !equals(obj1[i],obj2[i]) ){
return false;
}
keyCheck[i] = true;
}
}
for( i in obj2 ){
if ( obj2.hasOwnProperty(i) ){
if ( !keyCheck && obj2[i] !== undefined ){
return false;
}
}
}
}
}
}
return false;
} | javascript | {
"resource": ""
} |
q36889 | exec | train | function exec (func, context, args) {
switch (args.length) {
case 0: func.call(context); break;
case 1: func.call(context, args[0]); break;
case 2: func.call(context, args[0], args[1]); break;
case 3: func.call(context, args[0], args[1], args[2]); break;
case 4: func.call(context, args[0], args[1], args[2], args[3]); break;
default: func.apply(context, args); break;
}
} | javascript | {
"resource": ""
} |
q36890 | propagate | train | function propagate (parent, prefix) {
var self = this;
if (!parent || typeof parent.emit !== 'function') {
throw new TypeError('"parent" argument must implement an "emit" method');
}
self.parent = parent;
self.parentPrefix = prefix;
return this;
} | javascript | {
"resource": ""
} |
q36891 | hasCompleteEventParams | train | function hasCompleteEventParams(eventType, listener) {
var hasParams = eventType && listener,
isTypeString = typeof eventType === 'string',
isTypeFunction = typeof listener === 'function';
if (!isTypeFunction) {
throw new TypeError(EventDispatcher.TYPE_ERROR);
}
return hasParams && isTypeString && isTypeFunction;
} | javascript | {
"resource": ""
} |
q36892 | Description | train | function Description(def) {
if(typeof def === 'string') {
this.parse(def);
}else if(def
&& typeof def === 'object'
&& typeof def.txt === 'string'
&& typeof def.md === 'string') {
this.md = def.md;
this.txt = def.txt;
}else{
throw new Error('invalid value for description');
}
} | javascript | {
"resource": ""
} |
q36893 | useYarn | train | function useYarn(setYarn) {
if (typeof setYarn !== "undefined") {
allowYarn = setYarn;
}
if (typeof allowYarn !== "undefined") {
return allowYarn;
}
return getYarnVersionIfAvailable() ? true : false;
} | javascript | {
"resource": ""
} |
q36894 | _load | train | function _load(file, defaultConfig, dump) {
const f = normalize(file);
const b = f.base;
const p = f.profile;
const ext = f.ext;
if (ext) {
const p = b + ext;
let r = loadSpecific(b, '.js', p, defaultConfig, dump);
if (r) return r;
if (defaultConfig) return defaultConfig;
throw new Error('file not found: ' + p);
}
let r = loadSpecific(b, '.yml', p, defaultConfig, dump);
if (r) return r;
r = loadSpecific(b, '.yaml', p, defaultConfig, dump);
if (r) return r;
r = loadSpecific(b, '.json', p, defaultConfig, dump);
if (r) return r;
r = loadSpecific(b, '.js', p, defaultConfig, dump);
if (r) return r;
if (defaultConfig) return defaultConfig;
throw new Error(`file not found: ${b}[.profile].yml( or .yaml/.json/.js)`);
} | javascript | {
"resource": ""
} |
q36895 | HttpApplication | train | function HttpApplication() {
this.app = express();
this._registerConfigurations();
this._registerMiddlewares();
this._registerControllers();
this._registerAreas();
this.initialize.apply(this, arguments);
} | javascript | {
"resource": ""
} |
q36896 | train | function(parent, field, options) {
options = options || {};
// Unique id for this node's generated method
this.id = utils.generateId();
// Link to parent node
this.parent = parent;
// The field related to this node
this.field = field;
// Any options
this.options = options;
// Just some metadata
this.type = 'custom';
// Custom context
this.context = {};
} | javascript | {
"resource": ""
} | |
q36897 | statFile | train | function statFile(path, sizes_data, sizes_file_path){
writeFileData(path, fs.statSync(path).mtime.getTime(), fs.statSync(path).size, sizes_data, sizes_file_path);
} | javascript | {
"resource": ""
} |
q36898 | writeFileData | train | function writeFileData(file_path, time, size, sizes_data, sizes_file_path){
var file_ext = path.extname(file_path).replace('.','');
var file_name = path.basename(file_path);
// create file type object if it doesnt exist
if(sizes_data[file_ext] === undefined){
sizes_data[file_ext] = {};
}
// create file array
if(sizes_data[file_ext][file_name] === undefined){
sizes_data[file_ext][file_name] = [];
}
var time_obj = {
date: time,
size: size
};
grunt.log.writeln(file_path + " .... " + size + "b");
sizes_data[file_ext][file_name].push(time_obj);
fs.writeFileSync(sizes_file_path, JSON.stringify(sizes_data), 'utf8');
} | javascript | {
"resource": ""
} |
q36899 | ScriptRunner | train | function ScriptRunner() {
this.flush();
function onMessage(msg, handle) {
var script, digest;
switch(msg.event) {
case 'loglevel':
log.level(msg.level);
break;
case 'eval':
try {
script = this.load(msg.source).script;
this.run(script, msg.args);
}catch(e) {
process.send({err: true, data: e.message});
}
break;
case 'evalsha':
try {
script = this._cache[msg.sha];
if(!script) throw NoScript;
this.run(script, msg.args);
}catch(e) {
process.send({err: true, data: e.message});
}
break;
case 'load':
try {
digest = this.load(msg.source).sha;
process.send({data: digest});
}catch(e) {
process.send({err: true, data: e.message});
}
break;
case 'exists':
process.send({data: this.exists(msg.args)});
break;
case 'flush':
this.flush();
process.send({data: Constants.OK});
break;
}
}
process.on('message', onMessage.bind(this));
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.