_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: de... | 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);
... | 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 ||... | 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"]) {
... | 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.... | 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'... | 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... | 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 |... | 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 transit... | 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 t... | 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.ty... | 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.depend... | 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)... | 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++) {
... | 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... | 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) {
... | 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(/\... | 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... | 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())) {
... | 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]);
... | 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) {
... | 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') {
... | 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.
... | 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) {
at... | 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',... | 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'... | 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'),... | 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.... | 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 fo... | 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 ex... | 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.printInternal... | 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.... | 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) {
... | 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 re... | 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;
... | 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].snip... | 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
... | 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 Prom... | 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 a... | 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)... | 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].co... | 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(workor... | 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... | 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);
... | 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... | 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 sh... | 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 = worko... | 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 (tok... | 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... | 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);
... | 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(... | 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(arra... | 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... | 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(... | 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.on... | 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')
report... | 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 t... | 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);
... | 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
... | 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(c... | 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... | 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.... | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.