_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q40600 | convertTrees | train | function convertTrees() {
setDefault("treeClass","mktree");
setDefault("nodeClosedClass","liClosed");
setDefault("nodeOpenClass","liOpen");
setDefault("nodeBulletClass","liBullet");
setDefault("nodeLinkClass","bullet");
setDefault("preProcessTrees",true);
if (preProcessTrees) {
if (!document.createElement) { return; } // Without createElement, we can't do anything
var uls = document.getElementsByTagName("ul");
if (uls==null) { return; }
var uls_length = uls.length;
for (var uli=0;uli<uls_length;uli++) {
var ul=uls[uli];
if (ul.nodeName=="UL" && ul.className==treeClass) {
processList(ul);
ul.setAttribute( "data-xdh-mktree", "handled" );
}
}
}
} | javascript | {
"resource": ""
} |
q40601 | processList | train | function processList(ul) {
if ( ul.getAttribute( "data-xdh-mktree" ) == "handled" )
return;
if (!ul.childNodes || ul.childNodes.length==0) { return; }
// Iterate LIs
var childNodesLength = ul.childNodes.length;
for (var itemi=0;itemi<childNodesLength;itemi++) {
var item = ul.childNodes[itemi];
if (item.nodeName == "LI") {
// Iterate things in this LI
var subLists = false;
var itemChildNodesLength = item.childNodes.length;
for (var sitemi=0;sitemi<itemChildNodesLength;sitemi++) {
var sitem = item.childNodes[sitemi];
if (sitem.nodeName=="UL") {
subLists = true;
processList(sitem);
}
}
var s= document.createElement("SPAN");
var t= '\u00A0'; //
s.className = nodeLinkClass;
if (subLists) {
// This LI has UL's in it, so it's a +/- node
if (item.className==null || item.className=="") {
item.className = nodeClosedClass;
}
// If it's just text, make the text work as the link also
if (item.firstChild.nodeName=="#text") {
t = t+item.firstChild.nodeValue;
item.removeChild(item.firstChild);
}
s.onclick = treeNodeOnclick;
}
else {
// No sublists, so it's just a bullet node
item.className = nodeBulletClass;
s.onclick = retFalse;
}
s.appendChild(document.createTextNode(t));
item.insertBefore(s,item.firstChild);
}
}
} | javascript | {
"resource": ""
} |
q40602 | gitDateOf | train | function gitDateOf(val) {
let date = null;
try {
date = exec(`git log -1 --format=%cI ${val}`).toString();
} catch (err) {
return new Error(err);
}
return date.substring(0, date.indexOf('T'));
} | javascript | {
"resource": ""
} |
q40603 | train | function(text){
var deferred = Q.defer();
r.question(text, function(answer) {
deferred.resolve(answer);
});
return deferred.promise;
} | javascript | {
"resource": ""
} | |
q40604 | castType | train | function castType(val, type, def) {
function cast() {
if (!is_1.isValue(val))
return to_1.toDefault(null, def);
// If no type specified try to get automatically.
type = type || getType(val);
if (is_1.isArray(type)) {
return to_1.toArray(val)
.map(function (v, i) { return castType(v, type[i] || type[i - 1] || type[0]); });
}
else if (is_1.isFunction(type)) {
val = to_1.toArray(val);
return type.apply(void 0, val);
}
else if (is_1.isString(type)) {
type = type.toLowerCase();
var func = toMap[type];
if (func)
return func(val);
return to_1.toDefault(null, def);
}
else {
return val;
}
}
return function_1.tryWrap(cast)(def);
} | javascript | {
"resource": ""
} |
q40605 | getType | train | function getType(val, strict, def) {
if (is_1.isString(strict)) {
def = strict;
strict = undefined;
}
var type = typeof val;
var parse = !is_1.isValue(strict) ? true : false;
function isKnown() {
return (type === 'undefined' ||
(type !== 'object' &&
type !== 'number' &&
type !== 'string'));
}
// If not 'object', 'number' or 'string' just
// return the type, numbers, objects and strings
// should fall through for more specific type.
if (isKnown())
return type;
if (is_1.isNull(val)) {
return 'null';
}
else if (is_1.isDate(val)) {
return 'date';
}
else if (is_1.isNumber(val)) {
if (strict)
return 'number';
if (is_1.isFloat(val))
return 'float';
if (is_1.isInteger(val))
return 'integer';
/* istanbul ignore next */
return 'number';
}
else if (is_1.isPlainObject(val)) {
if (strict)
return type;
return 'literal';
}
else if (is_1.isError(val)) {
return 'error';
}
else if (is_1.isRegExp(val)) {
return 'regexp';
}
else if (is_1.isArray(val)) {
return 'array';
}
else if (is_1.isString(val)) {
return 'string';
}
else if (val.constructor && val.constructor.name) {
if (strict)
return type;
return val.constructor.name;
}
/* istanbul ignore next */
return def || 'any';
} | javascript | {
"resource": ""
} |
q40606 | ensureLoader | train | function ensureLoader (lang) {
return lang.split('!').map(function (loader) {
return loader.replace(/^([\w-]+)(\?.*)?/, function (_, name, query) {
return (/-loader$/.test(name) ? name : (name + '-loader')) + (query || '')
})
}).join('!')
} | javascript | {
"resource": ""
} |
q40607 | train | function (opt) {
if (typeof opt !== "object" || opt === null) {
opt = {};
}
if (typeof opt.tag !== "string") {
opt.tag = null;
}
if (typeof opt.encoding !== "string") {
opt.encoding = "utf8";
}
//Extends the readable stream
stream.Readable.call(this, {encoding: opt.encoding});
this._tag = (typeof opt.tag === "string") ? opt.tag.trim() : null;
this._level = labels.length;
this._disabled = false;
//Default message format
this._format = function (tag, label, text) {
let list = [];
if (tag) {
//Add the tag if it is provided
list.push("[" + tag + "]");
}
list.push("[" + timestamp("YYYY-MM-DD hh:mm:ss") + "]");
list.push("[" + label.toUpperCase() + "]");
list.push(text.trim());
return list.join(" ");
};
return this;
} | javascript | {
"resource": ""
} | |
q40608 | is | train | function is(type, input) {
if (type === 'Object') return Object(input) === input;
return toString.call(input) === '[object ' + type + ']';
} | javascript | {
"resource": ""
} |
q40609 | str | train | function str(input) {
if (!is('String', input)) return;
return root[input] || (root.require || require)(input);
} | javascript | {
"resource": ""
} |
q40610 | removeClass | train | function removeClass(element, className) {
if (!hasClassNameProperty(element)) {
return;
}
element.className = element.className
.replace(className, '')
.replace(/^\s+|\s+$/g, '')
.replace(/\s\s/g, ' ');
} | javascript | {
"resource": ""
} |
q40611 | normalizeOptions | train | function normalizeOptions(obj) {
for (var key in obj) {
if (utils.optsKeys.indexOf(key) > -1) {
obj.options = obj.options || {};
obj.options[key] = obj[key];
delete obj[key];
}
}
return obj;
} | javascript | {
"resource": ""
} |
q40612 | toObject | train | function toObject(src, dest, options) {
if (!utils.isObject(options)) {
options = {};
}
var config = {};
if (utils.isObject(dest)) {
options = extend({}, options, dest);
dest = null;
}
if (utils.isObject(src)) {
config = src;
}
if (isValidSrc(src)) {
config.src = src;
} else if (Array.isArray(src)) {
config = normalize(src);
}
if (typeof dest === 'string') {
config.dest = dest;
}
if (options.hasOwnProperty('options')) {
options = extend({}, options, options.options);
delete options.options;
}
config.options = extend({}, config.options, options);
return config;
} | javascript | {
"resource": ""
} |
q40613 | normalizeSrc | train | function normalizeSrc(val) {
if (!val.src) return val;
val.src = utils.arrayify(val.src);
return val;
} | javascript | {
"resource": ""
} |
q40614 | reduceFiles | train | function reduceFiles(files, orig) {
var config = {files: []};
var len = files.length;
var idx = -1;
while (++idx < len) {
var val = normalize(files[idx]);
config.files = config.files.concat(val.files);
}
return copyNonfiles(config, orig);
} | javascript | {
"resource": ""
} |
q40615 | copyNonfiles | train | function copyNonfiles(config, provider) {
if (!provider) return config;
for (var key in provider) {
if (!isFilesKey(key)) {
config[key] = provider[key];
}
}
return config;
} | javascript | {
"resource": ""
} |
q40616 | filesObjects | train | function filesObjects(val) {
var res = {};
if (val.options) res.options = val.options;
res.files = [];
for (var key in val) {
if (key !== 'options') {
var file = {};
if (val.options) file.options = val.options;
file.src = utils.arrayify(val[key]);
file.dest = key;
res.files.push(file);
}
}
return res;
} | javascript | {
"resource": ""
} |
q40617 | formatObject | train | function formatObject(val) {
if (val.options && val.options.format === false) {
return val;
}
var res = { options: val.options };
res.files = val.files;
for (var key in val) {
if (key === 'files' || key === 'options') {
continue;
}
res[key] = val[key];
}
var len = res.files.length;
var idx = -1;
while (++idx < len) {
var ele = res.files[idx];
var obj = {};
obj.options = {};
obj.src = ele.src || [];
obj.dest = ele.dest || '';
copyNonfiles(obj, ele);
if (!ele.options) {
obj.options = res.options;
}
res.files[idx] = obj;
}
return res;
} | javascript | {
"resource": ""
} |
q40618 | train | function (app) {
//Provide angularLivi18nService
app.get('/livi18n/ngLivi18n.js', function (req, res) {
var filepath = path.join(__dirname, 'client', 'ngLivi18n.js');
res.sendfile(filepath);
});
//Check if socket is enabled
if (config.socket) {
//Provide SocketManager
app.get('/livi18n/livi18n.js', function (req, res) {
var filepath = path.join(__dirname, 'client', 'livi18nSocket.js');
res.sendfile(filepath);
});
//Provide angularSocketService
app.get('/livi18n/ngSocket.js', function (req, res) {
var filepath = path.join(__dirname, 'client', 'ngSocket.js');
res.sendfile(filepath);
});
} else {
//Provide js library
app.get('/livi18n/livi18n.js', function (req, res) {
var filepath = path.join(__dirname, 'client', 'livi18n.js');
res.sendfile(filepath);
});
//Provide i18n API
app.get('/livi18n/:filename', function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.json(readLanguage(config.currentLanguage, req.params.filename + '.json'));
});
}
} | javascript | {
"resource": ""
} | |
q40619 | train | function (language) {
for (var i in config.languages) {
if (config.languages[i] === language) {return true;}
}
//
return false;
} | javascript | {
"resource": ""
} | |
q40620 | GetValues | train | function GetValues(mydata, keys, index)
{
//Output
var values = [];
//Loop
for(var j = 0; j < keys.length; j++)
{
//Save data value
var value = mydata[keys[j]];
//Check if value exists
if(!value)
{
//Show warning
console.log('WARNING: value "' + keys[j] + '" is not defined on element "' + index + '" of your array.');
//Set it to empty string
value = '';
}
//Check the data type
if(typeof value === 'string' || value instanceof String)
{
//Add the quotes
value = '"' + value + '"';
}
//Push
values.push(value);
}
//Return
return values.join(',');
} | javascript | {
"resource": ""
} |
q40621 | zadd | train | function zadd(key /* score-1, member-1, score-N, member-N, req */) {
var args = slice.call(arguments, 1)
, req = typeof args[args.length-1] === 'object' ? args.pop() : null
, val = this.getKey(key, req);
if(val === undefined) {
val = new SortedSet();
this.setKey(key, val, undefined, undefined, undefined, req);
}
return val.zadd(args);
} | javascript | {
"resource": ""
} |
q40622 | zrank | train | function zrank(key, member, req) {
var zset = this.getKey(key, req);
if(zset === undefined) return null;
return zset.zrank(member);
} | javascript | {
"resource": ""
} |
q40623 | zrevrank | train | function zrevrank(key, member, req) {
var zset = this.getKey(key, req);
if(zset === undefined) return null;
return zset.zrevrank(member);
} | javascript | {
"resource": ""
} |
q40624 | zscore | train | function zscore(key, member, req) {
var zset = this.getKey(key, req);
if(zset === undefined) return null;
return zset.zscore(member);
} | javascript | {
"resource": ""
} |
q40625 | zrem | train | function zrem(key /* member-1, member-N, req */) {
var args = slice.call(arguments, 1)
, req = typeof args[args.length-1] === 'object' ? args.pop() : null
, val = this.getKey(key, req);
if(val === undefined) return 0;
var deleted = val.zrem(args);
if(val.zcard() === 0) {
this.delKey(key, req);
}
return deleted;
} | javascript | {
"resource": ""
} |
q40626 | zincrby | train | function zincrby(key, increment, member, req) {
var val = this.getKey(key, req);
if(val === undefined) {
val = new SortedSet();
this.setKey(key, val, undefined, undefined, undefined, req);
}
return val.zincrby(increment, member);
} | javascript | {
"resource": ""
} |
q40627 | train | function (arr, val) {
if (!arr || arr.length === 0) return {}
let o = {}
let v = val || null
if (arr.length > 1)
v = this.fromArray(arr.slice(1), v)
o[arr[0]] = v
return o
} | javascript | {
"resource": ""
} | |
q40628 | train | function (str, sep, val) {
if (!str || str.length === 0) return {}
const parts = str.split(sep).filter((s) => s)
return this.fromArray(parts, val)
} | javascript | {
"resource": ""
} | |
q40629 | mergeObjects | train | function mergeObjects (o1, o2) {
let m = Object.assign({}, o1)
for (let attr in o2) {
let v = o2[attr]
if (attr in m && isPlainObject(v) && isPlainObject(m[attr]))
m[attr] = mergeObjects(m[attr], v)
else
m[attr] = v
}
return m
} | javascript | {
"resource": ""
} |
q40630 | parser | train | function parser (defaults, validators, mappers) {
return function (opts) {
const merged = mergeObjects(defaults, opts)
Object.keys(merged).forEach((key) => {
if (validators[key] && ! validators[key](merged[key]))
throw new Error('Failed to validate ' + key)
if (mappers && mappers[key])
merged[key] = mappers[key](merged[key])
})
return merged
}
} | javascript | {
"resource": ""
} |
q40631 | combine | train | function combine () {
const c = Array.prototype.concat.apply([], arguments)
.map((expression) => '(' + expression.source + ')')
.join('|')
return new RegExp(c)
} | javascript | {
"resource": ""
} |
q40632 | _executeCommands | train | function _executeCommands (showDetails, cmds) {
if (cmds.length) {
const cmd = cmds.shift();
execute(showDetails, cmd.cmd, cmd.options).then((...data) => {
if (data.length && undefined !== data[0]) {
if (1 === data.length && "boolean" === typeof data[0]) {
if (showDetails) {
(0, console).log(getFormatedTime(), "=>", data[0]);
}
else {
(0, console).log(data[0] ? "1" : "0");
}
}
else if (showDetails) {
(0, console).log(getFormatedTime(), "=>", ...data);
}
else {
(0, console).log(...data);
}
}
_executeCommands(showDetails, cmds);
}).catch((err) => {
(0, console).error(err);
(0, process).exitCode = 1;
});
}
} | javascript | {
"resource": ""
} |
q40633 | _getDefaultSessionSchema | train | function _getDefaultSessionSchema() {
return new MongooseSchema({
sid: {type : String, index: true },
session: {
type: MongooseSchema.Types.Mixed
},
dateLoggedIn : {
type : Date,
default : new Date()
},
lastAccessTime: {
type : Date,
default : new Date()
},
expires : {
type : Date,
index : true
}
});
} | javascript | {
"resource": ""
} |
q40634 | _pasreCookies | train | function _pasreCookies(sessionToStore) {
if (sessionToStore && sessionToStore.cookie && (typeof sessionToStore.cookie.toJSON === "function")) {
sessionToStore.cookie = sessionToStore.cookie.toJSON();
}
return sessionToStore;
} | javascript | {
"resource": ""
} |
q40635 | initLunr | train | function initLunr() {
if (!endsWith(baseurl,"/")){
baseurl = baseurl+'/'
};
// First retrieve the index file
$.getJSON(baseurl +"index.json")
.done(function(index) {
pagesIndex = index;
// Set up lunrjs by declaring the fields we use
// Also provide their boost level for the ranking
lunrIndex = new lunr.Index
lunrIndex.ref("uri");
lunrIndex.field('title', {
boost: 15
});
lunrIndex.field('tags', {
boost: 10
});
lunrIndex.field("content", {
boost: 5
});
// Feed lunr with each file and let lunr actually index them
pagesIndex.forEach(function(page) {
lunrIndex.add(page);
});
lunrIndex.pipeline.remove(lunrIndex.stemmer)
})
.fail(function(jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.error("Error getting Hugo index flie:", err);
});
} | javascript | {
"resource": ""
} |
q40636 | search | train | function search(query) {
// Find the item in our index corresponding to the lunr one to have more info
return lunrIndex.search(query).map(function(result) {
return pagesIndex.filter(function(page) {
return page.uri === result.ref;
})[0];
});
} | javascript | {
"resource": ""
} |
q40637 | init | train | function init(ctx) {
_.each(resources, function (resource) {
_.each(resource.tasks, function (taskInfo, taskName) {
taskInfo.name = taskName;
taskInfo.service = pancakes.getService(resource.name);
taskHandlers[taskName] = taskInfo;
});
});
return new Q(ctx);
} | javascript | {
"resource": ""
} |
q40638 | isTaskHandled | train | function isTaskHandled(request, reply) {
var taskName = request.query.task;
// if no task or task handler, don't do anything
if (!taskName && !taskHandlers[taskName]) { return false; }
// if task info doesn't have service or method, don't do anything
var taskInfo = taskHandlers[taskName];
if (!taskInfo || !taskInfo.service || !taskInfo.method || !taskInfo.service[taskInfo.method]) {
return false;
}
// if user is not logged in redirect to login then back to here
if (!request.caller || !request.caller.user) {
var currentUrl = request.url.pathname;
var loginUrl = currentUrl + '?modal=auth&submodal=login&redirect=' + currentUrl;
reply().redirect(loginUrl);
return true;
}
// start collecting the service request
var serviceReq = { caller: request.caller };
// get the values from the request object to put into the service request
_.each(taskInfo.params, function (param) {
if (request.query[param]) {
serviceReq[param] = request.query[param];
}
});
// call the service method
taskInfo.service[taskInfo.method](serviceReq)
.then(function () {
reply().redirect(request.path + '?notify=' + taskInfo.notifySuccess);
})
.catch(function (err) {
log.error(err);
reply().redirect(request.path + '?notify=' + taskInfo.notifyFailure);
});
return true;
} | javascript | {
"resource": ""
} |
q40639 | transformReact | train | function transformReact(source, options) {
// TODO: just use react-tools
options = options || {};
var visitorList;
if (options.harmony) {
visitorList = visitors.getAllVisitors();
} else {
visitorList = visitors.transformVisitors.react;
}
if (options.stripTypes) {
// Stripping types needs to happen before the other transforms
// unfortunately, due to bad interactions. For example,
// es6-rest-param-visitors conflict with stripping rest param type
// annotation
source = transform(typesSyntax.visitorList, source, options).code;
}
return transform(visitorList, source, {
sourceMap: supportsAccessors && options.sourceMap
});
} | javascript | {
"resource": ""
} |
q40640 | createSourceCodeErrorMessage | train | function createSourceCodeErrorMessage(code, e) {
var sourceLines = code.split('\n');
var erroneousLine = sourceLines[e.lineNumber - 1];
// Removes any leading indenting spaces and gets the number of
// chars indenting the `erroneousLine`
var indentation = 0;
erroneousLine = erroneousLine.replace(/^\s+/, function(leadingSpaces) {
indentation = leadingSpaces.length;
return '';
});
// Defines the number of characters that are going to show
// before and after the erroneous code
var LIMIT = 30;
var errorColumn = e.column - indentation;
if (errorColumn > LIMIT) {
erroneousLine = '... ' + erroneousLine.slice(errorColumn - LIMIT);
errorColumn = 4 + LIMIT;
}
if (erroneousLine.length - errorColumn > LIMIT) {
erroneousLine = erroneousLine.slice(0, errorColumn + LIMIT) + ' ...';
}
var message = '\n\n' + erroneousLine + '\n';
message += new Array(errorColumn - 1).join(' ') + '^';
return message;
} | javascript | {
"resource": ""
} |
q40641 | verifyTasks | train | function verifyTasks() {
if ( options.tasks.build ) {
if ( isTypeString(options.tasks.build) ) {
options.tasks.build = [options.tasks.build];
}
if ( util.isArray(options.tasks.build) ) {
options.tasks.build.forEach(function( item ) {
if ( !isTypeString(item) ) {
errorOption('tasks.build', JSON.stringify(item));
}
});
}
else {
errorOption('tasks.build', options.tasks.build);
}
}
else {
options.tasks.build = [];
}
} | javascript | {
"resource": ""
} |
q40642 | verifyOthers | train | function verifyOthers() {
if ( !isTypeString(options.commit) ) {
errorOption('commit', options.commit);
}
if ( !isTypeString(options.tag) ) {
errorOption('tag', options.tag);
}
} | javascript | {
"resource": ""
} |
q40643 | isCurrentBranch | train | function isCurrentBranch( branch ) {
return function() {
var deferred = Q.defer();
Q.fcall(command('git symbolic-ref --short -q HEAD', 'Get current branch'))
.then(function( data ) {
//console.log('data=',data);
if ( data && data.trim() === branch ) {
deferred.resolve(true);
}
else {
throw new Error(format('Error. Branch [%s] is not the current branch. Output:[%s]', branch, data.trim()));
}
})
.catch(function( err ) {
console.log('err=',err);
deferred.reject(err);
});
return deferred.promise;
};
} | javascript | {
"resource": ""
} |
q40644 | runBuildTasks | train | function runBuildTasks() {
return (function() {
if ( options.tasks.build.length > 0 ) {
var aToRun = [];
options.tasks.build.forEach(function( item ) {
aToRun.push(command('grunt ' + item, 'Task:' + item));
});
return aToRun.reduce(function( accum, cur ) { //tks to http://stackoverflow.com/a/24262233/854575
return accum.then(cur);
}, Q());
}
}());
} | javascript | {
"resource": ""
} |
q40645 | gitTag | train | function gitTag() {
return function() {
var deferred = Q.defer();
if (!grunt.option('version')) {
throw new Error('Error in step [Git tag]. Version is not defined.');
}
Q.fcall(command(format('git tag -a v%s -m \'%s\'', grunt.option('version'), options.tag.replace('%v', grunt.option('version'))), 'Git tag'))
//Q.fcall(command(format('echo "git tag -a v%s -m \'%s\'"', grunt.option('version'), options.tag.replace('%v', grunt.option('version'))), 'Git tag', false))//TODO:temp
.then(function( data ) {
deferred.resolve(data);
})
.catch(function( err ) {
deferred.reject(err);
});
return deferred.promise;
};
} | javascript | {
"resource": ""
} |
q40646 | gitRemote | train | function gitRemote() {
return function() {
var deferred = Q.defer();
Q.fcall(command('git remote', 'Git remote'))
.then(function( data ) {
if ( !data || !data.trim() ) {
deferred.reject(new Error('Error in step [Git remote]. No remotes founds.'));
}
var remotes = data.trim().split('\n');
if ( remotes.length == 1 ) {
grunt.option('remote', remotes[0]);
deferred.resolve(grunt.option('remote'));
}
else {
remotes.forEach(function( item, index, list ) {
list[index] = format('[%s]-%s', index + 1, item);
});
var resp = 0;
grunt.log.writeln(format('%s ', '\n\nThere are more than 1 remote associate with this repo, please choose the one to push into.\n\n' + remotes.join('\n')));
while ( isNaN(resp) || resp === 0 || resp > remotes.length ) {
resp = readlinesync.question('\nYour choice?');
if ( resp === '' ) {
grunt.option('remote', undefined);
throw new Error('Error in step [Git remote]. No response from user.');
}
resp = parseInt(resp);
}
grunt.option('remote', data.trim().split('\n')[resp-1]);//using original output
deferred.resolve(grunt.option('remote'));
}
})
.catch(function( err ) {
grunt.option('remote', undefined);
deferred.reject(err);
});
return deferred.promise;
};
} | javascript | {
"resource": ""
} |
q40647 | train | function ( range, root ) {
var container = range.startContainer,
block;
// If inline, get the containing block.
if ( isInline( container ) ) {
block = getPreviousBlock( container, root );
} else if ( container !== root && isBlock( container ) ) {
block = container;
} else {
block = getNodeBefore( container, range.startOffset );
block = getNextBlock( block, root );
}
// Check the block actually intersects the range
return block && isNodeContainedInRange( range, block, true ) ? block : null;
} | javascript | {
"resource": ""
} | |
q40648 | train | function ( event ) {
var types = event.dataTransfer.types;
var l = types.length;
var hasPlain = false;
var hasHTML = false;
while ( l-- ) {
switch ( types[l] ) {
case 'text/plain':
hasPlain = true;
break;
case 'text/html':
hasHTML = true;
break;
default:
return;
}
}
if ( hasHTML || hasPlain ) {
this.saveUndoState();
}
} | javascript | {
"resource": ""
} | |
q40649 | updateHead | train | function updateHead(title, description) {
updateTitle(title);
description = (description || '').replace(/"/g, '');
var metaDesc = angular.element($rootElement.find('meta[name=description]')[0]);
metaDesc.attr('content', description);
} | javascript | {
"resource": ""
} |
q40650 | updatePageStyle | train | function updatePageStyle(pageName) {
var pageCssId = 'gh-' + pageName.replace('.', '-');
var elem = $rootElement.find('.maincontent');
if (elem && elem.length) {
elem = angular.element(elem[0]);
elem.attr('id', pageCssId);
}
} | javascript | {
"resource": ""
} |
q40651 | canvasFilters | train | function canvasFilters(canvas, settings) {
settings = Object.assign({}, {
smoothing : false, // Smoothing [true|fale]
brightness : 0, // Image brightness [-255 to +255]
contrast : 0, // Image contrast [-255 to +255]
gamma : 0, // Image gamma correction [0.01 to 7.99]
grayscale : 'none', // Graysale algorithm [average, luma, luma-601, luma-709, luma-240, desaturation, decomposition-[min|max], [red|green|blue]-chanel]
shadesOfGray: 256, // Number of shades of gray [2-256]
invertColor : false // Invert color...
}, settings || {})
// Get canvas 2d context
let context = canvas.getContext('2d')
// Smoothing
if (context.imageSmoothingEnabled !== undefined) {
context.imageSmoothingEnabled = settings.smoothing
}
else {
context.mozImageSmoothingEnabled = settings.smoothing
context.webkitImageSmoothingEnabled = settings.smoothing
context.msImageSmoothingEnabled = settings.smoothing
context.oImageSmoothingEnabled = settings.smoothing
}
// Get image data
let imageData = context.getImageData(0, 0, canvas.width, canvas.height)
let data = imageData.data
let contrastFactor, brightnessOffset, gammaCorrection, shadesOfGrayFactor
if (settings.contrast !== 0) {
contrastFactor = (259 * (settings.contrast + 255)) / (255 * (259 - settings.contrast))
}
if (settings.brightness !== 0) {
brightnessOffset = settings.brightness
}
if (settings.gamma !== 0) {
gammaCorrection = 1 / settings.gamma
}
// Shades of gray
if (settings.shadesOfGray > 1 && settings.shadesOfGray < 256) {
shadesOfGrayFactor = 255 / (settings.shadesOfGray - 1)
}
// For each pixel
for (let i = 0, il = data.length; i < il; i += 4) {
// Apply filters
invertColor(data, i, settings.invertColor)
brightness(data, i, brightnessOffset)
contrast(data, i, contrastFactor)
gamma(data, i, gammaCorrection)
grayscale(data, i, settings.grayscale, shadesOfGrayFactor)
}
// Write new image data on the context
context.putImageData(imageData, 0, 0)
} | javascript | {
"resource": ""
} |
q40652 | getHandler | train | function getHandler (method, trans, version) {
return function (req, res, next) {
res.setHeader('Allow', Object.values(allowedMethods).join(','));
let service = req.params.__service;
let id = req.params.__id;
let action = req.params.__action;
let path = '/' + service +
(id? '/' + id : '') +
(action? '/' + action : '');
// guess whether id is an action?
if (id && !action) {
if (!(validator.isNumeric(id) || validator.isMongoId(id))) {
action = id;
}
}
service += (action? '.' + action : '');
debug(`REST handler calling service \'${service}\'`);
debug(` => cmd \'${method}\'`);
debug(` => path \'${path}\'`);
debug(` => version \'${version}\'`);
// The service success callback which sets res.data or calls next() with the error
const callback = function (err, data) {
debug(' => service response:', err, data);
if (err) return next(err.cause || err);
res.data = data;
if (!data) {
debug(`No content returned for '${req.url}'`);
res.status(statusCodes.noContent);
} else if (method === 'post') {
res.status(statusCodes.created);
}
return next();
};
trans.act({
topic: `poplar.${service}`,
cmd: method,
path: path,
version: version,
headers: req.headers || {},
query: req.query || {},
body: req.body || {}
}, callback);
};
} | javascript | {
"resource": ""
} |
q40653 | Chain | train | function Chain(val, name) {
if (!(this instanceof Chain)) return new Chain(val, name);
this._val = val;
this._name = name;
this.clear();
return this;
} | javascript | {
"resource": ""
} |
q40654 | train | function (id, width)
{
ModalDialog.id = id;
ModalDialog.width = width;
ModalDialog.ShowBackground();
ModalDialog.ShowDialog();
// Install the event handlers
window.onresize = ModalDialog.Resize;
// Call them initially
ModalDialog.Resize();
if (typeof(ModalDialog.onmodaldialog) == 'function') {
ModalDialog.onmodaldialog();
}
ModalDialog.FireCustomEvent('onmodaldialog');
} | javascript | {
"resource": ""
} | |
q40655 | train | function ()
{
// Create the background if neccessary
ModalDialog.background = document.createElement('DIV');
ModalDialog.background.className = 'ModalDialog_background';
ModalDialog.background.style.position = 'fixed';
ModalDialog.background.style.top = 0;
ModalDialog.background.style.left = 0;
ModalDialog.background.style.width = (screen.width + 100) + 'px';
ModalDialog.background.style.height = (screen.height + 100) + 'px';
ModalDialog.background.style.backgroundColor = 'rgb(204,204,204)';
ModalDialog.background.style.opacity = 0;
ModalDialog.background.style.zIndex = 3276;
ModalDialog.background.style.filter = "Alpha(opacity=50)";
document.body.appendChild(ModalDialog.background);
ModalDialog.background.style.visibility = 'visible';
} | javascript | {
"resource": ""
} | |
q40656 | train | function ()
{
if (ModalDialog.dialog) {
ModalDialog.dialog.style.left = (document.body.offsetWidth / 2) - (ModalDialog.dialog.offsetWidth / 2) + 'px';
}
ModalDialog.background.style.width = '2500px';
ModalDialog.background.style.height = '2500px';
} | javascript | {
"resource": ""
} | |
q40657 | train | function (name, func)
{
if (typeof(ModalDialog.events) == 'undefined') {
ModalDialog.events = [];
}
ModalDialog.events.push([name, func]);
} | javascript | {
"resource": ""
} | |
q40658 | train | function (name)
{
for (var i=0; i<ModalDialog.events.length; ++i) {
if (typeof(ModalDialog.events[i][0]) == 'string' && ModalDialog.events[i][0] == name && typeof(ModalDialog.events[i][1]) == 'function') {
ModalDialog.events[i][1]();
}
}
} | javascript | {
"resource": ""
} | |
q40659 | median | train | function median(array) {
var length = array.length;
if (length === 0) {
throw new RangeError("Error");
}
array.sort(function(a, b) {
return a - b;
});
var middle = Math.floor(length / 2);
return length % 2 ? array[middle] : (array[middle] + array[middle - 1]) / 2;
} | javascript | {
"resource": ""
} |
q40660 | Connection | train | function Connection(conn) {
if(!(this instanceof Connection)) {
return new Connection(conn);
}
var self = this;
if(!conn) { throw new TypeError("no connection set"); }
self._connection = conn;
self._connect = Q.nfbind(self._connection.connect.bind(self._connection));
self._query = Q.nfbind(self._connection.query.bind(self._connection));
// These do not have callbacks when PoolConnection is used
//self._end = Q.nfbind(self._connection.end.bind(self._connection));
//self._release = Q.nfbind(self._connection.release.bind(self._connection));
self._changeUser = Q.nfbind(self._connection.changeUser.bind(self._connection));
db.Connection.call(self, conn);
} | javascript | {
"resource": ""
} |
q40661 | mapFalseInputs | train | function mapFalseInputs(suite, input, p) {
if (p === undefined) {
p = 0;
}
for (p; p < input.length; p++) {
if (input[p] === false) {
var i, newInput = [];
for (i in suite[map[p]]) {
var mapped, cloned = input.slice(0);
cloned[p] = i;
if ((mapped = mapFalseInputs(suite, cloned, p + 1)) !== true) {
newInput = newInput.concat(mapped);
} else {
newInput.push(cloned);
}
}
return newInput;
}
}
return true;
} | javascript | {
"resource": ""
} |
q40662 | presignRequest | train | function presignRequest (presignUrl, token) {
return new Promise((resolve, reject) => {
request
.post(presignUrl)
.set({
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-Token': token
})
.end((err, res) => {
// throw a custom error message
if (err) return reject(customError('presignRequest', err))
resolve(res)
})
})
} | javascript | {
"resource": ""
} |
q40663 | presign | train | function presign (presignUrl, token, fn = presignRequest) {
return new Promise((resolve, reject) => {
fn(presignUrl, token)
.then(responseStatus)
.then(parseJSON)
.then((res) => {
resolve(res)
})
.catch((err) => {
reject(err)
})
})
} | javascript | {
"resource": ""
} |
q40664 | Prompt | train | function Prompt () {
Base.apply(this, arguments);
if (!this.opt.basePath) {
this.throwParamError('basePath');
}
this.pathIndexHash = {};
this.originalBaseDir = this.currentPath =
path.normalize(path.isAbsolute(this.opt.basePath) ?
path.resolve(this.opt.basePath) : path.resolve(process.cwd(), this.opt.basePath));
if (String(this.currentPath).endsWith(path.sep)) {
this.currentPath = String(this.currentPath).slice(0, -1);
}
this.onlyOneFile = !!this.opt.onlyOneFile;
this.opt.choices = new Choices(this.createChoices(this.currentPath), this.answers);
this.selected = 0;
if (this.opt.filterItems) {
assert(typeof this.opt.filterItems === 'function', ' "filterItems" option property must be a function.');
}
this.firstRender = true;
// Make sure no default is set (so it won't be printed)
this.opt.default = null;
this.searchTerm = '';
this.paginator = new Paginator();
} | javascript | {
"resource": ""
} |
q40665 | createAndFlush | train | function createAndFlush(size) {
if (self._stream) {
self._stream.end();
self._stream.destroySoon();
}
self._size = size;
self.filename = target;
self._stream = fs.createWriteStream(fullname, self.options);
//
// We need to listen for drain events when
// write() returns false. This can make node
// mad at times.
//
self._stream.setMaxListeners(Infinity);
//
// When the current stream has finished flushing
// then we can be sure we have finished opening
// and thus can emit the `open` event.
//
self.once('flush', function () {
// Because "flush" event is based on native stream "drain" event,
// logs could be written inbetween "self.flush()" and here
// Therefore, we need to flush again to make sure everything is flushed
self.flush();
self.opening = false;
self.emit('open', fullname);
});
//
// Remark: It is possible that in the time it has taken to find the
// next logfile to be written more data than `maxsize` has been buffered,
// but for sensible limits (10s - 100s of MB) this seems unlikely in less
// than one second.
//
self.flush();
} | javascript | {
"resource": ""
} |
q40666 | train | function (title) {
Suite.super_.call(this)
this.title = title
this.suites = []
this.exclusivity = Suite.EXCLUSIVITY.NONE
this.testExclusivity = undefined
this.parent = undefined
this.nextTests = []
this.globalTests = []
this.testContainer = false
this.testDependencies = []
this.hasOnlyTest = false
this._only = false
this._skip = false
this._timeout = undefined
this._prepared = false
this._nonExclusives = []
this._context = undefined
this.tests = {
beforeAll: []
, beforeEach: []
, normal: []
, afterEach: []
, afterAll: []
}
} | javascript | {
"resource": ""
} | |
q40667 | isArray | train | function isArray(val) {
/* istanbul ignore if */
if (!Array.isArray)
return constant_1.toStr.call(val) === '[object Array]';
return Array.isArray(val);
} | javascript | {
"resource": ""
} |
q40668 | isBrowser | train | function isBrowser(override) {
// Enables checking a process.env key while
// in Node.
if (override)
return typeof process !== 'undefined' &&
function_1.tryWrap(to_1.toBoolean, process.env &&
process.env[override])(false) === true;
// Otherwise just return NOT Node.
return !isNode();
} | javascript | {
"resource": ""
} |
q40669 | isDebug | train | function isDebug(debugging) {
// If manually passed just return.
if (isValue(debugging))
return debugging;
var eargv = process && process.execArgv;
function chkDebug() {
return (eargv.filter(function (v) { return /^(--debug|--inspect)/.test(v); }).length ||
isValue(v8debug));
}
return function_1.tryWrap(chkDebug)(false);
} | javascript | {
"resource": ""
} |
q40670 | isEmpty | train | function isEmpty(val) {
return (isUndefined(val) ||
isNull(val) ||
(isString(val) && val.length === 0) ||
(isNumber(val) && isNaN(val)) ||
(isPlainObject(val) && !array_1.keys(val).length) ||
(isArray(val) && !val.length));
} | javascript | {
"resource": ""
} |
q40671 | isEqual | train | function isEqual(val, comp, loose) {
if (isDate(val) && isDate(comp))
return to_1.toEpoch(val) === to_1.toEpoch(comp);
if (loose)
return val == comp;
return val === comp;
} | javascript | {
"resource": ""
} |
q40672 | isError | train | function isError(val, prop) {
if (!isValue(val) || !isObject(val))
return false;
var type = constant_1.toStr.call(val).toLowerCase();
return type === '[object error]' || type === '[object domexception]' || !isEmpty(val[prop]);
} | javascript | {
"resource": ""
} |
q40673 | isDocker | train | function isDocker() {
if (!isNode())
return false;
var hasEnv = function_1.tryWrap(function () {
statSync('/.dockerenv');
return true;
})(false);
var hasGroup = function_1.tryWrap(function () {
return ~readFileSync('/proc/self/cgroup', 'utf8').indexOf('docker');
})(false);
return hasEnv || hasGroup;
} | javascript | {
"resource": ""
} |
q40674 | isObject | train | function isObject(val) {
return (!isUndefined(val) &&
!isNull(val) &&
((val && val.constructor === Object) || typeof val === 'function' || typeof val === 'object'));
} | javascript | {
"resource": ""
} |
q40675 | isPromise | train | function isPromise(val, name) {
name = name || 'Promise';
return (!isEmpty(val) &&
val.constructor &&
val.constructor.name === name);
} | javascript | {
"resource": ""
} |
q40676 | renderTmpl | train | function renderTmpl (path, vars, callback) {
fs.readFile(path, 'utf8', function (err, file) {
if (err) {
return callback(err);
}
var out = file.replace(/\{\{([a-z]+)\}\}/ig, function (all, name) {
return vars[name];
});
callback(null, out);
});
} | javascript | {
"resource": ""
} |
q40677 | train | function(db) {
var methods_uuid = uuid();
debug.assert(methods_uuid).is('uuid');
return db.query('CREATE SEQUENCE methods_seq')
.query(['CREATE TABLE IF NOT EXISTS methods (',
" id uuid PRIMARY KEY NOT NULL default uuid_generate_v5('"+methods_uuid+"', nextval('methods_seq'::regclass)::text),",
' types_id uuid REFERENCES types,',
' type text NOT NULL,',
' name text NOT NULL,',
' body text NOT NULL,',
' meta json NOT NULL,',
' active BOOLEAN DEFAULT TRUE,',
' created timestamptz NOT NULL default now(),',
' modified timestamptz NOT NULL default now(),',
' CONSTRAINT active_not_false CHECK(active != false)',
')'
].join('\n'))
.query('ALTER SEQUENCE methods_seq OWNED BY methods.id')
.query('CREATE INDEX methods_types_id ON methods (types_id)')
.query('CREATE INDEX methods_types_id_name ON methods (types_id,name)')
.query('CREATE INDEX methods_type ON methods (type)')
.query('CREATE INDEX methods_type_name ON methods (type,name)')
.query('CREATE UNIQUE INDEX ON methods USING btree(types_id, name, active nulls LAST);')
.query('CREATE TRIGGER methods_modified BEFORE UPDATE ON methods FOR EACH ROW EXECUTE PROCEDURE moddatetime (modified)')
.query(
[
'CREATE OR REPLACE FUNCTION ensure_only_one_active_row_trigger()',
'RETURNS trigger',
'AS $function$',
'BEGIN',
// Disable the currently enabled row
" IF (TG_OP = 'UPDATE') THEN",
// Nothing to do if updating the row currently enabled'
" IF (OLD.active = true AND OLD.name = NEW.name) THEN",
' RETURN NEW;',
' END IF;',
" EXECUTE format('UPDATE %I.%I SET active = null WHERE active = true AND name = %L;', TG_TABLE_SCHEMA, TG_TABLE_NAME, OLD.name);",
" IF (OLD.name != NEW.name) THEN",
" EXECUTE format('UPDATE %I.%I SET active = null WHERE active = true AND name = %L;', TG_TABLE_SCHEMA, TG_TABLE_NAME, NEW.name);",
' END IF;',
' ELSE',
" EXECUTE format('UPDATE %I.%I SET active = null WHERE active = true AND name = %L;', TG_TABLE_SCHEMA, TG_TABLE_NAME, NEW.name);",
' END IF;',
// Enable new row
' NEW.active := true;',
' RETURN NEW;',
'END;',
'$function$',
'LANGUAGE plpgsql'
].join('\n')
)
.query('CREATE TRIGGER methods_only_one_active_row'+
' BEFORE INSERT OR UPDATE OF active ON methods'+
' FOR EACH ROW WHEN (NEW.active = true)'+
' EXECUTE PROCEDURE ensure_only_one_active_row_trigger()'
);
} | javascript | {
"resource": ""
} | |
q40678 | isInstance | train | function isInstance(node) {
if (node.type === 'Identifier') {
if (currentOptions.angular) {
if (instanceVarsRegExp.angular.test(node.name)) {
return true;
}
} else {
if (instanceVarsRegExp.noangular.test(node.name)) {
return true;
}
}
}
if (node.type === 'CallExpression') {
if (isConstructor(node.callee)) {
return true;
}
if (node.callee.type === 'MemberExpression') {
if (isInstance(node.callee.object)) {
if (node.callee.property.type === 'Identifier' &&
constants.METHODS.CHAIN.indexOf(node.callee.property.name) !== -1) {
return true;
}
}
}
}
return false;
} | javascript | {
"resource": ""
} |
q40679 | DecisionPoller | train | function DecisionPoller(name, domain, options) {
if (!(this instanceof DecisionPoller)) {
return new DecisionPoller(name, domain, options);
}
if (!_.isString(name)) {
throw new Error('A `name` is required');
}
if (!_.isString(domain)) {
throw new Error('A `domain` is required');
}
this.name = name;
this.domain = domain;
this.options = options || {};
// Make sure taskList is an object of { name: '' }
if (this.options.taskList && _.isString(this.options.taskList)) {
this.options.taskList = { name: this.options.taskList };
}
// Set default taskList if not defined
if (!this.options.taskList) {
this.options.taskList = { name: this.name + '-tasklist' };
}
/** @private */
this._registrations = [];
this._workflows = [];
this._poller = undefined;
} | javascript | {
"resource": ""
} |
q40680 | getInfo | train | function getInfo(d) {
var p = path.join(d, 'package.json')
return exists(p) ? require(p) : false
} | javascript | {
"resource": ""
} |
q40681 | getPath | train | function getPath() {
var p = info && info.config ? info.config : './config'
if (p.charAt(0) === '/') return p
return path.join(base, p)
} | javascript | {
"resource": ""
} |
q40682 | pathExtend | train | function pathExtend(p) {
if (!exists(p)) return false
loaded.push(p)
return extend(config, require(p))
} | javascript | {
"resource": ""
} |
q40683 | train | function(options, methods){
options = options || {};
// Wrap yes/no methods with a success method
options['success'] = function(result){
if ( methods['isValidResult'](result) ){
if (typeof methods['yes'] === "function") methods['yes'](result);
} else {
if (typeof methods['no'] === "function") methods['no'](result);
}
};
// Set default error method if one is not provided
if ( !options['error'] && (typeof methods['error'] === "function") ) {
options['error'] = methods['error'];
}
return options;
} | javascript | {
"resource": ""
} | |
q40684 | train | function(username, options) {
if ( this._containsCallbacks(options, ['yes', 'no']) ){
options = this._generateCallbacks(options, {
'isValidResult': function(result) {
return result == username;
},
'yes': options['yes'],
'no': options['no'],
'error': options['no']
});
this.hasValidOAuth(options);
} else {
return username == this.getLoggedInUser(options);
}
} | javascript | {
"resource": ""
} | |
q40685 | train | function() {
if( StackMob['useRelativePathForAjax'] ){
// Build "relative path" (also used for OAuth signing)
return StackMob.apiDomain ? StackMob.apiDomain : (this.getHostname() + (this.getPort() ? ':' + this.getPort() : '')) + '/';
} else {
// Use absolute path and operate through CORS
return StackMob.apiDomain ? StackMob.apiDomain : (StackMob['API_SERVER'] + '/');
}
} | javascript | {
"resource": ""
} | |
q40686 | train | function(options) {
options = options || {};
//If we aren't running in OAuth 2.0 mode, then kick out early.
if(!this.isOAuth2Mode()){
if (options && options['error'])
options['error']();
return false;
}
//Check to see if we have all the necessary OAuth 2.0 credentials locally AND if the credentials have expired.
var creds = this.getOAuthCredentials();
var expires = (creds && creds['oauth2.expires']) || 0;
//If no accesstoken, mackey, or expires..
if ( !_.all([creds['oauth2.accessToken'], creds['oauth2.macKey'], expires], _.identity) ){
if (options && options['success']) options['success'](undefined);
return false;
}
if ( !StackMob.hasExpiredOAuth() ) {
//If not expired
if (options && options['success'] ){
options['success']( this.Storage.retrieve('oauth2.user') );
}
return this.Storage.retrieve('oauth2.user');
} else if ( options && options['success']) {
//If expired and async
var originalSuccess = options['success'];
options['success'] = function(input){
var creds = StackMob.getOAuthCredentials();
var loginField = (creds['oauth2.userSchemaInfo'] && creds['oauth2.userSchemaInfo']['loginField']) ?
creds['oauth2.userSchemaInfo']['loginField'] : this['loginField'];
originalSuccess( input[loginField]);
};
this.initiateRefreshSessionCall(options);
} else {
//If expired and sync
return false;
}
} | javascript | {
"resource": ""
} | |
q40687 | train | function() {
var oauth_accessToken = StackMob.Storage.retrieve('oauth2.accessToken');
var oauth_macKey = StackMob.Storage.retrieve('oauth2.macKey');
var oauth_expires = StackMob.Storage.retrieve('oauth2.expires');
var oauth_refreshToken = StackMob.Storage.retrieve(StackMob.REFRESH_TOKEN_KEY);
var userSchemaInfo = StackMob.Storage.retrieve('oauth2.userSchemaInfo');
var oauth_schema = null;
try {
oauth_schema = JSON.parse(userSchemaInfo);
} catch (e) { /* Harmless if this fails (in theory!)*/ }
if (_.every([oauth_accessToken, oauth_macKey, oauth_expires, oauth_refreshToken, oauth_schema])) {
var creds = {
'oauth2.accessToken' : oauth_accessToken,
'oauth2.macKey' : oauth_macKey,
'oauth2.expires' : oauth_expires,
'oauth2.userSchemaInfo' : oauth_schema
};
creds[StackMob.REFRESH_TOKEN_KEY] = oauth_refreshToken;
return creds;
} else {
return {};
}
} | javascript | {
"resource": ""
} | |
q40688 | train | function(options) {
options = options || {};
// Run stuff before StackMob is initialized.
this.initStart(options);
/* DEPRECATED METHODS BELOW */
this.userSchema = options['userSchema']; // DEPRECATED: Use StackMob.User.extend({ schemaName: 'customschemaname' });
this.loginField = options['loginField']; // DEPRECATED: Use StackMob.User.extend({ loginField: 'customloginfield' });
this.passwordField = options['passwordField']; // DEPRECATED: Use StackMob.User.extend({ passwordField: 'custompasswordfield' });
/* DEPRECATED METHODS ABOVE */
this.newPasswordField = 'new_password';
this.publicKey = options['publicKey'];
this.apiVersion = options['apiVersion'] || this.DEFAULT_API_VERSION;
/*
* apiURL (DEPRECATED) - Advaanced Users Only. Use apiDomain instead.
* Used to redirect SDK requests to a different URL.
*
*/
if (typeof options['apiURL'] !== "undefined")
throw new Error("Error: apiURL is no longer supported. The API URL is now automatically set for PhoneGap users.");
/*
* apiDomain - Advanced Users Only. Only set apiDomain to redirect SDK
* requests to a different domain.
*
* Init variable 'apiDomain' should not contain a URL scheme (http:// or https://).
* Scheme will be prepended according to 'secure' init setting.
*/
var apiDomain = options['apiDomain'];
if (typeof apiDomain === "string"){
if (apiDomain.indexOf('http') === 0){
throw new Error("Error: apiDomain should not specify url scheme (http/https). For example, specify api.stackmob.com instead of http://api.stackmob.com. URL Scheme is determined by the 'secure' init variable.");
} else {
if (apiDomain.indexOf('/') == apiDomain.length - 1){
this.apiDomain = apiDomain;
} else {
this.apiDomain = apiDomain + '/';
}
}
}
/*
* useRelativePathForAjax - Advanced Users Only. Use to redirect SDK requests to a
* path relative to the current URL. Will only work for StackMob Hosts that can
* properly proxy requests to api.stackmob.com
*
* HTML5 apps hosted on stackmobapp.com will be set to `true` and use a relative path
* automatically.
*/
var isSMHosted = (this.getHostname().indexOf('.stackmobapp.com') > 0);
this.useRelativePathForAjax = (typeof options['useRelativePathForAjax'] === "boolean") ? options['useRelativePathForAjax'] : isSMHosted;
/*
* secure - Determine which requests should be done over SSL.
* Default the security mode to match the current URL scheme.
*
* If current page is HTTPS, set to SECURE_ALWAYS.
* If current page is HTTP, set to SECURE_NEVER.
* Otherwise, set to SECURE_MIXED.
* Can be overridden by manually specifying a security mode in init().
*/
if (options['secure']) {
this.secure = options['secure'];
} else if (this.getProtocol().indexOf("https:") == 0) {
this.secure = this.SECURE_ALWAYS;
} else if (this.getProtocol().indexOf("http:") == 0) {
this.secure = this.SECURE_NEVER;
} else {
this.secure = this.SECURE_MIXED;
}
this.ajax = options['ajax'] || this.ajax;
this.initEnd(options);
return this;
} | javascript | {
"resource": ""
} | |
q40689 | train | function(facebookAccessToken, options) {
options = options || {};
options['data'] = options['data'] || {};
_.extend(options['data'], {
"fb_at" : facebookAccessToken,
"token_type" : "mac"
});
(this.sync || Backbone.sync).call(this, "linkUserWithFacebook", this, options);
} | javascript | {
"resource": ""
} | |
q40690 | train | function(b){
/*
* Naming convention: A.or(B)
*/
if (typeof this.orId == "undefined"){
/*
* If A is a normal AND query:
* Clone A into newQuery
* Clear newQuery's params
* Assign OR Group# (1)
* Prefix A params with and[#+1]
* Prefix B params with and[#+1]
* Prefix all params with or[#]
* Set all of the above as newQuery.params
* Return newQuery
*/
var a = this;
var newQuery = this.clone();
newQuery['params'] = {}; // Reset params that will be populated below
newQuery['orId'] = 1; // Only allowed one OR, otherwise orCount++;
newQuery['andCount'] = 1; // And counts are per or-clause
var andCounter, keys, parsedAndString;
// Determine [and#] prefix for A
keys = _.keys(a.params);
parsedAndString = "";
if (keys.length > 1) {
andCounter = newQuery['andCount']++;
parsedAndString = andString(andCounter);
}
// Copy A's params to newQuery
for (var key in a['params']){
var newKey = orString(newQuery['orId']) + parsedAndString + key;
newQuery['params'][newKey] = a['params'][key];
}
// Determine [and#] prefix for B
keys = _.keys(b.params);
parsedAndString = "";
if (keys.length > 1) {
andCounter = newQuery['andCount']++;
parsedAndString = andString(andCounter);
}
// Copy B's params to newQuery
for (key in b['params']){
var newKey = orString(newQuery['orId']) + parsedAndString + key;
if (typeof newQuery['params'][newKey] !== "undefined") {
throw new Error("Error: You are attempting to OR two or more values for the same field. You should use an mustBeOneOf method instead.");
} else {
newQuery['params'][newKey] = b['params'][key];
}
}
return newQuery;
} else {
/*
* If A is already an OR query:
* Clone A into newQuery
* Prefix B with and[#+1]
* Prefix B with or[A.orId]
* Add B's params to newQuery
* Return newQuery
*/
var a = this;
var newQuery = this.clone();
// Determine [and#] prefix for B
keys = _.keys(b.params);
parsedAndString = "";
if (keys.length > 1) {
andCounter = newQuery['andCount']++;
parsedAndString = andString(andCounter)
}
// Copy B's params to newQuery
for (key in b['params']){
var newKey = orString(newQuery['orId']) + parsedAndString + key;
if (typeof newQuery['params'][newKey] !== "undefined") {
throw new Error("Error: You are attempting to OR two or more values for the same field. You should use an mustBeOneOf method instead.");
} else {
newQuery['params'][newKey] = b['params'][key];
}
}
return newQuery;
}
} | javascript | {
"resource": ""
} | |
q40691 | train | function(b){
/*
* Naming convention: A.or(B)
*
* Combine all params of a and b into one object
*/
var a = this;
var newQuery = this.clone();
for (var key in b['params']){
newQuery['params'][key] = b['params'][key];
}
return newQuery;
} | javascript | {
"resource": ""
} | |
q40692 | build | train | function build(
projectOptions, buildOptions, outDirsAsync, cssRenamingFileAsync) {
var inputFilesAsync = resolveInputsAsync(projectOptions);
return outDirsAsync.then(function(outDirs) {
var transitiveClosureDepsAsync =
closureDepCalculator.calcDeps(projectOptions, buildOptions, outDirs);
return kew.all([inputFilesAsync, transitiveClosureDepsAsync])
.then(function(results) {
var inputFiles = results[0];
var transitiveClosureDeps = results[1];
var resolvedProjectOptions =
resolveProjectOptions(projectOptions, inputFiles);
var jsModules = jsModuleManager.calcInputFiles(
resolvedProjectOptions, transitiveClosureDeps);
return compileAndOutputJs(resolvedProjectOptions, buildOptions,
outDirs, cssRenamingFileAsync, jsModules);
});
});
} | javascript | {
"resource": ""
} |
q40693 | getNodesMetaData | train | function getNodesMetaData(rootEl) {
let elMeta = [];
let toVisit = [rootEl];
let current = {el: rootEl, path: [], isPre: $.tag(rootEl) === 'PRE'};
//generate paths for comment and text nodes. There's no way to quickly retrieve them
//need to deeply traverse the DOM tree
while (current) {
let {el, isPre, path} = current;
let childNodes = $.childNodes(el);
for (let i = 0; i < childNodes.length; i++) {
let childNode = childNodes[i];
if ($.isText(childNode)) {
let {meta, delta} = getTextMetaData(rootEl, i, childNode, path, !isPre);
elMeta.push(...meta);
i += delta;
} else if ($.isElement(childNode)) {
let name = $.getAttr(childNode, ATTR);
if (name && $.tag(childNode) === 'SCRIPT') {
let {meta, delta} = getContainerMetaData(rootEl, i, childNode, path, name);
elMeta.push(...meta);
i += delta;
} else {
toVisit.push({
el: childNode,
path: path.concat(i),
isPre: current.isPre || $.tag(childNode) === 'PRE'
});
}
}
}
toVisit.shift();
current = toVisit[0];
}
let elementMeta = getElementsMetaData(rootEl);
elMeta.push(...elementMeta);
//we need to sort the elements in order of their depth, so that they can be updated
//from bottom up when ultimately passed to a component.
return elMeta.sort((a, b) => b.depth - a.depth);
} | javascript | {
"resource": ""
} |
q40694 | getParserConfiguration | train | function getParserConfiguration(target, config) {
target = target || this;
config = config || {alias: {}, flags: [], options: []};
var k, arg, key
, conf = this.configure();
var no = /^\[?no\]?/, nor = /(\[no-?\]-?)/;
for(k in target._options) {
arg = target._options[k];
// misconfigured option, not a valid instance
if(typeof arg.isArgument !== 'function') continue;
if(!arg.isFlag() && !arg.isOption()) {
continue;
}
var names = arg.names().slice(0);
names.forEach(function(nm, index, arr) {
arr[index] = nm.replace(nor, '');
})
key = arg.key();
//console.log('key: %s', key);
if(no.test(key)) {
// this works around an issue with args such as --noop
// without the charAt test the id is *op*
// ensuring the first character is uppercase is akin to
// checking the declaration was '[no]-'
if(/^[A-Z]$/.test(key.charAt(2))) {
key = key.replace(no, '');
key = key.charAt(0).toLowerCase() + key.slice(1);
}
//console.log('final key: %s', key);
}
config.alias[names.join(' ')] = key;
if(arg.isFlag()) {
config.flags = config.flags.concat(names);
}else{
config.options = config.options.concat(names);
}
}
// TODO: sometimes child options have the same keys
// TODO: as top-level options, these duplicates can be removed
for(k in target._commands) {
getParserConfiguration.call(this, target._commands[k], config);
}
if(conf.variables && conf.variables.prefix) {
config.vars = {variables: conf.variables.prefix};
}
return config;
} | javascript | {
"resource": ""
} |
q40695 | next | train | function next(actionData) {
index++;
if(index === store.middlewares.length) {
done(actionData);
} else {
store.middlewares[index](store, actionName, actionData, next);
}
} | javascript | {
"resource": ""
} |
q40696 | checkArgumentType | train | function checkArgumentType(argument, position, type) {
let wrongTypeOf = typeof argument !== type;
let isCheckObject = type === 'object';
let n = isCheckObject ? 'n' : '';
if (isCheckObject && (wrongTypeOf || argument.constructor !== Object) || wrongTypeOf) {
throw new TypeError('A ' + position + ' argument must be a' + n + ' ' + type + '.');
}
} | javascript | {
"resource": ""
} |
q40697 | onResponseFinished | train | function onResponseFinished() {
// Resolve the payload from the 'request' and 'response' objects,
// and send it to the Jarmo server, catching any errors.
var payload = config.resolve(req, res, Date.now() - start);
if(!payload) {
// If the payload is falsy we don't send the data. This allows
// for some ad hoc filtering with custom resolve functions.
return removeListeners();
}
return send(config.host, config.port, payload, function(err) {
if(err) {
config.error(err);
}
return removeListeners();
});
} | javascript | {
"resource": ""
} |
q40698 | removeListeners | train | function removeListeners() {
res.removeListener('error', removeListeners);
res.removeListener('close', removeListeners);
res.removeListener('finish', onResponseFinished);
} | javascript | {
"resource": ""
} |
q40699 | send | train | function send(host, port, payload, callback) {
// Create a Buffer of the JSON stringified payload, so we can send it.
var data = new Buffer(JSON.stringify(payload));
// Resolve or reject the promise once the we have at least attempted to
// send the payload. Should we add some sort of a retry on error?
return client.send(data, 0, data.length, port, host, callback);
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.