_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q34800 | DocAction | train | function DocAction(docStr) {
return function (target, propertyKey, descriptor) {
let m = exports.globalKCState.getOrInsertController(target.constructor).getOrInsertMethod(propertyKey);
m.docString = docStr;
};
} | javascript | {
"resource": ""
} |
q34801 | OpenApiResponse | train | function OpenApiResponse(httpCode, description, type) {
return function (target, propertyKey, descriptor) {
let m = exports.globalKCState.getOrInsertController(target.constructor).getOrInsertMethod(propertyKey);
httpCode = httpCode.toString();
m.openApiResponses[httpCode] = { description: description, type: type };
};
} | javascript | {
"resource": ""
} |
q34802 | async | train | function async(schema, values, optionalOptions, callbackFn) {
var options, callback;
options = optionalOptions || {};
callback = callbackFn || optionalOptions;
process.nextTick(_async);
function _async() {
deref(schema, options, function (err, derefSchema) {
var result;
if (err) {
callback(err);
} else {
result = normalize(derefSchema, values, options);
callback(null, result);
}
});
}
} | javascript | {
"resource": ""
} |
q34803 | Squeak | train | function Squeak(opts) {
if (!(this instanceof Squeak)) {
return new Squeak(opts);
}
EventEmitter.call(this);
this.opts = opts || {};
this.align = this.opts.align !== false;
this.indent = this.opts.indent || 2;
this.separator = this.opts.separator || ' : ';
this.stream = this.opts.stream || process.stderr || consoleStream();
this.types = [];
} | javascript | {
"resource": ""
} |
q34804 | hook | train | function hook(cps, section) {
var i, len;
if (section["section header"] === "empty") {
if (section["data"]) {
// Guess it's a claim
len = section["data"].length;
for (i = 0; i < len; i++) {
if (section["data"][i]["claim number"]) {
section["section header"] = "claim summary";
if (!section["claim number"]) {
section["claim number"] = section["data"][i]["claim number"];
}
break;
}
}
}
}
if (section["section header"] === "claim" || section["section header"] === "claim summary") {
if (!section["claim number"]) {
if (section["data"]) {
len = section["data"].length;
for (i = 0; i < len; i++) {
if (section["data"][i]["claim number"]) {
section["claim number"] = section["data"][i]["claim number"];
break;
}
}
}
}
}
} | javascript | {
"resource": ""
} |
q34805 | elixir | train | function elixir(file, buildDirectory) {
if (!buildDirectory) {
buildDirectory = 'build';
}
var manifestPath = path.join(publicPath(buildDirectory), 'rev-manifest.json');
var manifest = require(manifestPath);
if (isset(manifest[file])) {
return '/'+ str.trim(buildDirectory + '/' + manifest[file], '/');
}
throw new Error("File " + file + " not defined in asset manifest.");
} | javascript | {
"resource": ""
} |
q34806 | train | function(states, targets, transitions) {
initMethods.forEach( function(method) {
method(states, targets, transitions);
});
} | javascript | {
"resource": ""
} | |
q34807 | parseExtraVars | train | function parseExtraVars(extraVars) {
if (!(_.isString(extraVars))) {
return undefined;
}
const myVars = _.split(extraVars, ' ').map(it => {
const v = _.split(it, '=');
if ( v.length != 2 )
throw new Error("Can't parse variable");
return v;
});
return _.fromPairs(myVars);
} | javascript | {
"resource": ""
} |
q34808 | parseArgs | train | function parseArgs(argv) {
debug('parseArgs argv: ', argv);
// default action
var action = 'deploy';
if ( argv['_'].length >= 1 ) {
action = argv['_'][0];
}
failIfEmpty('e', 'environment', argv);
failIfAbsent('e', 'environment', argv);
if ('s' in argv || 'stacks' in argv) failIfEmpty('s', 'stacks', argv);
return {
environment: argv['e'] || argv['environment'],
extraVars: parseExtraVars(argv['x'] || argv['extraVars']),
action: action,
region: argv['r'] || argv['region'],
profile: argv['p'],
cfg: argv['c'] || argv['config'],
stackFilters: argv['s'] || argv['stacks'] || undefined
};
} | javascript | {
"resource": ""
} |
q34809 | loadConfigFile | train | async function loadConfigFile(filePath) {
const f = await Promise.any(
_.map(['.yml', '.yaml', '.json', ''], async(ext) =>
await utils.fileExists(`${filePath}${ext}`)));
if (f) {
return loadYaml(await fs.readFileAsync(f));
}
return undefined;
} | javascript | {
"resource": ""
} |
q34810 | extractAttributeFields | train | function extractAttributeFields(attributeFields) {
var attributes = {};
if (attributeFields) {
for (var field in attributeFields) {
if (attributeFields[field].length > 0) {
attributes[field] = attributeFields[field][0];
}
}
}
return attributes;
} | javascript | {
"resource": ""
} |
q34811 | formatProfileData | train | function formatProfileData(profileData) {
var profile;
if (profileData) {
profile = extractAttributeFields(profileData.attributes);
profile.username = profileData.username;
profile.email = profileData.email;
}
return profile;
} | javascript | {
"resource": ""
} |
q34812 | f1 | train | function f1(settings) {
if(!(this instanceof f1)) {
return new f1(settings);
}
settings = settings || {};
var emitter = this;
var onUpdate = settings.onUpdate || noop;
var onState = settings.onState || noop;
// this is used to generate a "name" for an f1 instance if one isn't given
numInstances++;
this.onState = function() {
emitter.emit.apply(emitter, getEventArgs('state', arguments));
if(onState) {
onState.apply(undefined, arguments);
}
};
this.onUpdate = function() {
emitter.emit.apply(emitter, getEventArgs('update', arguments));
if(onUpdate) {
onUpdate.apply(undefined, arguments);
}
};
this.name = settings.name || 'ui_' + numInstances;
this.isInitialized = false;
this.data = null; // current animation data
this.defTargets = null;
this.defStates = null;
this.defTransitions = null;
this.parser = null;
if(settings.transitions) {
this.transitions(settings.transitions);
}
if(settings.states) {
this.states(settings.states);
}
if(settings.targets) {
this.targets(settings.targets);
}
if(settings.parsers) {
this.parsers(settings.parsers);
}
// kimi is the man who does all the work under the hood
this.driver = kimi( {
manualStep: settings.autoUpdate === undefined ? false : !settings.autoUpdate,
onState: _onState.bind(this),
onUpdate: _onUpdate.bind(this)
});
} | javascript | {
"resource": ""
} |
q34813 | train | function(transitions) {
this.defTransitions = Array.isArray(transitions) ? transitions : Array.prototype.slice.apply(arguments);
return this;
} | javascript | {
"resource": ""
} | |
q34814 | train | function(parsersDefinitions) {
// check that the parsersDefinitions is an object
if(typeof parsersDefinitions !== 'object' || Array.isArray(parsersDefinitions)) {
throw new Error('parsers should be an Object that contains arrays of functions under init and update');
}
this.parser = this.parser || getParser();
this.parser.add(parsersDefinitions);
return this;
} | javascript | {
"resource": ""
} | |
q34815 | train | function(initState) {
if(!this.isInitialized) {
this.isInitialized = true;
var driver = this.driver;
if(!this.defStates) {
throw new Error('You must define states before attempting to call init');
} else if(!this.defTransitions) {
throw new Error('You must define transitions before attempting to call init');
} else if(!this.parser) {
throw new Error('You must define parsers before attempting to call init');
} else if(!this.defTargets) {
throw new Error('You must define targets before attempting to call init');
} else {
parseStates(driver, this.defStates);
parseTransitions(driver, this.defStates, this.defTransitions);
this.parser.init(this.defStates, this.defTargets, this.defTransitions);
driver.init(initState);
}
if(global.__f1__) {
global.__f1__.init(this);
}
}
return this;
} | javascript | {
"resource": ""
} | |
q34816 | train | function(pathToTarget, target, parserDefinition) {
var data = this.data;
var parser = this.parser;
var animationData;
// if parse functions were passed in then create a new parser
if(parserDefinition) {
parser = new getParser(parserDefinition);
}
// if we have a parser then apply the parsers (parsers set css etc)
if(parser) {
if(typeof pathToTarget === 'string') {
pathToTarget = pathToTarget.split('.');
}
animationData = data[ pathToTarget[ 0 ] ];
for(var i = 1, len = pathToTarget.length; i < len; i++) {
animationData = animationData[ pathToTarget[ i ] ];
}
parser.update(target, animationData);
}
} | javascript | {
"resource": ""
} | |
q34817 | train | function(options){
this.type = options.type || EJS.type;
this.cache = options.cache != null ? options.cache : EJS.cache;
this.text = options.text || null;
this.name = options.name || null;
this.ext = options.ext || EJS.ext;
this.extMatch = new RegExp(this.ext.replace(/\./, '\.'));
} | javascript | {
"resource": ""
} | |
q34818 | train | function(el, type, event) {
if (!el) {
// emit for ALL elements
el = document.getElementsByTagName('*');
var i = el.length;
while (i--) if (el[i].nodeType === 1) {
emit(el[i], type, event);
}
return;
}
event = event || {};
event.target = event.target || el;
event.type = event.type || type;
// simulate bubbling
while (el) {
var data = DOM.getData(el, 'events')
, handle = data && data[type];
if (handle) {
event.currentTarget = el;
var ret = handle.call(el, event);
if (ret === false || event.cancelBubble) break;
}
el = el.parentNode
|| el.ownerDocument
|| el.defaultView
|| el.parentWindow;
}
} | javascript | {
"resource": ""
} | |
q34819 | Package | train | function Package(name)
{
var dotBowerJson = Package._readBowerJson(name) || {};
var overrides = globalOverrides[name] || {};
this.name = name;
this.installed = !! dotBowerJson.name;
this.main = overrides.main || dotBowerJson.main || [];
this.dependencies = overrides.dependencies || dotBowerJson.dependencies || [];
} | javascript | {
"resource": ""
} |
q34820 | StartSession | train | function StartSession(app, next) {
this.__app = app;
this.__next = next;
/**
* Session config
*/
this.__config = this.__app.config.get('session');
this.sessionHandler = app.sessionHandler;
} | javascript | {
"resource": ""
} |
q34821 | WorkflowProcessStepsController | train | function WorkflowProcessStepsController($scope, $state, wfmService, $timeout, $stateParams) {
var self = this;
var workorderId = $stateParams.workorderId;
function updateWorkflowState(workorder) {
//If the workflow is complete, then we can switch to the summary view.
if (wfmService.isCompleted(workorder)) {
return $state.go('app.workflowProcess.complete', {
workorderId: workorder.id
});
}
if (!wfmService.isOnStep(workorder)) {
return $state.go('app.workflowProcess.begin', {
workorderId: workorder.id
});
}
$timeout(function() {
self.workorder = workorder;
self.workflow = workorder.workflow;
self.result = workorder.results;
self.stepIndex = wfmService.getCurrentStepIdx(workorder);
self.stepCurrent = wfmService.getCurrentStep(workorder);
});
}
self.back = function() {
wfmService.previousStep(workorderId)
.then(updateWorkflowState)
.catch(console.error);
};
self.triggerCompleteStep = function(submission) {
wfmService.completeStep(workorderId, submission)
.then(updateWorkflowState)
.catch(console.error);
};
self.triggerBackStep = function() {
self.back();
};
wfmService.readWorkOrder(workorderId).then(updateWorkflowState);
} | javascript | {
"resource": ""
} |
q34822 | train | function(sel) {
var cap, param;
if (typeof sel !== 'string') {
if (sel.length > 1) {
var func = []
, i = 0
, l = sel.length;
for (; i < l; i++) {
func.push(parse(sel[i]));
}
l = func.length;
return function(el) {
for (i = 0; i < l; i++) {
if (!func[i](el)) return;
}
return true;
};
}
// optimization: shortcut
return sel[0] === '*'
? selectors['*']
: selectors.type(sel[0]);
}
switch (sel[0]) {
case '.': return selectors.attr('class', '~=', sel.substring(1));
case '#': return selectors.attr('id', '=', sel.substring(1));
case '[': cap = /^\[([\w-]+)(?:([^\w]?=)([^\]]+))?\]/.exec(sel);
return selectors.attr(cap[1], cap[2] || '-', unquote(cap[3]));
case ':': cap = /^(:[\w-]+)\(([^)]+)\)/.exec(sel);
if (cap) sel = cap[1], param = unquote(cap[2]);
return param ? selectors[sel](param) : selectors[sel];
case '*': return selectors['*'];
default: return selectors.type(sel);
}
} | javascript | {
"resource": ""
} | |
q34823 | train | function(sel) {
var filter = []
, comb = combinators.noop
, qname
, cap
, op
, len;
// add implicit universal selectors
sel = sel.replace(/(^|\s)(:|\[|\.|#)/g, '$1*$2');
while (cap = /\s*((?:\w+|\*)(?:[.#:][^\s]+|\[[^\]]+\])*)\s*$/.exec(sel)) {
len = sel.length - cap[0].length;
cap = cap[1].split(/(?=[\[:.#])/);
if (!qname) qname = cap[0];
filter.push(comb(parse(cap)));
if (len) {
op = sel[len - 1];
// if the combinator doesn't exist,
// assume it was a whitespace.
comb = combinators[op] || combinators[op = ' '];
sel = sel.substring(0, op !== ' ' ? --len : len);
} else {
break;
}
}
// compile to a single function
filter = make(filter);
// optimize the first qname
filter.qname = qname;
return filter;
} | javascript | {
"resource": ""
} | |
q34824 | LevArray | train | function LevArray (data, str) {
var result = [];
for (var i = 0; i < data.length; ++i) {
var cWord = data[i];
result.push({
l: LevDist(cWord, str)
, w: cWord
});
}
result.sort(function (a, b) {
return a.l > b.l ? 1 : -1;
});
return result;
} | javascript | {
"resource": ""
} |
q34825 | train | function () {
return $http({
method: 'GET',
url: 'https://api.punkapi.com/v2/beers'
}).then(function (response) {
var beerArray = response.data;
var newBeerArray = [];
beerArray.forEach( function (arrayItem) {
newBeerArray.push({
label: arrayItem.name,
value: arrayItem.name
})
});
// return processed items
return newBeerArray;
});
} | javascript | {
"resource": ""
} | |
q34826 | findNextSeparator | train | function findNextSeparator(pattern) {
if ('' == pattern) {
// return empty string if pattern is empty or false (false which can be returned by substr)
return '';
}
// first remove all placeholders from the pattern so we can find the next real static character
pattern = pattern.replace(/\{\w+\}/g, '');
return isset(pattern[0]) && (-1 != SEPARATORS.indexOf(pattern[0])) ? pattern[0] : '';
} | javascript | {
"resource": ""
} |
q34827 | computeRegexp | train | function computeRegexp(tokens, index, firstOptional) {
var token = tokens[index];
if ('text' === token[0]) {
// Text tokens
return str.regexQuote(token[1]);
} else {
// Variable tokens
if (0 === index && 0 === firstOptional) {
// When the only token is an optional variable token, the separator is required
return str.regexQuote(token[1]) + '(?P<' + token[3] + '>' + token[2] + ')?';
} else {
var regexp = str.regexQuote(token[1]) + '(?P<' + token[3] + '>' + token[2] + ')';
if (index >= firstOptional) {
// Enclose each optional token in a subpattern to make it optional.
// "?:" means it is non-capturing, i.e. the portion of the subject string that
// matched the optional subpattern is not passed back.
regexp = "(?:" + regexp;
var nbTokens = tokens.length;
if (nbTokens - 1 == index) {
// Close the optional subpatterns
regexp += ")?".repeat(nbTokens - firstOptional - (0 === firstOptional ? 1 : 0));
}
}
return regexp;
}
}
} | javascript | {
"resource": ""
} |
q34828 | train | function (route) {
var staticPrefix = null;
var hostVariables = [];
var pathVariables = [];
var variables = [];
var tokens = [];
var regex = null;
var hostRegex = null;
var hostTokens = [];
var host;
if ('' !== (host = route.domain())) {
var result = compilePattern(route, host, true);
hostVariables = result['variables'];
variables = variables.concat(hostVariables);
hostTokens = result['tokens'];
hostRegex = result['regex'];
}
var path = route.getPath();
result = compilePattern(route, path, false);
staticPrefix = result['staticPrefix'];
pathVariables = result['variables'];
variables = variables.concat(pathVariables);
tokens = result['tokens'];
regex = result['regex'];
return new CompiledRoute(
staticPrefix,
regex,
tokens,
pathVariables,
hostRegex,
hostTokens,
hostVariables,
_.uniq(variables)
);
} | javascript | {
"resource": ""
} | |
q34829 | acceptParams | train | function acceptParams(str, index) {
var parts = str.split(/ *; */);
var ret = {value: parts[0], quality: 1, params: {}, originalIndex: index};
for (var i = 1; i < parts.length; ++i) {
var pms = parts[i].split(/ *= */);
if ('q' == pms[0]) {
ret.quality = parseFloat(pms[1]);
} else {
ret.params[pms[0]] = pms[1];
}
}
return ret;
} | javascript | {
"resource": ""
} |
q34830 | parseJSON | train | function parseJSON(buf, cb) {
try {
cb(null, JSON.parse(buf));
} catch (err) {
return cb(err);
}
} | javascript | {
"resource": ""
} |
q34831 | multiMapSet | train | function multiMapSet(multimap, key, value) {
if (!multimap.has(key)) {
multimap.set(key, new Set());
}
const values = multimap.get(key);
if (!values.has(value)) {
values.add(value);
return true;
}
return false;
} | javascript | {
"resource": ""
} |
q34832 | transitiveClosure | train | function transitiveClosure(nodeLabels, graph) {
let madeProgress = false;
do {
madeProgress = false;
for (const [ src, values ] of Array.from(nodeLabels.entries())) {
const targets = graph[src];
if (targets) {
for (const target of targets) {
for (const value of values) {
madeProgress = multiMapSet(nodeLabels, target, value) || madeProgress;
}
}
}
}
} while (madeProgress);
} | javascript | {
"resource": ""
} |
q34833 | distrust | train | function distrust(msg, optAstNode) {
const { filename, line } = optAstNode || policyPath[policyPath.length - 2] || {};
const relfilename = options.basedir ? path.relative(options.basedir, filename) : filename;
report(`${ relfilename }:${ line }: ${ msg }`);
mayTrustOutput = false;
} | javascript | {
"resource": ""
} |
q34834 | getContainerName | train | function getContainerName(skip = 0) {
let element = null;
let mixin = null;
for (let i = policyPath.length - (skip * 2); (i -= 2) >= 0;) {
const policyPathElement = policyPath[i];
if (typeof policyPathElement === 'object') {
if (policyPathElement.type === 'Tag') {
element = policyPathElement.name.toLowerCase();
break;
} else if (policyPathElement.type === 'Mixin' && !policyPathElement.call) {
mixin = policyPathElement.name;
break;
}
}
}
return { element, mixin };
} | javascript | {
"resource": ""
} |
q34835 | addGuard | train | function addGuard(guard, expr) {
let safeExpr = null;
if (!isWellFormed(expr)) {
expr = '{/*Malformed Expression*/}';
}
needsRuntime = true;
safeExpr = ` rt_${ unpredictableSuffix }.${ guard }(${ expr }) `;
return safeExpr;
} | javascript | {
"resource": ""
} |
q34836 | addScrubber | train | function addScrubber(scrubber, element, expr) {
let safeExpr = null;
if (!isWellFormed(expr)) {
expr = '{/*Malformed Expression*/}';
}
needsScrubber = true;
safeExpr = ` sc_${ unpredictableSuffix }.${ scrubber }(${ stringify(element || '*') }, ${ expr }) `;
return safeExpr;
} | javascript | {
"resource": ""
} |
q34837 | checkCodeDoesNotInterfere | train | function checkCodeDoesNotInterfere(astNode, exprKey, isExpression) {
let expr = astNode[exprKey];
const seen = new Set();
const type = typeof expr;
if (type !== 'string') {
// expr may be true, not "true".
// This occurs for inferred expressions like valueless attributes.
expr = `${ expr }`;
astNode[exprKey] = expr;
}
let warnedPug = false;
let warnedModule = false;
// Allows check to take into account the context in which a node appears.
// Flattened pairs of [ancestor, keyInAncestorToDescendent].
const jsAstPath = [];
function check(jsAst) {
if (jsAst && typeof jsAst === 'object' && jsAst.type === 'Identifier') {
const { name } = jsAst;
if (/^pug_/.test(name) || name === 'eval') {
if (!warnedPug) {
distrust(`Expression (${ expr }) may interfere with PUG internals ${ jsAst.name }`);
warnedPug = true;
}
} else if (name === 'require' &&
// Allow trusted plugin code to require modules they need.
!(Object.hasOwnProperty.call(astNode, 'mayRequire') && astNode.mayRequire) &&
// Allow require.moduleKeys and require.resolve but not require(moduleId).
!(jsAstPath.length && jsAstPath[jsAstPath.length - 2].type === 'MemberExpression' &&
jsAstPath[jsAstPath.length - 1] === 'object')) {
// Defang expression.
astNode[exprKey] = 'null';
// We trust trusted plugin code and PUG code to use the module's private key
// but not template code.
if (!warnedModule) {
distrust(`Expression (${ expr }) may interfere with module internals ${ jsAst.name }`);
warnedModule = true;
}
}
}
checkChildren(jsAst); // eslint-disable-line no-use-before-define
}
function checkChildren(jsAst) {
if (!seen.has(jsAst)) {
seen.add(jsAst);
const jsAstPathLength = jsAstPath.length;
jsAstPath[jsAstPathLength] = jsAst;
for (const key in jsAst) {
if (Object.hasOwnProperty.call(jsAst, key)) {
jsAstPath[jsAstPathLength + 1] = key;
check(jsAst[key]);
}
}
jsAstPath.length = jsAstPathLength;
}
}
let root = null;
try {
root = isExpression ? parseExpression(expr) : parse(expr);
} catch (exc) {
distrust(`Malformed expression (${ expr })`);
return;
}
check(root);
} | javascript | {
"resource": ""
} |
q34838 | noncifyAttrs | train | function noncifyAttrs(element, getValue, attrs) {
if (nonceValueExpression) {
if (element === 'script' || element === 'style' ||
(element === 'link' && (getValue('rel') || '').toLowerCase() === 'stylesheet')) {
if (attrs.findIndex(({ name }) => name === 'nonce') < 0) {
attrs[attrs.length] = {
name: 'nonce',
val: nonceValueExpression,
mustEscape: true,
};
}
}
}
} | javascript | {
"resource": ""
} |
q34839 | noncifyTag | train | function noncifyTag({ name, block: { nodes } }) {
if (name === 'form' && csrfInputValueExpression) {
nodes.unshift({
type: 'Conditional',
test: csrfInputValueExpression,
consequent: {
type: 'Block',
nodes: [
{
type: 'Tag',
name: 'input',
selfClosing: false,
block: {
type: 'Block',
nodes: [],
},
attrs: [
{
name: 'name',
val: stringify(csrfInputName),
mustEscape: true,
},
{
name: 'type',
val: '\'hidden\'',
mustEscape: true,
},
{
name: 'value',
val: csrfInputValueExpression,
mustEscape: true,
},
],
attributeBlocks: [],
isInline: false,
},
],
},
alternate: null,
});
}
} | javascript | {
"resource": ""
} |
q34840 | apply | train | function apply(x) {
const policyPathLength = policyPath.length;
policyPath[policyPathLength] = x;
if (Array.isArray(x)) {
for (let i = 0, len = x.length; i < len; ++i) {
policyPath[policyPathLength + 1] = i;
apply(x[i]);
}
} else if (x && typeof x === 'object') {
for (const key of Object.getOwnPropertyNames(x)) {
policyPath[policyPathLength + 1] = key;
const valueType = typeof policy[key];
if (valueType === 'function') {
policy[key](x[key]);
} else if (valueType === 'object') {
const policyMember = policy[key][x[key]];
if (typeof policyMember === 'function') {
policyMember(x);
}
}
if (key === 'test' || key === 'expr') {
checkCodeDoesNotInterfere(x, key, true);
}
apply(x[key]);
}
}
policyPath.length = policyPathLength;
} | javascript | {
"resource": ""
} |
q34841 | Plugin | train | function Plugin(script, _interface, options) {
this._script = script
this._options = options || {}
this._initialInterface = _interface || {}
this._connect()
} | javascript | {
"resource": ""
} |
q34842 | train | function (arr) {
var jsonData = {};
_.forEach(arr, function (elem) {
var keys = Object.keys(elem);
_.forEach(keys, function (key) {
var value = elem[key];
jsonData[key] = value;
});
})
return jsonData;
} | javascript | {
"resource": ""
} | |
q34843 | bindAPI | train | function bindAPI (self, api, fnName) {
return api[fnName].bind(self, self.__REQUEST_OPTIONS, self.__CREDENTIALS, self.__TOKEN);
} | javascript | {
"resource": ""
} |
q34844 | ConnectedInstance | train | function ConnectedInstance (requestOptions, authToken, credentials) {
this.__REQUEST_OPTIONS = requestOptions;
this.__TOKEN = authToken;
this.__CREDENTIALS = credentials;
this.SurveyFieldwork = {
status : bindAPI(this, API, 'statusSurveyFieldwork'),
start : bindAPI(this, API, 'startSurveyFieldwork'),
stop : bindAPI(this, API, 'stopSurveyFieldwork')
};
this.DefaultTexts = {
get : bindAPI(this, API, 'getDefaultTexts')
};
this.SurveyTranslations = {
get : bindAPI(this, API, 'getSurveyTranslations'),
add : bindAPI(this, API, 'addSurveyTranslations'),
update : bindAPI(this, API, 'updateSurveyTranslations'),
remove : bindAPI(this, API, 'removeSurveyTranslations')
};
this.SurveyLanguages = {
get : bindAPI(this, API, 'getSurveyLanguages'),
add : bindAPI(this, API, 'addSurveyLanguages'),
update : bindAPI(this, API, 'updateSurveyLanguages'),
remove : bindAPI(this, API, 'removeSurveyLanguages')
};
this.SurveySettings = {
get : bindAPI(this, API, 'getSurveySettings'),
update : bindAPI(this, API, 'updateSurveySettings')
};
this.SurveyScript = {
get : bindAPI(this, API, 'getSurveyScript'),
update : bindAPI(this, API, 'updateSurveyScript')
};
this.SurveyData = {
request : bindAPI(this, API, 'requestSurveyData')
};
this.Surveys = {
get : bindAPI(this, API, 'getSurveys'),
add : bindAPI(this, API, 'addSurveys'),
update : bindAPI(this, API, 'updateSurveys'),
remove : bindAPI(this, API, 'removeSurveys')
};
this.SurveyPublish = {
get : bindAPI(this, API, 'getSurveyPublish'),
update : bindAPI(this, API, 'updateSurveyPublish')
};
this.BackgroundTasks = {
get : bindAPI(this, API, 'getBackgroundTasks')
};
this.InterviewQuality = {
get : bindAPI(this, API, 'getInterviewQuality'),
update : bindAPI(this, API, 'updateInterviewQuality')
};
} | javascript | {
"resource": ""
} |
q34845 | NfieldClient | train | function NfieldClient (defOptions) {
var defaultRequestCliOptions = {
baseUrl : 'https://api.nfieldmr.com/'
};
extend(true, defaultRequestCliOptions, defOptions);
/**
* Sign In api method provided strait with NfieldCliend instance because it doesn't need authentication
*/
this.SignIn = API.signIn.bind(null, defaultRequestCliOptions);
/**
* Returns a new instance of NfieldClient with new request parameters
*/
this.defaults = function defaults (options) {
if (typeof options !== 'object') throw new TypeError('`options` must be an object with request parameters');
return new NfieldClient(options);
};
/**
* Connects NfieldClient to API
* Returns ConnectedInstance
*/
this.connect = function connect (credentials, callback) {
var token = {};
var promise;
if (typeof credentials === 'function') callback = credentials;
promise = API.signIn(defaultRequestCliOptions, credentials).then(function (data) {
if (data[0].statusCode !== 200) {
throw new Error(`${data[0].statusCode}: ${data[0].body.Message}`);
} else {
token = {
AuthenticationToken : data[0].body.AuthenticationToken,
Timestamp : Date.now()
};
return new ConnectedInstance(defaultRequestCliOptions, token, credentials);
}
}).nodeify(callback);
return promise;
};
} | javascript | {
"resource": ""
} |
q34846 | server | train | function server() {
// TODO: Show require express error
var express = require('express')
, app = express();
app.configure(function() {
app.use(express.static(siteBuilder.outputRoot));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
// Map missing trailing slashes for posts
app.get('*', function(req, res) {
var postPath = siteBuilder.outputRoot + req.url + '/';
// TODO: Security
if (req.url.match(/[^/]$/) && existsSync(postPath)) {
res.redirect(req.url + '/');
} else {
res.send('404');
}
});
app.listen(siteBuilder.config.port);
log.info('Listening on port', siteBuilder.config.port);
} | javascript | {
"resource": ""
} |
q34847 | normalizeError | train | function normalizeError(err,pools){
if (!(err instanceof Error)){
err = new Error(err)
}
if (!err._isException){
//Iterate over exceptionPools finding error match
for(let i=0;i<pools.length;i++){
let exception = pools[i]._convert(err)
if (exception) return exception
}
}
return err
} | javascript | {
"resource": ""
} |
q34848 | defaultTransformError | train | function defaultTransformError(err,req){
let body = {
code: err.code,
message: err.message,
data: err.data,
}
if (req._expressDeliverOptions.printErrorStack===true){
body.stack = err.stack
}
if (err.name == 'InternalError' && req._expressDeliverOptions.printInternalErrorData!==true){
delete body.data
}
return {
status:false,
error:body
}
} | javascript | {
"resource": ""
} |
q34849 | getChannel | train | function getChannel(auth, youtube, channelID, callback) {
youtube.channels.list( // Call the Youtube API
{
auth: auth,
part: "snippet, statistics",
order: "date",
id: channelID,
maxResults: 1 // Integer 0-50, default 5
},
function(err, res) {
if (err) {
console.log("The API returned an error: " + err);
} else {
if (res.data.items[0] !== undefined) { // Check if a result was found
var formatedChannel = formatChannelJson(res.data.items[0]) // Format the recieved JSON object
callback(formatedChannel);
} else {
callback([]);
}
}
}
);
} | javascript | {
"resource": ""
} |
q34850 | getChannelUsername | train | function getChannelUsername(auth, youtube, username, callback) {
youtube.channels.list( // Call the Youtube API
{
auth: auth,
part: "snippet, statistics",
order: "date",
forUsername: username,
maxResults: 1 // Integer 0-50, default 5
},
function(err, res) {
if (err) {
console.log("The API returned an error: " + err);
} else {
if (res.data.items[0] !== undefined) { // Check if a result was found
var formatedChannel = formatChannelJson(res.data.items[0]) // Format the recieved JSON object
callback(formatedChannel);
} else {
callback([]);
}
}
}
);
} | javascript | {
"resource": ""
} |
q34851 | getVideos | train | function getVideos(auth, youtube, channel_id, count, callback) {
youtube.search.list( // Call the Youtube API
{
auth: auth,
part: "snippet",
order: "date",
maxResults : count, //integer 0-50, default 5
channelId: channel_id
},
function(err, res) {
if (err) {
console.log("The API returned an error: " + err);
} else {
if (res.data.items !== undefined) { // Check if a result was found
getVideoStatistics(auth, youtube, res.data.items, count, callback); // Get video statistics
} else {
callback([]);
}
}
});
} | javascript | {
"resource": ""
} |
q34852 | getVideoStatistics | train | function getVideoStatistics(auth, youtube, items, count, callback) {
// Convert the video ID:s of the provided videos to the appropriate format
var IDs = "";
if (Array.isArray(items)) {
for (var i = 0; i < items.length; i++) {
if (i != 0) {
IDs += ", "
}
IDs += items[i].id.videoId;
}
}
youtube.videos.list( // Call the Youtube API
{
auth: auth,
part: "statistics",
id: IDs,
maxResults: count //integer 0-50, default 5
},
function(err, res) {
if (err) {
console.log("The API returned an error: " + err);
} else {
var formatedVideos = formatVideosJson(items, res.data.items); // Format the recieved JSON object filled with videos
callback(formatedVideos);
}
});
} | javascript | {
"resource": ""
} |
q34853 | formatVideosJson | train | function formatVideosJson(videos, statistics) {
var formatedVideos = []
if (Array.isArray(videos)) {
for (var i = 0; i < videos.length; i++) {
var video = {
"platform": "Youtube",
"channel_id": videos[i].snippet.channelId,
"channel_url": "",
"channel_title": videos[i].snippet.channelTitle,
"video_id": videos[i].id.videoId,
"video_url": "",
"video_embeded_url": "",
"video_title": videos[i].snippet.title,
"video_description": videos[i].snippet.description,
"video_created_at": (new Date(videos[i].snippet.publishedAt).toISOString()),
"video_thumbnail_url": videos[i].snippet.thumbnails.high.url,
"video_view_count": "",
"video_like_count": "",
"video_dislike_count": "",
"video_comment_count": ""
};
video.channel_url = "https://www.youtube.com/channel/" + video.channel_id;
video.video_url = "https://www.youtube.com/watch?v=" + video.video_id;
video.video_embeded_url = "https://www.youtube.com/embed/" + video.video_id;
formatedVideos.push(video);
}
}
// Add statistics
if (Array.isArray(statistics)) {
for (var i = 0; i < statistics.length; i++) {
formatedVideos[i].video_view_count = statistics[i].statistics.viewCount;
formatedVideos[i].video_like_count = statistics[i].statistics.likeCount;
formatedVideos[i].video_dislike_count = statistics[i].statistics.dislikeCount;
formatedVideos[i].video_comment_count = statistics[i].statistics.commentCount;
}
}
return formatedVideos;
} | javascript | {
"resource": ""
} |
q34854 | train | function() {
// run iterator for this item
iterator(arr[current], function(err) {
// check for any errors with this element
if (err) {
callback(err, yielded);
} else {
// move onto the next element
current++;
if (current === arr.length) {
// all done
callback(null, yielded);
} else {
var now = +(new Date());
// check if we need to take a break at all
if (now > endTime) {
// reset start and end time
startTime = now;
endTime = startTime + workTime;
yielded = true;
// prioritize setImmediate
if (immediate) {
immediate(function() {
iterate();
});
} else {
// if we're not doing an immediate yield, also add yield time
endTime += yieldTime;
setTimeout(function() {
iterate();
}, yieldTime);
}
} else {
// work on the next item immediately
iterate();
}
}
}
});
} | javascript | {
"resource": ""
} | |
q34855 | combineMediaQuery | train | function combineMediaQuery(base, additional) {
var finalQuery = [];
base.forEach(function(b) {
additional.forEach(function(a) {
finalQuery.push(b + ' and ' + a);
});
});
return finalQuery.join(', ');
} | javascript | {
"resource": ""
} |
q34856 | query | train | function query(url, init) {
// Reject if user provided no arguments
if (!url || typeof url !== 'string') {
return Promise.reject(
"Expected a non-empty string for 'url' but received: " + typeof url
);
}
// Reject if user provided an invalid second argument
if (!init) {
return Promise.reject(
"Expected an object or a non-empty string for 'init' but received: " +
typeof init
);
}
// The user can just pass in a query string directly; however, if they
// pass in an object instead, we need to validate the properties.
if (typeof init !== 'string') {
// Reject if there's no valid fields or body parameter
if (
typeof init !== 'object' ||
init.constructor === Array ||
((!init.fields || typeof init.fields !== 'string') &&
(!init.body || typeof init.body !== 'string'))
) {
return Promise.reject(
"Expected a string for 'init.fields' or 'init.body' but received: " +
typeof init
);
}
}
try {
var fetchOptions = configureFetch(init);
} catch (err) {
return Promise.reject(err);
}
// Reject if something went wrong with building the request
if (!fetchOptions) {
return Promise.reject(
setTypeError(
'Something went wrong when setting the fetch options: ' +
JSON.stringify(fetchOptions)
)
);
}
return fetch(url, fetchOptions);
} | javascript | {
"resource": ""
} |
q34857 | train | function (key, defaultValue) {
var body = self.body || {};
var query = self.query || {};
if (null != body[key]) return body[key];
if (null != query[key]) return query[key];
return defaultValue;
} | javascript | {
"resource": ""
} | |
q34858 | train | function (key) {
var keys = Array.isArray(key) ? key : arguments;
for (var i = 0; i < keys.length; i++) {
if (isEmptyString(keys[i])) return false;
}
return true;
} | javascript | {
"resource": ""
} | |
q34859 | train | function (key) {
var keys = Array.isArray(key) ? key : arguments;
var input = self.input.all();
var results = {};
for (var i = 0; i < keys.length; i++) {
results[keys[i]] = input[keys[i]];
}
return results;
} | javascript | {
"resource": ""
} | |
q34860 | train | function (filter, keys) {
if (self.session) {
var flash = isset(filter) ? self.input[filter](keys) : self.input.all();
self.session.flash('_old_input', flash);
}
} | javascript | {
"resource": ""
} | |
q34861 | train | function (key, defaultValue) {
var input = self.session.get('_old_input', []);
// Input that is flashed to the session can be easily retrieved by the
// developer, making repopulating old forms and the like much more
// convenient, since the request's previous input is available.
if (key) {
return isset(input[key]) ? input[key] : defaultValue;
} else {
return input;
}
} | javascript | {
"resource": ""
} | |
q34862 | train | function (key) {
if (self.files) {
return self.files[key] ? self.files[key] : null;
}
} | javascript | {
"resource": ""
} | |
q34863 | Result | train | function Result( notation, value, rolls ) {
this.notation = notation;
this.value = value;
this.rolls = rolls;
} | javascript | {
"resource": ""
} |
q34864 | bytesToWords | train | function bytesToWords(bytes) {
var bytes_count = bytes.length,
bits_count = bytes_count << 3,
words = new Uint32Array((bytes_count + 64) >>> 6 << 4);
for (var i = 0, n = bytes.length; i < n; ++i)
words[i >>> 2] |= bytes.charCodeAt(i) << ((i & 3) << 3);
words[bytes_count >> 2] |= 0x80 << (bits_count & 31); // append "1" bit to message
words[words.length - 2] = bits_count;
return words;
} | javascript | {
"resource": ""
} |
q34865 | Id | train | function Id(s, r, m, isSimple) {
this.s = s;
this.r = r;
this.m = m;
Object.defineProperty(this, '_simple', {
value: isSimple
});
} | javascript | {
"resource": ""
} |
q34866 | train | function (seedAry, match) {
var res = $.replicate(seedAry.length, []);
seedAry.forEach(function (xps, x) {
// NB: while we are not writing 1-1 from seedAry to res, we are always
// making sure not to overwrite what we had in previous iterations
if (xps.indexOf(match.p[0]) < 0) {
res[x] = res[x].concat(xps);
return;
}
// always tieCompute match because only strict mode has guaranteed non-ties
var sorted = $.zip(match.p, match.m).sort(Base.compareZip);
Base.matchTieCompute(sorted, 0, function (p, pos) {
res[x+pos-1].push(p);
});
});
return res;
} | javascript | {
"resource": ""
} | |
q34867 | WorkorderListController | train | function WorkorderListController($scope, workorderService, workorderFlowService, $q, workorderStatusService) {
var self = this;
var _workorders = [];
self.workorders = [];
function refreshWorkorders() {
// Needs $q.when to trigger angular's change detection
workorderService.list().then(function(workorders) {
_workorders = workorders;
self.updateFilter();
});
}
refreshWorkorders();
self.selectWorkorder = function(event, workorder) {
workorderFlowService.workorderSelected(workorder);
event.preventDefault();
event.stopPropagation();
};
self.isWorkorderShown = function(workorder) {
return self.shownWorkorder === workorder;
};
self.applyFilter = function(term) {
self.term = term;
self.updateFilter();
};
self.updateFilter = _.debounce(function() {
$scope.$apply(function() {
if (!self.term) {
return self.workorders = _workorders;
}
if (self.term.length > 3) {
var term = self.term.toLowerCase();
self.workorders = _workorders.filter(function(workflow) {
return String(workflow.title).toLowerCase().indexOf(term) !== -1
|| String(workflow.id).indexOf(term) !== -1;
});
}
});
}, 300);
self.getColorIcon = function(workorder) {
if (!workorder || !workorder.status) {
return workorderStatusService.getStatusIconColor('').statusColor;
} else {
return workorderStatusService.getStatusIconColor(workorder.status).statusColor;
}
};
self.setupEventListenerHandlers = function() {
workorderService.on('create', function(workorder) {
_workorders.push(workorder);
self.updateFilter();
});
workorderService.on('remove', function(workorder) {
_.remove(_workorders, function(w) {
return w.id === workorder.id;
});
self.updateFilter();
});
workorderService.on('update', function(workorder) {
var idx = _.findIndex(_workorders, function(w) {
return w.id === workorder.id;
});
_workorders.splice(idx, 1, workorder);
self.updateFilter();
});
};
if (workorderService.on) {
self.setupEventListenerHandlers();
} else if (workorderService.subscribeToDatasetUpdates) {
// use the single method to update workorders via sync
workorderService.subscribeToDatasetUpdates(refreshWorkorders);
}
} | javascript | {
"resource": ""
} |
q34868 | fileExists | train | async function fileExists(f) {
debug(`fileExists called with: ${JSON.stringify(arguments)}`);
try {
await fs.statAsync(f);
return f;
} catch (e) {
throw e;
}
} | javascript | {
"resource": ""
} |
q34869 | execTasks | train | async function execTasks(tasks, taskType) {
debug(`execTasks: called for ${taskType}`);
if (!(_.isEmpty(tasks))) {
if (taskType) console.log(`running ${taskType}...`);
const output = await Promise.mapSeries(tasks, async(task) => {
const result = await execTask(task);
if (_.isString(result.stdout) && (!_.isEmpty(result.stdout)))
console.log(result.stdout.trim());
if (_.isString(result.stderr) && (!_.isEmpty(result.stderr)))
console.log(result.stderr.trim());
return result;
});
return output;
}
debug("execTasks: nothing to do; resolving");
return;
} | javascript | {
"resource": ""
} |
q34870 | Roll | train | function Roll( dice = 20, count = 1, modifier = 0 ) {
this.dice = positiveInteger( dice );
this.count = positiveInteger( count );
this.modifier = normalizeInteger( modifier );
} | javascript | {
"resource": ""
} |
q34871 | train | function(mtx) {
if (mtx && typeof mtx == "object" && mtx.mtx) mtx = mtx.mtx;
if (!mtx) return new Point(this.x,this.y);
var point = svg.createSVGPoint();
point.x = this.x;
point.y = this.y;
point = point.matrixTransform(mtx);
return new this.constructor(point.x,point.y);
} | javascript | {
"resource": ""
} | |
q34872 | Matrix | train | function Matrix(arg) {
if (arg && arguments.length === 1) {
if (arg instanceof window.SVGMatrix) this.mtx = arg.scale(1);
else if (arg instanceof Matrix) this.mtx = arg.mtx.scale(1);
else if (typeof arg == "string") return Matrix.parse(arg);
else throw new Error(arg+" : argument incorrect pour Matrix.");
}
else {
this.mtx = svg && svg.createSVGMatrix();
if (arguments.length === 6) {
var a = arguments, that = this;
['a','b','c','d','e','f'].forEach(function(prop,ind){ that[prop] = a[ind]; });
}
}
} | javascript | {
"resource": ""
} |
q34873 | train | function(str,tag,content) {
return str.replace(regexpTag(tag),function(str,p1,p2) { content && content.push(p2); return ''; });
} | javascript | {
"resource": ""
} | |
q34874 | train | function(data) {
data = data.replace(/{% highlight ([^ ]*) %}/g, '<pre class="prettyprint lang-$1">');
data = data.replace(/{% endhighlight %}/g, '</pre>');
return data;
} | javascript | {
"resource": ""
} | |
q34875 | train | function (){
if (!instance._once) return;
//Uncache the files
["index.js", "command.js", "argp.js", "body.js", "error.js", "wrap.js"]
.forEach (function (filename){
delete require.cache[__dirname + path.sep + filename];
});
//The user may have a reference to the instance so it should be freed, eg.
//var p = argp.createParser (). If the user doesn't free the instance, eg.
//p = null, it will retain an empty object, {}
for (var p in instance){
delete instance[p];
}
instance.__proto__ = null;
delete instance.constructor;
} | javascript | {
"resource": ""
} | |
q34876 | WorkflowProcessBeginController | train | function WorkflowProcessBeginController($state, workorderService, wfmService, $stateParams) {
var self = this;
var workorderId = $stateParams.workorderId;
workorderService.read(workorderId).then(function(workorder) {
self.workorder = workorder;
self.workflow = workorder.workflow;
self.results = workorder.results;
self.started = !wfmService.isNew(self.workorder);
self.completed = wfmService.isCompleted(self.workorder);
});
self.getStepForResult = function(result) {
return wfmService.getStepForResult(result, self.workorder);
};
self.begin = function() {
wfmService.begin(self.workorder)
.then(function() {
$state.go('app.workflowProcess.steps', {
workorderId: workorderId
});
})
.catch(console.error.bind(console));
};
} | javascript | {
"resource": ""
} |
q34877 | train | function (token, value) {
var self = this;
var emitString = false;
function additionalEmit(additionalKey, additionalValue) {
var oldKey = self.internalParser.key;
self.internalParser.key = additionalKey;
self.internalParser.onValue(additionalValue);
self.internalParser.key = oldKey;
}
if (token === JsonParser.C.STRING ||
token === JsonParser.C.NUMBER ||
token === JsonParser.C.TRUE ||
token === JsonParser.C.FALSE ||
token === JsonParser.C.NULL) {
// Parser will emit value in these cases
if (typeof value === 'number' &&
this.internalParser.string.indexOf('.') != -1 &&
parseInt(this.internalParser.string) === value &&
this.internalParser.mode !== JsonParser.C.ARRAY) {
var typeKey = this.internalParser.key + '@odata.type';
if (this.internalParser.value) {
this.internalParser.value[typeKey] = 'Edm.Double';
}
additionalEmit(typeKey, 'Edm.Double');
// Determine whether return raw string to avoid losing precision
emitString = this.internalParser.string !== value.toString();
}
}
if (emitString) {
this.originalOnToken.call(this.internalParser, token, this.internalParser.string);
} else {
this.originalOnToken.call(this.internalParser, token, value);
}
} | javascript | {
"resource": ""
} | |
q34878 | JailedSite | train | function JailedSite(connection) {
this._interface = {}
this._remote = null
this._remoteUpdateHandler = function() {
}
this._getInterfaceHandler = function() {
}
this._interfaceSetAsRemoteHandler = function() {
}
this._disconnectHandler = function() {
}
this._store = new ReferenceStore
var _this = this
this._connection = connection
this._connection.onMessage(
function(data) {
_this._processMessage(data)
}
)
this._connection.onDisconnect(
function(m) {
_this._disconnectHandler(m)
}
)
} | javascript | {
"resource": ""
} |
q34879 | convertToAnyRoll | train | function convertToAnyRoll( object = {}) {
const { again, success, fail } = object || {};
if ( isAbsent( again ) && isAbsent( success ) && isAbsent( fail )) {
return convertToRoll( object );
} // else
return convertToWodRoll( object );
} | javascript | {
"resource": ""
} |
q34880 | imageFilter | train | function imageFilter (item /*{File|FileLikeObject}*/, options) {
var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
if ('|jpg|png|jpeg|bmp|gif|'.indexOf(type) === -1) {
var err = new Error('File extension not supported (' + type + ')');
vm.onUploadFinished(err);
throw err;
}
return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
} | javascript | {
"resource": ""
} |
q34881 | sizeFilter | train | function sizeFilter (item /*{File|FileLikeObject}*/, options) {
var size = item.size,
// Use passed size limit or default to 10MB
sizeLimit = vm.sizeLimit || 10 * 1000 * 1000;
if (size > sizeLimit) {
var err = new Error('File too big (' + size + ')');
vm.onUploadFinished(err);
throw err;
}
return size < sizeLimit;
} | javascript | {
"resource": ""
} |
q34882 | onLoad | train | function onLoad(event) {
var img = new Image();
img.onload = utils.getDimensions(canvas, vm.$storage);
img.src = event.target.result;
} | javascript | {
"resource": ""
} |
q34883 | train | function(file) {
var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|';
return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
} | javascript | {
"resource": ""
} | |
q34884 | train | function(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([ new Uint8Array(array) ], { type: mimeString });
} | javascript | {
"resource": ""
} | |
q34885 | observePromise | train | function observePromise(proxy, promise) {
promise.then(value => {
set(proxy, 'isFulfilled', true);
value._settingFromFirebase = true;
set(proxy, 'content', value);
value._settingFromFirebase = false;
}, reason => {
set(proxy, 'isRejected', true);
set(proxy, 'reason', reason);
// don't re-throw, as we are merely observing
});
} | javascript | {
"resource": ""
} |
q34886 | parse | train | async function parse(apkPath, target = `${os.tmpdir()}/apktoolDecodes`) {
const cmd = `java -jar ${apktoolPath} d ${apkPath} -f -o ${target}`
await shell(cmd)
const MainfestFilePath = `${target}/AndroidManifest.xml`
const doc = await parseManifest(MainfestFilePath)
return parseDoc(doc)
} | javascript | {
"resource": ""
} |
q34887 | uniquenessValidator | train | function uniquenessValidator(values) {
if (values.presentAuthors) {
values = values.presentAuthors;
}
values.sort();
for (var i = 0; i < values.length - 1; i++) {
if (values[i] === values[i+1]) {
// can throw error or return false
// error allows supplying more detail
throw new Error('Duplicate value [' + values[i] + '] found in Room.presentAuthors');
}
}
return true;
} | javascript | {
"resource": ""
} |
q34888 | loadConfig | train | function loadConfig() {
var root = process.cwd()
, config = readConfig(path.join(root, '_config.json'));
config.root = root;
return config;
} | javascript | {
"resource": ""
} |
q34889 | loadConfigAndGenerateSite | train | function loadConfigAndGenerateSite(useServer, port) {
var config = loadConfig();
if (port) config.port = port;
generateSite(config, useServer);
} | javascript | {
"resource": ""
} |
q34890 | generateSite | train | function generateSite(config, useServer) {
var fileMap = new FileMap(config)
, siteBuilder = new SiteBuilder(config)
, server = require(__dirname + '/server')(siteBuilder);
fileMap.walk();
fileMap.on('ready', function() {
siteBuilder.fileMap = fileMap;
siteBuilder.build();
});
siteBuilder.once('ready', function() {
if (useServer) {
server.run();
server.watch();
}
});
return siteBuilder;
} | javascript | {
"resource": ""
} |
q34891 | saveScreenshot | train | function saveScreenshot(driver, dir, testTitle) {
const data = driver.takeScreenshot()
const fileName = testTitle.replace(/[^a-zA-Z0-9]/g, '_')
.concat('_')
.concat(new Date().getTime())
.concat('.png')
const fullPath = path.resolve(dir, fileName)
fs.writeFileSync(fullPath, data, 'base64')
reportOutput({
type: 'image',
name: fileName,
file: fullPath
})
} | javascript | {
"resource": ""
} |
q34892 | train | function() {
var self = this;
self.jabber.on('data', function(buffer) {
console.log(' IN > ' + buffer.toString());
});
var origSend = this.jabber.send;
self.jabber.send = function(stanza) {
console.log(' OUT > ' + stanza);
return origSend.call(self.jabber, stanza);
};
} | javascript | {
"resource": ""
} | |
q34893 | train | function() {
var self = this;
this.setAvailability('chat');
this.keepalive = setInterval(function() {
self.jabber.send(new xmpp.Message({}));
self.emit('ping');
}, 30000);
// load our profile to get name
this.getProfile(function(err, data) {
if (err) {
// This isn't technically a stream error which is what the `error`
// event usually represents, but we want to treat a profile fetch
// error as a fatal error and disconnect the bot.
self.emit('error', null, 'Unable to get profile info: ' + err, null);
return;
}
// now that we have our name we can let rooms be joined
self.name = data.fn;
// this is the name used to @mention us
self.mention_name = data.nickname;
self.emit('connect');
});
} | javascript | {
"resource": ""
} | |
q34894 | train | function(stanza) {
this.emit('data', stanza);
if (stanza.is('message') && stanza.attrs.type === 'groupchat') {
var body = stanza.getChildText('body');
if (!body) return;
// Ignore chat history
if (stanza.getChild('delay')) return;
var fromJid = new xmpp.JID(stanza.attrs.from);
var fromChannel = fromJid.bare().toString();
var fromNick = fromJid.resource;
// Ignore our own messages
if (fromNick === this.name) return;
this.emit('message', fromChannel, fromNick, body);
} else if (stanza.is('message') && stanza.attrs.type === 'chat') {
// Message without body is probably a typing notification
var body = stanza.getChildText('body');
if (!body) return;
var fromJid = new xmpp.JID(stanza.attrs.from);
this.emit('privateMessage', fromJid.bare().toString(), body);
} else if (stanza.is('message') && !stanza.attrs.type) {
// TODO: It'd be great if we could have some sort of xpath-based listener
// so we could just watch for '/message/x/invite' stanzas instead of
// doing all this manual getChild nonsense.
var x = stanza.getChild('x', 'http://jabber.org/protocol/muc#user');
if (!x) return;
var invite = x.getChild('invite');
if (!invite) return;
var reason = invite.getChildText('reason');
var inviteRoom = new xmpp.JID(stanza.attrs.from);
var inviteSender = new xmpp.JID(invite.attrs.from);
this.emit('invite', inviteRoom.bare(), inviteSender.bare(), reason);
} else if (stanza.is('iq')) {
// Handle a response to an IQ request
var event_id = 'iq:' + stanza.attrs.id;
if (stanza.attrs.type === 'result') {
this.emit(event_id, null, stanza);
} else {
// IQ error response
// ex: http://xmpp.org/rfcs/rfc6121.html#roster-syntax-actions-result
var condition = 'unknown';
var error_elem = stanza.getChild('error');
if (error_elem) {
condition = error_elem.children[0].name;
}
this.emit(event_id, condition, stanza);
}
}
} | javascript | {
"resource": ""
} | |
q34895 | getCookieToken | train | function getCookieToken(res) {
var value = res.req.cookies[cookieName(res.req)];
if (!value)
return false;
var parts = value.split('|');
// If the existing cookie is invalid, reject it.
if (parts.length !== 3)
return false;
// If the user data doesn't match this request's user, reject the cookie
if (parts[1] !== getUserData(res.req))
return false;
var hasher = crypto.createHmac(options.algorithm, cookieKey);
hasher.update(parts[0]);
hasher.update("|"); // Don't confuse longer or shorter userDatas
hasher.update(parts[1]);
// If the hash doesn't match, reject the cookie
if (parts[2] !== hasher.digest('base64'))
return false;
return parts[0];
} | javascript | {
"resource": ""
} |
q34896 | getFormToken | train | function getFormToken() {
/*jshint validthis:true */
if (this._csrfFormToken)
return this._csrfFormToken;
checkSecure(this.req);
var cookieToken = getCookieToken(this) || createCookie(this);
var salt = base64Random(saltSize);
var hasher = crypto.createHmac(options.algorithm, formKey);
hasher.update(cookieToken);
hasher.update("|");
hasher.update(salt);
this._csrfFormToken = salt + "|" + hasher.digest('base64');
return this._csrfFormToken;
} | javascript | {
"resource": ""
} |
q34897 | verifyFormToken | train | function verifyFormToken(formToken) {
/*jshint validthis:true */
checkSecure(this);
// If we already cached this token, we know that it's valid.
// If we validate two different tokens for the same request,
// this won't incorrectly skip the second one.
if (this.res._csrfFormToken && this.res._csrfFormToken === formToken)
return true;
this._csrfChecked = true;
if (!formToken) return false;
var cookieToken = getCookieToken(this.res);
if (!cookieToken) return false;
var parts = formToken.split('|');
// If the token is invalid, reject it.
if (parts.length !== 2)
return false;
var hasher = crypto.createHmac(options.algorithm, formKey);
hasher.update(cookieToken);
hasher.update("|"); // Don't confuse longer or shorter tokens
hasher.update(parts[0]);
// If the hash doesn't match, reject the token
if (parts[1] !== hasher.digest('base64'))
return false;
// If we have a valid token, reuse it for this request
// instead of generating a new one. (saves crypto ops)
if (!this.res._csrfFormToken)
this.res._csrfFormToken = formToken;
return true;
} | javascript | {
"resource": ""
} |
q34898 | getTemplateFile | train | async function getTemplateFile(templateDir, stackName) {
const f = await Promise.any(
_.map(['.yml', '.yaml', '.json', ''], async(ext) =>
await utils.fileExists(`${path.join(templateDir, stackName)}${ext}`)));
if (f) {
return f;
}
throw new Error(`Stack template "${stackName}" not found!`);
} | javascript | {
"resource": ""
} |
q34899 | Skytap | train | function Skytap () {
this.audit = new Audit(this);
this.environments = new Environments(this);
this.ips = new Ips(this);
this.networks = new Networks(this);
this.projects = new Projects(this);
this.templates = new Templates(this);
this.usage = new Usage(this);
this.users = new Users(this);
this.vms = new Vms(this);
this.vpns = new Vpns(this);
this.getArgs = function getArgs() {
return _.clone(this._config);
};
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.