_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q36200 | trimLeading | train | function trimLeading(text, prefix) {
if (text && prefix) {
if (_.startsWith(text, prefix) || text.indexOf(prefix) === 0) {
return text.substring(prefix.length);
}
}
return text;
} | javascript | {
"resource": ""
} |
q36201 | trimTrailing | train | function trimTrailing(text, postfix) {
if (text && postfix) {
if (_.endsWith(text, postfix)) {
return text.substring(0, text.length - postfix.length);
}
}
return text;
} | javascript | {
"resource": ""
} |
q36202 | adjustHeight | train | function adjustHeight() {
var windowHeight = $(window).height();
var headerHeight = $("#main-nav").height();
var containerHeight = windowHeight - headerHeight;
$("#main").css("min-height", "" + containerHeight + "px");
} | javascript | {
"resource": ""
} |
q36203 | addCSS | train | function addCSS(path) {
if ('createStyleSheet' in document) {
// IE9
document.createStyleSheet(path);
}
else {
// Everyone else
var link = $("<link>");
$("head").append(link);
link.attr({
rel: 'stylesheet',
type: 'text/css',
href: path
});
}
} | javascript | {
"resource": ""
} |
q36204 | parseBooleanValue | train | function parseBooleanValue(value, defaultValue) {
if (defaultValue === void 0) { defaultValue = false; }
if (!angular.isDefined(value) || !value) {
return defaultValue;
}
if (value.constructor === Boolean) {
return value;
}
if (angular.isString(value)) {
switch (value.toLowerCase()) {
case "true":
case "1":
case "yes":
return true;
default:
return false;
}
}
if (angular.isNumber(value)) {
return value !== 0;
}
throw new Error("Can't convert value " + value + " to boolean");
} | javascript | {
"resource": ""
} |
q36205 | pathGet | train | function pathGet(object, paths) {
var pathArray = (angular.isArray(paths)) ? paths : (paths || "").split(".");
var value = object;
angular.forEach(pathArray, function (name) {
if (value) {
try {
value = value[name];
}
catch (e) {
// ignore errors
return null;
}
}
else {
return null;
}
});
return value;
} | javascript | {
"resource": ""
} |
q36206 | pathSet | train | function pathSet(object, paths, newValue) {
var pathArray = (angular.isArray(paths)) ? paths : (paths || "").split(".");
var value = object;
var lastIndex = pathArray.length - 1;
angular.forEach(pathArray, function (name, idx) {
var next = value[name];
if (idx >= lastIndex || !angular.isObject(next)) {
next = (idx < lastIndex) ? {} : newValue;
value[name] = next;
}
value = next;
});
return value;
} | javascript | {
"resource": ""
} |
q36207 | getOrCreateElements | train | function getOrCreateElements(domElement, arrayOfElementNames) {
var element = domElement;
angular.forEach(arrayOfElementNames, function (name) {
if (element) {
var children = $(element).children(name);
if (!children || !children.length) {
$("<" + name + "></" + name + ">").appendTo(element);
children = $(element).children(name);
}
element = children;
}
});
return element;
} | javascript | {
"resource": ""
} |
q36208 | escapeHtml | train | function escapeHtml(str) {
if (angular.isString(str)) {
var newStr = "";
for (var i = 0; i < str.length; i++) {
var ch = str.charAt(i);
ch = _escapeHtmlChars[ch] || ch;
newStr += ch;
}
return newStr;
}
else {
return str;
}
} | javascript | {
"resource": ""
} |
q36209 | isBlank | train | function isBlank(str) {
if (str === undefined || str === null) {
return true;
}
if (angular.isString(str)) {
return str.trim().length === 0;
}
else {
// TODO - not undefined but also not a string...
return false;
}
} | javascript | {
"resource": ""
} |
q36210 | humanizeValue | train | function humanizeValue(value) {
if (value) {
var text = value + '';
if (Core.isBlank(text)) {
return text;
}
try {
text = _.snakeCase(text);
text = _.capitalize(text.split('_').join(' '));
}
catch (e) {
// ignore
}
return trimQuotes(text);
}
return value;
} | javascript | {
"resource": ""
} |
q36211 | lineCount | train | function lineCount(value) {
var rows = 0;
if (value) {
rows = 1;
value.toString().each(/\n/, function () { return rows++; });
}
return rows;
} | javascript | {
"resource": ""
} |
q36212 | toSearchArgumentArray | train | function toSearchArgumentArray(value) {
if (value) {
if (angular.isArray(value))
return value;
if (angular.isString(value))
return value.split(',');
}
return [];
} | javascript | {
"resource": ""
} |
q36213 | onSuccess | train | function onSuccess(fn, options) {
if (options === void 0) { options = {}; }
options['mimeType'] = 'application/json';
if (!_.isUndefined(fn)) {
options['success'] = fn;
}
if (!options['method']) {
options['method'] = "POST";
}
// the default (unsorted) order is important for Karaf runtime
options['canonicalNaming'] = false;
options['canonicalProperties'] = false;
if (!options['error']) {
options['error'] = function (response) { return defaultJolokiaErrorHandler(response, options); };
}
return options;
} | javascript | {
"resource": ""
} |
q36214 | defaultJolokiaErrorHandler | train | function defaultJolokiaErrorHandler(response, options) {
if (options === void 0) { options = {}; }
var operation = Core.pathGet(response, ['request', 'operation']) || "unknown";
var silent = options['silent'];
var stacktrace = response.stacktrace;
if (silent || isIgnorableException(response)) {
log.debug("Operation", operation, "failed due to:", response['error']);
}
else {
log.warn("Operation", operation, "failed due to:", response['error']);
}
} | javascript | {
"resource": ""
} |
q36215 | isIgnorableException | train | function isIgnorableException(response) {
var isNotFound = function (target) {
return target.indexOf("InstanceNotFoundException") >= 0
|| target.indexOf("AttributeNotFoundException") >= 0
|| target.indexOf("IllegalArgumentException: No operation") >= 0;
};
return (response.stacktrace && isNotFound(response.stacktrace)) || (response.error && isNotFound(response.error));
} | javascript | {
"resource": ""
} |
q36216 | logJolokiaStackTrace | train | function logJolokiaStackTrace(response) {
var stacktrace = response.stacktrace;
if (stacktrace) {
var operation = Core.pathGet(response, ['request', 'operation']) || "unknown";
log.info("Operation", operation, "failed due to:", response['error']);
}
} | javascript | {
"resource": ""
} |
q36217 | logLevelClass | train | function logLevelClass(level) {
if (level) {
var first = level[0];
if (first === 'w' || first === "W") {
return "warning";
}
else if (first === 'e' || first === "E") {
return "error";
}
else if (first === 'i' || first === "I") {
return "info";
}
else if (first === 'd' || first === "D") {
// we have no debug css style
return "";
}
}
return "";
} | javascript | {
"resource": ""
} |
q36218 | hashToString | train | function hashToString(hash) {
var keyValuePairs = [];
angular.forEach(hash, function (value, key) {
keyValuePairs.push(key + "=" + value);
});
var params = keyValuePairs.join("&");
return encodeURI(params);
} | javascript | {
"resource": ""
} |
q36219 | stringToHash | train | function stringToHash(hashAsString) {
var entries = {};
if (hashAsString) {
var text = decodeURI(hashAsString);
var items = text.split('&');
angular.forEach(items, function (item) {
var kv = item.split('=');
var key = kv[0];
var value = kv[1] || key;
entries[key] = value;
});
}
return entries;
} | javascript | {
"resource": ""
} |
q36220 | registerForChanges | train | function registerForChanges(jolokia, $scope, arguments, callback, options) {
var decorated = {
responseJson: '',
success: function (response) {
var json = angular.toJson(response.value);
if (decorated.responseJson !== json) {
decorated.responseJson = json;
callback(response);
}
}
};
angular.extend(decorated, options);
return Core.register(jolokia, $scope, arguments, onSuccess(undefined, decorated));
} | javascript | {
"resource": ""
} |
q36221 | register | train | function register(jolokia, scope, arguments, callback) {
if (scope.$$destroyed) {
// fail fast to prevent registration leaks
return;
}
/*
if (scope && !Core.isBlank(scope.name)) {
Core.log.debug("Calling register from scope: ", scope.name);
} else {
Core.log.debug("Calling register from anonymous scope");
}
*/
if (!angular.isDefined(scope.$jhandle) || !angular.isArray(scope.$jhandle)) {
//log.debug("No existing handle set, creating one");
scope.$jhandle = [];
}
else {
//log.debug("Using existing handle set");
}
if (angular.isDefined(scope.$on)) {
scope.$on('$destroy', function (event) {
unregister(jolokia, scope);
});
}
var handle = null;
if ('success' in callback) {
var cb_1 = callback.success;
var args_1 = arguments;
callback.success = function (response) {
addResponse(args_1, response);
cb_1(response);
};
}
if (angular.isArray(arguments)) {
if (arguments.length >= 1) {
// TODO can't get this to compile in typescript :)
//let args = [callback].concat(arguments);
var args_2 = [callback];
angular.forEach(arguments, function (value) { return args_2.push(value); });
//let args = [callback];
//args.push(arguments);
var registerFn = jolokia.register;
handle = registerFn.apply(jolokia, args_2);
scope.$jhandle.push(handle);
getResponse(jolokia, arguments, callback);
}
}
else {
handle = jolokia.register(callback, arguments);
scope.$jhandle.push(handle);
getResponse(jolokia, arguments, callback);
}
return function () {
if (handle !== null) {
scope.$jhandle.remove(handle);
jolokia.unregister(handle);
}
};
} | javascript | {
"resource": ""
} |
q36222 | unregister | train | function unregister(jolokia, scope) {
if (angular.isDefined(scope.$jhandle)) {
scope.$jhandle.forEach(function (handle) {
jolokia.unregister(handle);
});
delete scope.$jhandle;
}
} | javascript | {
"resource": ""
} |
q36223 | xmlNodeToString | train | function xmlNodeToString(xmlNode) {
try {
// Gecko- and Webkit-based browsers (Firefox, Chrome), Opera.
return (new XMLSerializer()).serializeToString(xmlNode);
}
catch (e) {
try {
// Internet Explorer.
return xmlNode.xml;
}
catch (e) {
//Other browsers without XML Serializer
console.log('WARNING: XMLSerializer not supported');
}
}
return false;
} | javascript | {
"resource": ""
} |
q36224 | fileExtension | train | function fileExtension(name, defaultValue) {
if (defaultValue === void 0) { defaultValue = ""; }
var extension = defaultValue;
if (name) {
var idx = name.lastIndexOf(".");
if (idx > 0) {
extension = name.substring(idx + 1, name.length).toLowerCase();
}
}
return extension;
} | javascript | {
"resource": ""
} |
q36225 | parseVersionNumbers | train | function parseVersionNumbers(text) {
if (text) {
var m = text.match(_versionRegex);
if (m && m.length > 4) {
var m1 = m[1];
var m2 = m[2];
var m4 = m[4];
if (angular.isDefined(m4)) {
return [parseInt(m1), parseInt(m2), parseInt(m4)];
}
else if (angular.isDefined(m2)) {
return [parseInt(m1), parseInt(m2)];
}
else if (angular.isDefined(m1)) {
return [parseInt(m1)];
}
}
}
return null;
} | javascript | {
"resource": ""
} |
q36226 | versionToSortableString | train | function versionToSortableString(version, maxDigitsBetweenDots) {
if (maxDigitsBetweenDots === void 0) { maxDigitsBetweenDots = 4; }
return (version || "").split(".").map(function (x) {
var length = x.length;
return (length >= maxDigitsBetweenDots)
? x : _.padStart(x, maxDigitsBetweenDots - length, ' ');
}).join(".");
} | javascript | {
"resource": ""
} |
q36227 | compareVersionNumberArrays | train | function compareVersionNumberArrays(v1, v2) {
if (v1 && !v2) {
return 1;
}
if (!v1 && v2) {
return -1;
}
if (v1 === v2) {
return 0;
}
for (var i = 0; i < v1.length; i++) {
var n1 = v1[i];
if (i >= v2.length) {
return 1;
}
var n2 = v2[i];
if (!angular.isDefined(n1)) {
return -1;
}
if (!angular.isDefined(n2)) {
return 1;
}
if (n1 > n2) {
return 1;
}
else if (n1 < n2) {
return -1;
}
}
return 0;
} | javascript | {
"resource": ""
} |
q36228 | forEachLeafFolder | train | function forEachLeafFolder(folders, fn) {
angular.forEach(folders, function (folder) {
var children = folder["children"];
if (angular.isArray(children) && children.length > 0) {
forEachLeafFolder(children, fn);
}
else {
fn(folder);
}
});
} | javascript | {
"resource": ""
} |
q36229 | parseUrl | train | function parseUrl(url) {
if (Core.isBlank(url)) {
return null;
}
var matches = url.match(httpRegex);
if (matches === null) {
return null;
}
//log.debug("matches: ", matches);
var scheme = matches[1];
var host = matches[3];
var port = matches[4];
var parts = null;
if (!Core.isBlank(port)) {
parts = url.split(port);
}
else {
parts = url.split(host);
}
// make sure we use port as a number
var portNum = Core.parseIntValue(port);
var path = parts[1];
if (path && _.startsWith(path, '/')) {
path = path.slice(1, path.length);
}
//log.debug("parts: ", parts);
return {
scheme: scheme,
host: host,
port: portNum,
path: path
};
} | javascript | {
"resource": ""
} |
q36230 | useProxyIfExternal | train | function useProxyIfExternal(connectUrl) {
if (Core.isChromeApp()) {
return connectUrl;
}
var host = window.location.host;
if (!_.startsWith(connectUrl, "http://" + host + "/") && !_.startsWith(connectUrl, "https://" + host + "/")) {
// lets remove the http stuff
var idx = connectUrl.indexOf("://");
if (idx > 0) {
connectUrl = connectUrl.substring(idx + 3);
}
// lets replace the : with a /
connectUrl = connectUrl.replace(":", "/");
connectUrl = Core.trimLeading(connectUrl, "/");
connectUrl = Core.trimTrailing(connectUrl, "/");
connectUrl = Core.url("/proxy/" + connectUrl);
}
return connectUrl;
} | javascript | {
"resource": ""
} |
q36231 | throttled | train | function throttled(fn, millis) {
var nextInvokeTime = 0;
var lastAnswer = null;
return function () {
var now = Date.now();
if (nextInvokeTime < now) {
nextInvokeTime = now + millis;
lastAnswer = fn();
}
else {
//log.debug("Not invoking function as we did call " + (now - (nextInvokeTime - millis)) + " ms ago");
}
return lastAnswer;
};
} | javascript | {
"resource": ""
} |
q36232 | parseJsonText | train | function parseJsonText(text, message) {
if (message === void 0) { message = "JSON"; }
var answer = null;
try {
answer = angular.fromJson(text);
}
catch (e) {
log.info("Failed to parse " + message + " from: " + text + ". " + e);
}
return answer;
} | javascript | {
"resource": ""
} |
q36233 | humanizeValueHtml | train | function humanizeValueHtml(value) {
var formattedValue = "";
if (value === true) {
formattedValue = '<i class="icon-check"></i>';
}
else if (value === false) {
formattedValue = '<i class="icon-check-empty"></i>';
}
else {
formattedValue = Core.humanizeValue(value);
}
return formattedValue;
} | javascript | {
"resource": ""
} |
q36234 | getQueryParameterValue | train | function getQueryParameterValue(url, parameterName) {
var parts;
var query = (url || '').split('?');
if (query && query.length > 0) {
parts = query[1];
}
else {
parts = '';
}
var vars = parts.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == parameterName) {
return decodeURIComponent(pair[1]);
}
}
// not found
return null;
} | javascript | {
"resource": ""
} |
q36235 | humanizeMilliseconds | train | function humanizeMilliseconds(value) {
if (!angular.isNumber(value)) {
return "XXX";
}
var seconds = value / 1000;
var years = Math.floor(seconds / 31536000);
if (years) {
return maybePlural(years, "year");
}
var days = Math.floor((seconds %= 31536000) / 86400);
if (days) {
return maybePlural(days, "day");
}
var hours = Math.floor((seconds %= 86400) / 3600);
if (hours) {
return maybePlural(hours, 'hour');
}
var minutes = Math.floor((seconds %= 3600) / 60);
if (minutes) {
return maybePlural(minutes, 'minute');
}
seconds = Math.floor(seconds % 60);
if (seconds) {
return maybePlural(seconds, 'second');
}
return value + " ms";
} | javascript | {
"resource": ""
} |
q36236 | createControllerFunction | train | function createControllerFunction(_module, pluginName) {
return function (name, inlineAnnotatedConstructor) {
return _module.controller(pluginName + '.' + name, inlineAnnotatedConstructor);
};
} | javascript | {
"resource": ""
} |
q36237 | parsePreferencesJson | train | function parsePreferencesJson(value, key) {
var answer = null;
if (angular.isDefined(value)) {
answer = Core.parseJsonText(value, "localStorage for " + key);
}
return answer;
} | javascript | {
"resource": ""
} |
q36238 | train | function () {
// looking for keys passed as cli arguments with urls and download-dirs
const urlsKey = "urls";
const downloadDirsKey = "download-dirs";
const destinationDir = "destination-dirs";
// keys used in the array (same as in configuration via package.json) for each item (so urls => url)
const confUrlsKey = "url";
const confDownloadDirsKey = "directory";
const confDestinationDir = "nodeModulesDir";
// getting cli arguments
var argv = require('minimist')(process.argv.slice(2));
var unjarConfigFromArguments = [];
if (argv[urlsKey] != null) {
// only 1 object passed
if (typeof argv[urlsKey] === 'string') {
// put into an array, so as it can be used the same way as multiple args
argv[urlsKey] = [argv[urlsKey]];
argv[downloadDirsKey] = [argv[downloadDirsKey]];
argv[destinationDir] = [argv[destinationDir]];
}
// put them together so that the array has a object with the attributes: nodeModulesDir, directory, url
for (var i = 0; i < argv[urlsKey].length; i++) {
var configItem = {};
configItem[confUrlsKey] = argv[urlsKey][i];
configItem[confDownloadDirsKey] = argv[downloadDirsKey][i];
configItem[confDestinationDir] = argv[destinationDir][i];
unjarConfigFromArguments.push(configItem);
}
}
return unjarConfigFromArguments;
} | javascript | {
"resource": ""
} | |
q36239 | train | function (module) {
const configKey = 'unjar-from-url-config';
if (module == null) {
return [];
}
var highestParent;
if (module.parent != null) {
highestParent = module.parent;
} else {
highestParent = module;
}
var parentFound = false;
// iterate up to all parents, until parent is undefined => root of all
while (!parentFound) {
parentFound = highestParent.parent == undefined || highestParent.parent == null;
// go to upper parent
if (!parentFound) {
highestParent = highestParent.parent;
}
}
// get the path to project itself (where the package.json is)
var pathToNodeModules = highestParent.paths[0].split("node_modules")[0];
// read the package json
var packageJson = require(pathToNodeModules + "package.json");
var unjarFromUrlConfig;
if (packageJson != null && packageJson[configKey] != null) {
unjarFromUrlConfig = packageJson[configKey];
}
if (unjarFromUrlConfig != null) {
// add the highest parent path (used as nodeModulesDir later) to each item
var nodeModulesDir = highestParent.paths != null ? highestParent.paths[0] : '';
unjarFromUrlConfig.forEach(function (item) {
item.nodeModulesDir = nodeModulesDir
});
} else {
console.warn("No config found in package.json: ", pathToNodeModules + "package.json");
unjarFromUrlConfig = [];
}
return unjarFromUrlConfig;
} | javascript | {
"resource": ""
} | |
q36240 | train | function (nodeModulesDir, unzipDirectory, url) {
const download = require('download');
const fs = require('fs');
const zlib = require('zlib');
var exec = require('child_process').exec,
child;
var path = require("path");
// extracting filename from url
var filename = path.basename(url);
var fileDirectory = nodeModulesDir + "/" + unzipDirectory;
console.log("nodeModules directory = ", nodeModulesDir);
console.log("downloading file from url=", url);
console.log("unzipping to directory=", unzipDirectory);
console.log("fileDriectory=", fileDirectory);
console.log("filename = ", filename);
// makes programming easier (create the directory anyway)
if (!fs.existsSync(fileDirectory)) {
// mkdir -p fileDirectory
fileDirectory.split('/').forEach((dir, index, splits) => {
const parent = splits.slice(0, index).join('/');
const dirPath = path.resolve(parent, dir);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath);
}
});
}
// delete directory with file in it, and after that download the file into newly created folder
exec('rm -r ' + fileDirectory, function (err, stdout, stderr) {
fs.mkdirSync(fileDirectory);
// fs.writeFileSync(fileDirectory + "/download.jar", content);
// download process
download(url, fileDirectory).then(() => {
console.log("downloaded file successful. unzipping...");
var DecompressZip = require('decompress-zip');
console.log("file to decompress: " + fileDirectory + "/" + filename);
var unzipper = new DecompressZip(fileDirectory + "/" + filename);
unzipper.on('error', function (err) {
console.log('Caught an error', err);
});
unzipper.on('extract', function (log) {
console.log('Finished extracting');
});
unzipper.on('progress', function (fileIndex, fileCount) {
console.log('Extracted file ' + (fileIndex + 1) + ' of ' + fileCount);
});
unzipper.extract({
path: fileDirectory,
filter: function (file) {
return file.type !== "SymbolicLink";
}
});
});
});
} | javascript | {
"resource": ""
} | |
q36241 | Builder | train | function Builder(tmpl, data) {
// Generate a this context for data
var that = {'tmpl': tmpl, 'data': data};
// Run the beforeFns on tmpl
tmpl = pre.call(that, tmpl);
// Convert the template into content
var content = template.call(that, tmpl, data);
// Pass the template through the dom engine
var $content = domify.call(that, content);
// Run the afterFns on $content
$content = post.call(that, $content);
// Return the $content
return $content;
} | javascript | {
"resource": ""
} |
q36242 | pre | train | function pre(tmpl) {
// Iterate over the beforeFns
var i = 0,
len = beforeFns.length;
for (; i < len; i++) {
tmpl = beforeFns[i].call(this, tmpl) || tmpl;
}
// Return tmpl
return tmpl;
} | javascript | {
"resource": ""
} |
q36243 | template | train | function template(tmpl, data) {
// Grab the template engine
var engine = settings['template engine'];
// Process the template through the template engine
var content = engine.call(this, tmpl, data);
// Return the content
return content;
} | javascript | {
"resource": ""
} |
q36244 | set | train | function set(name, val) {
// If the name is an object
var key;
if (typeof name === 'object') {
// Iterate over its properties
for (key in name) {
if (name.hasOwnProperty(key)) {
// Set each one
set(key, name[key]);
}
}
} else {
// Otherwise, save to settings
settings[name] = val;
}
} | javascript | {
"resource": ""
} |
q36245 | addPlugin | train | function addPlugin(params) {
// If the params are a string, upcast it to an object
if (typeof params === 'string') {
params = {
'plugin': params
};
}
// Grab and fallback plugin and selector
var plugin = params.plugin,
selector = params.selector || '.' + plugin;
// Generate an after function for binding
var afterFn = function pluginAfterFn($content) {
// Filter and find any jQuery module that has the corresponding class
var $items = $().add($content.filter(selector)).add($content.find(selector));
// Iterate over the items and initialize the plugin
$items.each(function () {
$(this)[plugin]();
});
};
// Bind the after function
after(afterFn);
} | javascript | {
"resource": ""
} |
q36246 | handle | train | function handle(js,line){
// handle message from board.
//stream.log("handle",stream.token,line);
var hasToken = stream.token;
if(js.type == "token") {
// send in event stream.
stream.queue(js);
stream.token = js.token;
if(!hasToken) {
readycb(false,stream);
clearTimeout(readyTimeout);
}
return;
}
if(!stream.token) return stream.log('data from socket before auth/id token.',js);
if(js.type == 'reply'){
o = stream.callbacks[js.id]||{};
if(o.id === undefined) return stream.log('got reply with no id mapping! ',js);
var output = js.output||js.reply||"";
var ret = js.return;// not set yet.
if(!o.output) o.output = "";
// handle chunked responses. they come in order.
o.output += output;
// soon the firmware will support returning the return int value of the scout script function/expression. it willbe the property return.
if(ret) {
o.return = ret;
}
js._cid = js.id;
js.id = o.id;
if(js.err || js.end) {
delete stream.callbacks[js._cid];
js.reply = js.output = o.output;
js.return = o.return;
o.cb(js.err,js)
}
} else if(js.type == "report" && line == stream._lastreport){
// duplicate reports are not really useful to propagate as events because nothing changed.
return;// stream.log('duplicate report ',line);
} else if (js.type == "report") {
stream._lastreport = line;
stream.queue(js);// send report in stream.
} else {
stream.log('unknown message type',js);
}
} | javascript | {
"resource": ""
} |
q36247 | getElement | train | function getElement () {
if (element === null) {
element = document.createElement('a');
element.innerText = 'Download';
element.style.position = 'absolute';
element.style.top = '-100px';
element.style.left = '0px';
}
return element;
} | javascript | {
"resource": ""
} |
q36248 | getObjectUrl | train | function getObjectUrl (data) {
let blob;
if (typeof data === 'object' && data.constructor.name === 'Blob') {
blob = data;
} else if (typeof data === 'string') {
blob = new Blob([getTextEncoder().encode(data).buffer], {
type: 'application/octet-stream'
});
} else if (typeof data === 'object' && data.constructor && data.constructor.name === 'ArrayBuffer') {
blob = new Blob([data], {
type: 'application/octet-stream'
});
} else {
throw new Error('in-browser-download: Data must either be a Blob, a string or an ArrayBuffer');
}
return URL.createObjectURL(blob);
} | javascript | {
"resource": ""
} |
q36249 | download | train | function download (data, filename) {
const element = getElement();
const url = getObjectUrl(data);
element.setAttribute('href', url);
element.setAttribute('download', filename);
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
setTimeout(function () {
URL.revokeObjectURL(url);
}, 100);
} | javascript | {
"resource": ""
} |
q36250 | makeObjectKeysLC | train | function makeObjectKeysLC (o){
var keys = Object.keys(o);
var lcObject = {};
keys.forEach(function(k){
lcObject[k.toLowerCase()] = o[k];
});
return lcObject;
} | javascript | {
"resource": ""
} |
q36251 | LacesObject | train | function LacesObject(options) {
Object.defineProperty(this, "_bindings", { "value": [], "writable": true });
Object.defineProperty(this, "_eventListeners", { "value": {}, "writable": true });
Object.defineProperty(this, "_heldEvents", { "value": null, "writable": true });
Object.defineProperty(this, "_gotLaces", { "value": true });
Object.defineProperty(this, "_options", { "value": options || {} });
} | javascript | {
"resource": ""
} |
q36252 | load | train | function load(file, options) {
if (options.cache && rr.cache['tpl!' + file]) {
return Promise.resolve(rr.cache['tpl!' + file]);
}
return fs.readFileAsync(file, 'utf8').then(function (template) {
return utils.wrap(Ractive.parse(template, options), options);
}).then(function (template) {
var basePath = path.relative(options.settings.views, path.dirname(file));
var cOptions = utils.buildOptions(options, null, true);
cOptions.template = template;
return Promise.join(utils.buildComponentsRegistry(cOptions), utils.buildPartialsRegistry(basePath, cOptions), function (components, partials) {
cOptions.components = components;
cOptions.partials = partials;
options.components = {};
options.partials = {};
var Component = Ractive.extend(cOptions);
if (options.cache) {
rr.cache['tpl!' + file] = Component;
}
return Component;
});
});
} | javascript | {
"resource": ""
} |
q36253 | generateTableTree | train | function generateTableTree(head, separator) {
return {
type: 'Table',
children: [{
type: 'TableHead',
children: [{
type: 'TableRow',
children: head.map((rawValue, index) => ({
type: 'TableHeadCell',
align: separator[index],
rawValue
}))
}]
}]
};
} | javascript | {
"resource": ""
} |
q36254 | generateTableRowNode | train | function generateTableRowNode(line, separator) {
const tableRow = {
type: 'TableRow',
children: separator.map(align => ({
type: 'TableDataCell',
align
}))
};
for (let i = 0, data = calRow(line), len = data.length; i < len; i++) {
tableRow.children[i].rawValue = data[i];
}
return tableRow;
} | javascript | {
"resource": ""
} |
q36255 | calSeparator | train | function calSeparator(str) {
return calRow(str).map(item => {
if (item.startsWith(':') && item.endsWith(':')) {
return 'center';
} else if (item.startsWith(':')) {
return 'left';
} else if (item.endsWith(':')) {
return 'right';
} else if (item.endsWith(':')) {
return '';
}
});
} | javascript | {
"resource": ""
} |
q36256 | createOauthClient | train | function createOauthClient(storagePath, clientSecrets) {
var secrets = fs.readFileSync(path.join(storagePath, clientSecrets + '.json'));
if (secrets === undefined) {
throw new Error('failed to read secrets file');
}
secrets = JSON.parse(secrets);
var gAuth = new googleAuth();
var oauthClient = new gAuth.OAuth2(secrets.installed.client_id,
secrets.installed.client_secret,
secrets.installed.redirect_uris[0]);
return oauthClient;
} | javascript | {
"resource": ""
} |
q36257 | Retry | train | function Retry(conf) {
component.Component.call(this, 'controller', conf);
this.registerGearman(conf.servers, {
client: true,
worker: {
func_name: 'retryController',
func: _.bind( function(json_string, worker) {
try {
// TODO: this parsing and meta parameter storing should be encapsulated into a Task class
var task = JSON.parse( json_string.toString() );
task._task_json_string = json_string;
task._task_worker = worker;
this.execute_task( task );
}
catch ( e ) {
_err( 'Error executing retryController with following payload:', json_string );
}
}, this )
}
});
} | javascript | {
"resource": ""
} |
q36258 | split | train | function split (splitBy, string) {
return (typeof splitBy === 'function')
? predicate(splitBy, string)
: string.split(splitBy)
} | javascript | {
"resource": ""
} |
q36259 | predicate | train | function predicate (fn, string) {
var idx = -1
var end = string.length
var out = []
var buf = ''
while (++idx < end) {
if (fn(string[idx], idx) === true) {
if (buf) out.push(buf)
buf = ''
} else {
buf += string[idx]
}
}
if (buf) out.push(buf)
return out
} | javascript | {
"resource": ""
} |
q36260 | NedbStore | train | function NedbStore(datastore, documentsName) {
if(arguments.length === 0 || typeof datastore !== 'object') {
throw new Error('Valid datastore parameter have to be provided')
}
if (arguments[1]) {
if (typeof arguments[1] !== 'string') {
throw new Error('documentsName must be a valid string')
}
}
TokenStore.call(this)
this._documentsName = documentsName || 'passwordless-token'
this._db = datastore
} | javascript | {
"resource": ""
} |
q36261 | compatible | train | function compatible(value, descriptor) {
if (!value) {
// If we're a null, then we can't validate.
return false;
} else if (!descriptor) {
return true;
}
const descriptorType = typeof descriptor;
if (descriptorType === 'string') {
return typeof value === descriptor;
} else if (descriptorType === 'function') {
return descriptor(value);
} else if (descriptorType === 'object') {
let matched = true;
Object.keys(descriptor).forEach((key) => {
const fromValue = value[key];
const fromDescriptor = descriptor[key];
if (!compatible(fromValue, fromDescriptor)) {
matched = false;
}
});
return matched;
}
throw new Error('Unknown descriptor type: ' + descriptorType);
} | javascript | {
"resource": ""
} |
q36262 | match | train | function match(args, typeMap) {
// No arguments, no win.
if (!args || !args.length) {
throw new Error('Cannot perform overload.match: args must be non-null array');
} else if (!typeMap || !typeMap.length) {
// We always satisfy a null or empty typeMap
return true;
}
// Validate the arguments one by one
for (let index = 0; index < args.length; index++) {
if (!compatible(args[index], typeMap[index])) {
return false;
}
}
// If not incompatible, sucess
return true;
} | javascript | {
"resource": ""
} |
q36263 | Runner | train | function Runner(conf) {
component.Component.call(this, 'runner', conf);
var that = this;
this._default_controller = defaults.controllerfuncname(conf);
this._dbconn = conf.dbconn;
this.registerGearman(conf.servers, { client: true });
this.on('connect', function() {
that.startPolling();
});
this.on('disconnect', function() {
if (that.db_poll_stop)
that.db_poll_stop();
});
} | javascript | {
"resource": ""
} |
q36264 | promiseCommand | train | function promiseCommand(command) {
const opts = {
env: process.env
};
console.log('>>>>', command)
return spawnShell(command, opts).exitPromise
.then((exitCode) => {
if (exitCode === 0) {
return;
} else {
throw Error("Exit " + exitCode)
}
})
} | javascript | {
"resource": ""
} |
q36265 | JITResolver | train | function JITResolver(map) {
if (!(this instanceof JITResolver)) return new JITResolver(map);
var lines = Array.isArray(map) ? map : map.split('\n')
this._addresses = lines
.reduce(processLine, [])
.sort(byDecimalAddress)
this._len = this._addresses.length;
} | javascript | {
"resource": ""
} |
q36266 | train | function($str)
{
if (!this.hasFormatOptions)
{
this.addToLog($str);
return false;
}
// strip colors from the string. this is ok with multilines
if (this.options.stripColor)
{
$str = Utils.stripColor($str);
}
var $result = [];
if (this.options.splitOnLinebreak)
{
var $split = Utils.splitOnLinebreak($str,
this.options.trimLinebreak);
for (var $i = 0, $iL = $split.length; $i < $iL; $i++)
{
$str = $split[$i];
if (this.options.trimTimestamp)
{
$str = Utils.trimTimestamp($str, !this.options.stripColor);
}
this.addToLog($str);
$result.push($str);
}
}
else
{
if (this.options.trimTimestamp)
{
$str = Utils.trimTimestamp($str, !this.options.stripColor);
}
if (this.options.trimLinebreak)
{
$str = Utils.trimLinebreak($str);
}
this.addToLog($str);
$result.push($str);
}
return $result;
} | javascript | {
"resource": ""
} | |
q36267 | train | function (fn, module, data, verbose) {
let complete = module.toUpperCase() + " > ";
// Only provide verbose log if logLevel > 5
verbose = config.logLevel >= 5 ? (verbose || undefined) : undefined;
// When writing to console
if ( config.destination === console) {
// Compose message
complete = " [ " + new Date().toLocaleString() + " ] " + complete + data;
if ( fn == "error" )
complete = complete.bgRed.white;
else if ( fn == "warning" )
complete = complete.bgYellow.black
// ... when writing to a custom log function
} else {
complete += fn + ': ' + data;
}
// Check that destination.fn exists, fallback to destination.log
let logger = (config.destination[fn] || config.destination.log).bind(config.destination);
if ( verbose !== undefined ) {
logger(complete, verbose);
} else {
logger(complete);
}
} | javascript | {
"resource": ""
} | |
q36268 | throttle | train | function throttle ( fn, time, context ) {
var lock, args, asyncKey, destroyed
var later = function () {
// reset lock and call if queued
lock = false
if ( args ) {
throttled.apply( context, args )
args = false
}
}
var checkDestroyed = function () {
if ( destroyed ) {
throw new Error( "Method was already destroyed" )
}
}
var throttled = function () {
checkDestroyed()
if ( lock ) {
// called too soon, queue to call later
args = arguments
return
}
// call and lock until later
fn.apply( context, arguments )
asyncKey = setTimeout( later, time )
lock = true
}
throttled.destroy = function () {
checkDestroyed()
if ( asyncKey ) {
clearTimeout( asyncKey )
}
destroyed = true
}
return throttled
} | javascript | {
"resource": ""
} |
q36269 | hasCookies | train | function hasCookies() {
if (navigator.cookieEnabled) {
return true;
}
document.cookie = "cookietest=1";
var ret = document.cookie.indexOf("cookietest=") != -1;
document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT";
return ret;
} | javascript | {
"resource": ""
} |
q36270 | getPageMeta | train | function getPageMeta() {
var data = detectFeatures();
data.title = document.title;
data.url = window.location.href;
data.path = document.location.pathname;
data.referrer = document.referrer;
data.url_section = window.location.pathname.split('/').filter(function(part){
return part.length !== 0;
}).map(function(part){
return part.replace(/\.[^/.]+$/, "");
});
data.hash = window.location.hash;
data.query_string = window.location.search;
return data;
} | javascript | {
"resource": ""
} |
q36271 | train | function(file){
// Sandboxed variables
var filePath = '';
// Read file source
var src = grunt.file.read(file);
// Get file name
var filename = path.basename(file);
// set file extention
if(_opts.ext) {
filename = filename.replace('.js', _opts.ext);
}
if(_opts.sourcemap){
uglifyOpts.outSourceMap = filename + '.map';
mapDest = _destPath + uglifyOpts.outSourceMap;
}
// Minify file source
var result = uglify.minify(file, uglifyOpts);
if(_opts.sourcemap){
// Write source map to file
grunt.file.write( mapDest, result.map );
}
var minSrc = result.code;
// Verbose output by default for now
if(_opts.verbose){
grunt.log.ok(filename.yellow + ': original size: ' + String(src.length).cyan + ' bytes' + ', minified size: ' + String(minSrc.length).cyan + ' bytes.');
if(_opts.sourcemap){
grunt.log.ok('sourcemap generated to ' + uglifyOpts.outSourceMap.yellow);
}
} else {
var _non_verbose_output = filename.yellow + ' minified';
if(_opts.sourcemap){
_non_verbose_output += ', and sourcemapped to ' + uglifyOpts.outSourceMap.yellow;
}
grunt.log.ok(_non_verbose_output);
}
// Set destination
filePath = (_isMirrorSource) ? changeFilePath(file) : _destPath;
minDest = filePath + filename;
// Write minified sorce to destination file
grunt.file.write( minDest, minSrc );
} | javascript | {
"resource": ""
} | |
q36272 | _translateBehind | train | function _translateBehind() {
if (this._zNode) {
this._zNode = this._zNode.add(new Modifier({
transform: Transform.behind
}));
}
else {
this._zNode = this.add(new Modifier({
transform: Transform.behind
}));
}
return this._zNode;
} | javascript | {
"resource": ""
} |
q36273 | _createParticles | train | function _createParticles(node, count) {
this._particles = [];
var options = {
size: [this.options.particleSize, this.options.particleSize],
properties: {
backgroundColor: this.options.color,
borderRadius: '50%'
}
};
for (var i = 0; i < count; i++) {
var particle = {
surface: new Surface(options),
mod: new Modifier({})
};
this._particles.push(particle);
node.add(particle.mod).add(particle.surface);
}
} | javascript | {
"resource": ""
} |
q36274 | _createForeground | train | function _createForeground(node) {
this._foreground = {
surface: new Surface({
size: this.options.size,
properties: {
backgroundColor: this.options.pullToRefreshBackgroundColor
}
}),
mod: new Modifier({})
};
node.add(this._foreground.mod).add(this._foreground.surface);
} | javascript | {
"resource": ""
} |
q36275 | _positionForeground | train | function _positionForeground(renderSize) {
if (this._pullToRefreshDirection) {
this._foreground.mod.transformFrom(Transform.translate(0, renderSize[1], 0));
}
else {
this._foreground.mod.transformFrom(Transform.translate(renderSize[0], 0, 0));
}
} | javascript | {
"resource": ""
} |
q36276 | train | function (filePatterns, destination, options) {
try {
var fse = require('fs-extra')
} catch (e) {
console.error('This method can only be used in server applications.\n' +
'Consider using the alternative method "i18nCompile.fromString()" instead.')
}
options = options || {};
var matchedFiles = _.map(filePatterns, function (pattern) {
return glob.sync(pattern);
});
var files = _.uniq(_.flatten(matchedFiles));
var srcList = files.filter(function (filepath) {
// Warn on and remove invalid source files (if nonull was set).
try {
fse.accessSync(filepath);
return true;
} catch (e) {
console.warn('Source file "' + filepath + '" not found.');
return false;
}
}).map(function (filepath) {
// Read YAML file.
var content = yaml.safeLoad(fse.readFileSync(filepath, 'utf8'), {
filename: filepath,
schema: yaml.JSON_SCHEMA
});
return new SrcItem(filepath, content);
});
var compiled = compileTranslations(srcList);
// Handle options.
if (options.merge) {
// Write the destination file(with all languages merged in the same file).
fse.outputFileSync(destination, JSON.stringify(compiled));
// Print a success message.
console.log('File "' + destination + '" created.');
return;
}
// Write the destination files.
for (var lang in compiled) {
var fileDest = langFileDest(destination, lang, options.langPlace);
fse.outputFileSync(fileDest, JSON.stringify(compiled[lang]));
// Print a success message.
console.log('File "' + fileDest + '" created.');
}
} | javascript | {
"resource": ""
} | |
q36277 | randomDate | train | function randomDate() {
var start = new Date(1995, 5, 16),
end = new Date(),
current = start,
dates = [];
while (current < end) {
dates.push([
current.getFullYear(),
current.getMonth() + 1,
current.getDate()
].join("-"));
current.setDate(current.getDate() + 1);
}
return dates[Math.floor(Math.random() * dates.length)];
} | javascript | {
"resource": ""
} |
q36278 | train | function ( n, k ) {
if ( ! n || ( n < k ) )
throw new RangeError( 'check input values' )
;
// buffer for generating combinations
const buff = balloc( n, 0 )
// colex recursive generator
, colex_gen = function *( n, k ) {
if ( n === 0 ) yield buff;
else {
if ( k < n ) {
buff[ n - 1 ] = 0;
yield* colex_gen( n - 1, k );
}
if ( k > 0 ) {
buff[ n - 1 ] = 1;
yield* colex_gen( n - 1, k - 1 );
}
}
}
// generating colex order for k <= n/2.
, colex_gen_2 = function *( n, k ) {
if ( k === 0 ) yield buff;
else {
if ( k < n ) {
buff[ n - 1 ] = 0;
yield* colex_gen_2( n - 1, k );
}
buff[ n - 1 ] = 1;
yield* colex_gen_2( n - 1, k - 1);
buff[ n - 1 ] = 0;
}
}
;
return ( k > n / 2 ) ?
colex_gen( n , k ) :
colex_gen_2( n, k )
;
} | javascript | {
"resource": ""
} | |
q36279 | build | train | function build (args, cb) {
readAll(args, function (er, args) {
if (er) return cb(er)
// do all preinstalls, then check deps, then install all, then finish up.
chain
( [asyncMap, args, function (a, cb) {
return lifecycle(a, "preinstall", cb)
}]
, [asyncMap, args, function (a, cb) {
return resolveDependencies(a, cb)
}]
, [ asyncMap
, args
, function (pkg, cb) {
linkModules(pkg, path.join(npm.root, pkg.name+"@"+pkg.version), cb)
}
, linkBins
, linkMans
]
// must rebuild bundles serially, because it messes with configs.
, [chain].concat(args.map(function (a) { return [rebuildBundle, a] }))
, [linkDependencies, args]
, [finishBuild, args]
, cb
)
})
} | javascript | {
"resource": ""
} |
q36280 | resolveDependencies | train | function resolveDependencies (pkg, cb) {
if (!pkg) return topCb(new Error(
"Package not found to resolve dependencies"))
// link foo-1.0.3 to ROOT/.npm/{pkg}/{version}/node_modules/foo
// see if it's bundled already
var bundleDir = path.join( npm.dir, pkg.name, pkg.version
, "package", "node_modules" )
, deps = pkg.dependencies && Object.keys(pkg.dependencies) || []
log.verbose([pkg, deps], "deps being resolved")
fs.readdir(bundleDir, function (er, bundledDeps) {
if (er) bundledDeps = []
bundledDeps.forEach(function (bd) {
var i = deps.indexOf(bd)
if (i !== -1) deps.splice(i, 1)
})
asyncMap(deps, function (i, cb) {
var req = { name:i, version:pkg.dependencies[i] }
log.verbose(req.name+"@"+req.version, "required")
// see if we have this thing installed.
fs.readdir(path.join(npm.dir, req.name), function (er, versions) {
if (er) return cb(new Error(
"Required package: "+req.name+"("+req.version+") not found."+
"\n(required by: "+pkg._id+")"))
// TODO: Get the "stable" version if there is one.
// Look that up from the registry.
var satis = semver.maxSatisfying(versions, req.version)
if (satis) return cb(null, {name:req.name, version:satis})
return cb(new Error(
"Required package: "+req.name+"("+req.version+") not found. "+
"(Found: "+JSON.stringify(versions)+")"+
"\n(required by: "+pkg._id+")"))
})
}, function (er, found) {
// save the resolved dependencies on the pkg data for later
pkg._resolvedDeps = found
cb(er, found)
})
})
} | javascript | {
"resource": ""
} |
q36281 | dependentLink | train | function dependentLink (pkg, cb) {
asyncMap(pkg._resolvedDeps, function (dep, cb) {
var dependents = path.join(npm.dir, dep.name, dep.version, "dependents")
, to = path.join(dependents, pkg.name + "@" + pkg.version)
, from = path.join(npm.dir, pkg.name, pkg.version)
link(from, to, cb)
}, cb)
} | javascript | {
"resource": ""
} |
q36282 | dependencyLink | train | function dependencyLink (pkg, cb) {
var dependencies = path.join(npm.dir, pkg.name, pkg.version, "node_modules")
, depBin = path.join(npm.dir, pkg.name, pkg.version, "dep-bin")
asyncMap(pkg._resolvedDeps, function (dep, cb) {
log.silly(dep, "dependency")
var fromRoot = path.join(npm.dir, dep.name, dep.version)
, dependsOn = path.join( npm.dir, pkg.name, pkg.version
, "dependson", dep.name + "@" + dep.version
)
link(fromRoot, dependsOn, cb)
}, function (dep, cb) {
var depDir = path.join(npm.dir, dep.name, dep.version, "package")
readJson(path.join(depDir, "package.json"), function (er, dep) {
if (er) return cb(er)
loadPackageDefaults(dep, function (er, dep) {
if (er) return cb(er)
asyncMap([dep], function (dep) {
var toLib = path.join(dependencies, dep.name)
linkModules(dep, toLib, cb)
}, function (dep, cb) {
// link the bins to this pkg's "dep-bin" folder.
linkBins(dep, depBin, false, cb)
}, cb)
})
})
}, cb)
} | javascript | {
"resource": ""
} |
q36283 | getPrev | train | function getPrev(renderTree) {
if (!renderTree || !renderTree.children || renderTree.children.length < 1
|| !renderTree.children[renderTree.children.length - 1]) {
return;
}
return renderTree.children[renderTree.children.length - 1];
} | javascript | {
"resource": ""
} |
q36284 | shuffleArray | train | function shuffleArray (options, arr) {
if (!options.minify) { return undefined; }
for (let i = 0, max = arr.length; i < max; i++) {
let j = randomInt(max);
if (arr[j] !== arr[i]) {
let source = arr[i];
arr[i] = arr[j];
arr[j] = source;
}
}
} | javascript | {
"resource": ""
} |
q36285 | parseExtend | train | function parseExtend (ast) {
for (let i = 0, max = ast.body.length; i < max; i++) {
let node = ast.body[i];
// Search for extend('Parent', 'Child');
if (isExpressionStatement(node) && isCallExpression(node.expression) && node.expression.callee.name === 'extend') {
node = node.expression;
let parent = node.arguments[0].value;
let child = node.arguments[1].value;
createHierarchyNode(parent);
createHierarchyNode(child);
// Link child to parent.
hierarchy[parent].children.push(child);
// Link parent to child.
hierarchy[child].parent = parent;
return true;
}
}
return false;
} | javascript | {
"resource": ""
} |
q36286 | parseClass | train | function parseClass (ast, content) {
let appendNode = null;
let appendName = '';
let constructorNode = null;
let constructorName = '';
for (let i = 0, max = ast.body.length; i < max; i++) {
let node = ast.body[i];
if (!isExpressionStatement(node) || !isAssignmentExpression(node.expression)) { continue; }
node = node.expression;
// Search for constructor -> CLASS.Module = function () {};
if (isIdentifier(node.left.object) && isIdentifier(node.left.property) && node.left.object.name === 'CLASS') {
constructorNode = node;
constructorName = node.left.property.name;
// Search for append -> CLASS.Module.append = {};
} else if (isMemberExpression(node.left.object)) {
let subNode = node.left;
if (isIdentifier(subNode.object.object) && isIdentifier(subNode.object.property)) {
if (subNode.object.object.name !== 'CLASS' || subNode.property.name !== 'append') { continue; }
appendNode = node;
appendName = subNode.object.property.name;
}
}
}
// If no constructor or append node is found or if the constructor and
// append name do not match then don't create the hierarchy node.
if (constructorNode === null || appendNode === null) {
return false;
} else if (constructorName !== appendName) {
return false;
}
createHierarchyNode(constructorName);
let hierarchyNode = hierarchy[constructorName];
hierarchyNode.content = content;
hierarchyNode.appendNode = appendNode;
hierarchyNode.constructorNode = constructorNode;
return true;
} | javascript | {
"resource": ""
} |
q36287 | processClass | train | function processClass (options, name, node) {
processClassConstructor(options, name, node);
processClassAppend(options, name, node);
shuffleArray(options, node.children);
for (let i = 0, max = node.children.length; i < max; i++) {
let child = node.children[i];
processClass(options, child, hierarchy[child]);
}
} | javascript | {
"resource": ""
} |
q36288 | config | train | function config (args, cb) {
var action = args.shift()
switch (action) {
case "set": return set(args[0], args[1], cb)
case "get": return get(args[0], cb)
case "delete": case "rm": case "del": return del(args[0], cb)
case "list": case "ls": return list(cb)
case "edit": return edit(cb)
default: return unknown(action, cb)
}
} | javascript | {
"resource": ""
} |
q36289 | init | train | function init(input) {
// Use provided pool
if(typeof input == 'function') db.pool = input;
else {
// Create the pool with any options merged with the below defaults
db.pool = mysql.createPool(Object.assign({
user: 'root',
password: 'root',
database: 'test'
},input));
}
// Set the local _pool(just for convenience)
_pool = db.pool;
return db;
} | javascript | {
"resource": ""
} |
q36290 | _checkConnection | train | function _checkConnection(conn) {
// Return Promise for getConnection callback wrapping
return new Promise((resolve, reject) => {
if (conn) {
resolve(conn);
} else {
_pool.getConnection((err, conn) => {
if (err) reject(err); // Reject this error
else resolve(conn); // Resolve the connection
})
}
});
} | javascript | {
"resource": ""
} |
q36291 | train | function(sql, val, callback) {
let qry = (typeof sql === 'object') ? sql : mysql.format(sql, val);
if (!callback && typeof val === 'function') callback = val; // Handle 2 parm scenario
_pool.getConnection((err, conn) => {
_pool.query(qry, (err, items, fields) => {
if (err) return callback(err);
conn.release();
callback(err, items);
});
});
} | javascript | {
"resource": ""
} | |
q36292 | knexAppender | train | function knexAppender(config, layouts) {
if (! config.knex) {
throw new Error('knex.js connection parameters are missing');
}
let layout = null;
if (config.layout) {
layout = layouts.layout(config.layout.type, config.layout);
} else {
layout = layouts.messagePassThroughLayout;
}
let tableName = config.table || 'log';
let additionalFields = config.additionalFields || {};
let knex = typeof config.knex === 'object' ? Knex(config.knex) : config.knex;
function writeEvent(loggingEvent) {
// Build a record to insert
const record = Object.assign({}, {
time: loggingEvent.startTime.valueOf(),
data: layout(loggingEvent),
rank: loggingEvent.level.level,
level: loggingEvent.level.levelStr,
category: loggingEvent.categoryName
}, additionalFields);
// Insert it, inside a transaction
return knex.transaction((trx) => trx(tableName).insert(record).then(() => null));
};
return writeEvent;
} | javascript | {
"resource": ""
} |
q36293 | match | train | function match(regex, callback) {
return inspect(onComplete);
function onComplete(filename, contents, done) {
callback(filename, contents.match(regex), done);
if (callback.length < 3) {
done();
}
}
} | javascript | {
"resource": ""
} |
q36294 | random | train | function random (arg, used) {
var n;
do {
n = Math.floor(Math.random() * arg);
} while (used[n]);
used[n] = 1;
return n;
} | javascript | {
"resource": ""
} |
q36295 | train | function(err, res) {
if(err) {
return onError('Weird Error open', err);
}
//Check for no errors
if(res === 0) {
//Save the handle & other information to the
// device class
self.handle = refDeviceHandle.readInt32LE(0);
self.deviceType = deviceType;
self.connectionType = connectionType;
self.identifier = identifier;
self.isHandleValid = true;
return onSuccess();
} else {
//Make sure that the handle, deviceType
// & connectionType are still null
self.handle = null;
self.deviceType = null;
self.connectionType = null;
self.identifier = null;
return onError(res);
}
} | javascript | {
"resource": ""
} | |
q36296 | train | function(address, writeData) {
var writeInfo = {
'isValid': false,
'message': 'Unknown Reason',
// Data to be written
'address': undefined,
'type': undefined,
'numValues': undefined,
'aValues': undefined,
'errorAddress': undefined,
};
var info = self.constants.getAddressInfo(address, 'W');
var isDirectionValid = info.directionValid == 1;
var isBufferRegister = false;
if(info.data) {
if(info.data.isBuffer) {
isBufferRegister = true;
}
}
if (isDirectionValid && isBufferRegister) {
writeInfo.isValid = true;
// Save info
writeInfo.address = info.address;
writeInfo.type = info.type;
var errorVal = new ref.alloc('int',1);
errorVal.fill(0);
writeInfo.errorAddress = errorVal;
// Variable declarations:
var aValues, offset, i;
// Check to see if the input-data is of the type "buffer"
if(Buffer.isBuffer(writeData)) {
writeInfo.isValid = false;
writeInfo.message = 'Buffer type is not supported';
} else if(Array.isArray(writeData)) {
writeInfo.numValues = writeData.length;
aValues = new Buffer(writeData.length * ARCH_DOUBLE_NUM_BYTES);
aValues.fill(0);
offset = 0;
for(i = 0; i < writeData.length; i++) {
aValues.writeDoubleLE(writeData[i], offset);
offset += ARCH_DOUBLE_NUM_BYTES;
}
writeInfo.aValues = aValues;
} else if((typeof(writeData) === 'string') || (writeData instanceof String)) {
writeInfo.numValues = writeData.length;
aValues = new Buffer(writeData.length * ARCH_DOUBLE_NUM_BYTES);
aValues.fill(0);
offset = 0;
for(i = 0; i < writeData.length; i++) {
aValues.writeDoubleLE(writeData.charCodeAt(i), offset);
offset += ARCH_DOUBLE_NUM_BYTES;
}
writeInfo.aValues = aValues;
} else {
// Un-supported type
writeInfo.isValid = false;
writeInfo.message = 'Invalid data type being written: ' + typeof(writeData) + '.';
}
writeInfo.numValues = writeData.length;
} else {
writeInfo.isValid = false;
if (info.type == -1) {
writeInfo.message = 'Invalid Address';
} else if (info.directionValid === 0) {
writeInfo.message = 'Invalid Read Attempt';
} else if (!isBufferRegister) {
writeInfo.message = 'Tried to read an array from a register that is not a buffer';
}
}
return writeInfo;
} | javascript | {
"resource": ""
} | |
q36297 | train | function(manifest) {
var out = "/*\n";
_.forEach(fields, function(n, key) {
if (typeof manifest[key] != "undefined") {
out += pad(n+":", 20) + manifest[key] + "\n";
}
});
out += "*/\n";
return out;
} | javascript | {
"resource": ""
} | |
q36298 | streamWrappers | train | function streamWrappers (grunt, fileData, options) {
stream.createWriteStream(fileData.tmpWrapStart, () => {
streamWrapperEnd(grunt, fileData, options);
});
if (options.license) {
streamLicense(grunt, fileData, options);
} else {
streamWrapperStart(grunt, fileData, options);
}
} | javascript | {
"resource": ""
} |
q36299 | streamLicense | train | function streamLicense (grunt, fileData, options) {
let content = grunt.file.read(options.license);
// Use JSDoc license tag to preserve file content as
// comment when minifying.
if (options.deploy && options.minify) {
content = `/**@license ${content}*/`;
} else {
content = `/*\x0A${content}*/\x0A\x0A`;
}
stream.write(content, () => {
streamWrapperStart(grunt, fileData, options);
});
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.