_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q55400
|
format
|
train
|
function format(str, obj) {
if (obj instanceof Array) {
var i = 0, len = obj.length;
//find the matches
return str.replace(FORMAT_REGEX, function (m, format, type) {
var replacer, ret;
if (i < len) {
replacer = obj[i++];
} else {
//we are out of things to replace with so
//just return the match?
return m;
}
if (m === "%s" || m === "%d" || m === "%D") {
//fast path!
ret = replacer + "";
} else if (m === "%Z") {
ret = replacer.toUTCString();
} else if (m === "%j") {
try {
ret = JSON.stringify(replacer);
} catch (e) {
throw new Error("comb.string.format : Unable to parse json from ", replacer);
}
} else {
format = format.replace(/^\[|\]$/g, "");
switch (type) {
case "s":
ret = formatString(replacer, format);
break;
case "d":
ret = formatNumber(replacer, format);
break;
case "j":
ret = formatObject(replacer, format);
break;
case "D":
ret = getDate().date.format(replacer, format);
break;
case "Z":
ret = getDate().date.format(replacer, format, true);
break;
}
}
return ret;
});
} else if (isHash(obj)) {
return str.replace(INTERP_REGEX, function (m, format, value) {
value = obj[value];
if (!misc.isUndefined(value)) {
if (format) {
if (comb.isString(value)) {
return formatString(value, format);
} else if (typeof value === "number") {
return formatNumber(value, format);
} else if (getDate().isDate(value)) {
return getDate().date.format(value, format);
} else if (typeof value === "object") {
return formatObject(value, format);
}
} else {
return "" + value;
}
}
return m;
});
} else {
var args = pSlice.call(arguments).slice(1);
return format(str, args);
}
}
|
javascript
|
{
"resource": ""
}
|
q55401
|
style
|
train
|
function style(str, options) {
var ret = str;
if (options) {
if (ret instanceof Array) {
ret = ret.map(function (s) {
return style(s, options);
});
} else if (options instanceof Array) {
options.forEach(function (option) {
ret = style(ret, option);
});
} else if (options in styles) {
ret = '\x1B[' + styles[options] + 'm' + str + '\x1B[0m';
}
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q55402
|
applyFirst
|
train
|
function applyFirst(method, args) {
args = Array.prototype.slice.call(arguments).slice(1);
if (!isString(method) && !isFunction(method)) {
throw new Error(method + " must be the name of a property or function to execute");
}
if (isString(method)) {
return function () {
var scopeArgs = Array.prototype.slice.call(arguments), scope = scopeArgs.shift();
var func = scope[method];
if (isFunction(func)) {
scopeArgs = args.concat(scopeArgs);
return spreadArgs(func, scopeArgs, scope);
} else {
return func;
}
};
} else {
return function () {
var scopeArgs = Array.prototype.slice.call(arguments), scope = scopeArgs.shift();
scopeArgs = args.concat(scopeArgs);
return spreadArgs(method, scopeArgs, scope);
};
}
}
|
javascript
|
{
"resource": ""
}
|
q55403
|
each
|
train
|
function each(iterator) {
for (var i = 0, length = this.length; i < length; i++)
iterator(this[i]);
}
|
javascript
|
{
"resource": ""
}
|
q55404
|
asyncForEach
|
train
|
function asyncForEach(promise, iterator, scope, limit) {
return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) {
return results.arr;
}));
}
|
javascript
|
{
"resource": ""
}
|
q55405
|
asyncMap
|
train
|
function asyncMap(promise, iterator, scope, limit) {
return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) {
return results.loopResults;
}));
}
|
javascript
|
{
"resource": ""
}
|
q55406
|
asyncFilter
|
train
|
function asyncFilter(promise, iterator, scope, limit) {
return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) {
var loopResults = results.loopResults, resultArr = results.arr;
return (isArray(resultArr) ? resultArr : [resultArr]).filter(function (res, i) {
return loopResults[i];
});
}));
}
|
javascript
|
{
"resource": ""
}
|
q55407
|
asyncEvery
|
train
|
function asyncEvery(promise, iterator, scope, limit) {
return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) {
return results.loopResults.every(function (res) {
return !!res;
});
}));
}
|
javascript
|
{
"resource": ""
}
|
q55408
|
asyncSome
|
train
|
function asyncSome(promise, iterator, scope, limit) {
return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) {
return results.loopResults.some(function (res) {
return !!res;
});
}));
}
|
javascript
|
{
"resource": ""
}
|
q55409
|
asyncZip
|
train
|
function asyncZip() {
return asyncArray(when.apply(null, argsToArray(arguments)).chain(function (result) {
return zip.apply(array, normalizeResult(result).map(function (arg) {
return isArray(arg) ? arg : [arg];
}));
}));
}
|
javascript
|
{
"resource": ""
}
|
q55410
|
train
|
function (namespaces, defaultNamespace, name) {
var self = this;
assert(namespaces);
assert(name);
if (/^\{.+\}/.test(name)) {
return name;
}
else if (/:/.test(name)) {
var parts = name.split(':');
assert(parts.length === 2, parts);
if (!namespaces[parts[0]]) {
throw new xml2js.ValidationError("Unknown namespace " + parts[0] + ", name: " + name + ", known namespaces: " + util.inspect(namespaces, false, null));
}
return '{' + namespaces[parts[0]] + '}' + parts[1];
}
else if (defaultNamespace) {
return '{' + defaultNamespace + '}' + name;
}
else {
throw new xml2js.ValidationError("Unqualified name and no default namespace: " + name);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55411
|
createScript
|
train
|
function createScript(url, appID) {
if (!document) { return; }
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = url+appID;
// Attach the script tag to the document head
var s = document.getElementsByTagName('head')[0];
s.appendChild(script);
}
|
javascript
|
{
"resource": ""
}
|
q55412
|
train
|
function() {
if ( !(scope.model instanceof Array) ) {
scope.model = scope.model ? [ scope.model ] : [];
}
return scope.model;
}
|
javascript
|
{
"resource": ""
}
|
|
q55413
|
SemanticPopup
|
train
|
function SemanticPopup(SemanticPopupLink)
{
return {
restrict: 'A',
scope: {
/* Required */
smPopup: '=',
/* Optional */
smPopupTitle: '=',
smPopupHtml: '=',
smPopupPosition: '@',
smPopupVariation: '@',
smPopupSettings: '=',
smPopupOnInit: '=',
/* Events */
smPopupOnCreate: '=',
smPopupOnRemove: '=',
smPopupOnShow: '=',
smPopupOnVisible: '=',
smPopupOnHide: '=',
smPopupOnHidden: '='
},
link: SemanticPopupLink
};
}
|
javascript
|
{
"resource": ""
}
|
q55414
|
SemanticPopupInline
|
train
|
function SemanticPopupInline(SemanticPopupInlineLink)
{
return {
restrict: 'A',
scope: {
/* Optional */
smPopupInline: '=',
smPopupInlineOnInit: '=',
/* Events */
smPopupInlineOnCreate: '=',
smPopupInlineOnRemove: '=',
smPopupInlineOnShow: '=',
smPopupInlineOnVisible: '=',
smPopupInlineOnHide: '=',
smPopupInlineOnHidden: '='
},
link: SemanticPopupInlineLink
};
}
|
javascript
|
{
"resource": ""
}
|
q55415
|
SemanticPopupDisplay
|
train
|
function SemanticPopupDisplay(SemanticPopupDisplayLink)
{
return {
restrict: 'A',
scope: {
/* Required */
smPopupDisplay: '@',
/* Optional */
smPopupDisplaySettings: '=',
smPopupDisplayOnInit: '=',
/* Events */
smPopupDisplayOnCreate: '=',
smPopupDisplayOnRemove: '=',
smPopupDisplayOnShow: '=',
smPopupDisplayOnVisible: '=',
smPopupDisplayOnHide: '=',
smPopupDisplayOnHidden: '='
},
link: SemanticPopupDisplayLink
};
}
|
javascript
|
{
"resource": ""
}
|
q55416
|
walk
|
train
|
function walk(data, path, result, key) {
var fn;
switch (type(path)) {
case 'string':
fn = seekSingle;
break;
case 'array':
fn = seekArray;
break;
case 'object':
fn = seekObject;
break;
}
if (fn) {
fn(data, path, result, key);
}
}
|
javascript
|
{
"resource": ""
}
|
q55417
|
seekSingle
|
train
|
function seekSingle(data, pathStr, result, key) {
if(pathStr.indexOf('$') < 0){
result[key] = pathStr;
}else{
var seek = jsonPath.eval(data, pathStr) || [];
result[key] = seek.length ? seek[0] : undefined;
}
}
|
javascript
|
{
"resource": ""
}
|
q55418
|
seekArray
|
train
|
function seekArray(data, pathArr, result, key) {
var subpath = pathArr[1];
var path = pathArr[0];
var seek = jsonPath.eval(data, path) || [];
if (seek.length && subpath) {
result = result[key] = [];
seek[0].forEach(function(item, index) {
walk(item, subpath, result, index);
});
} else {
result[key] = seek;
}
}
|
javascript
|
{
"resource": ""
}
|
q55419
|
seekObject
|
train
|
function seekObject(data, pathObj, result, key) {
if (typeof key !== 'undefined') {
result = result[key] = {};
}
Object.keys(pathObj).forEach(function(name) {
walk(data, pathObj[name], result, name);
});
}
|
javascript
|
{
"resource": ""
}
|
q55420
|
train
|
function(selection, mainTemplate, suggestionsTemplate) {
selection = defaults({}, selection, {
isMisspelled: false,
spellingSuggestions: []
});
var template = getTemplate(mainTemplate, DEFAULT_MAIN_TPL);
var suggestionsTpl = getTemplate(suggestionsTemplate, DEFAULT_SUGGESTIONS_TPL);
if (selection.isMisspelled) {
var suggestions = selection.spellingSuggestions;
if (isEmpty(suggestions)) {
template.unshift.apply(template, suggestionsTpl);
} else {
template.unshift.apply(template, suggestions.map(function(suggestion) {
return {
label: suggestion,
click: function() {
BrowserWindow.getFocusedWindow().webContents.replaceMisspelling(suggestion);
}
};
}).concat({
type: 'separator'
}));
}
}
return Menu.buildFromTemplate(template);
}
|
javascript
|
{
"resource": ""
}
|
|
q55421
|
resize
|
train
|
function resize(w, h) {
w && self.view.win.width(w);
h && self.view.nav.add(self.view.cwd).height(h);
}
|
javascript
|
{
"resource": ""
}
|
q55422
|
dialogResize
|
train
|
function dialogResize() {
resize(null, self.dialog.height()-self.view.tlb.parent().height()-($.browser.msie ? 47 : 32))
}
|
javascript
|
{
"resource": ""
}
|
q55423
|
reset
|
train
|
function reset() {
self.media.hide().empty();
self.win.attr('class', 'el-finder-ql').css('z-index', self.fm.zIndex);
self.title.empty();
self.ico.removeAttr('style').show();
self.add.hide().empty();
self._hash = '';
}
|
javascript
|
{
"resource": ""
}
|
q55424
|
update
|
train
|
function update() {
var f = self.fm.getSelected(0);
reset();
self._hash = f.hash;
self.title.text(f.name);
self.win.addClass(self.fm.view.mime2class(f.mime));
self.name.text(f.name);
self.kind.text(self.fm.view.mime2kind(f.link ? 'symlink' : f.mime));
self.size.text(self.fm.view.formatSize(f.size));
self.date.text(self.fm.i18n('Modified')+': '+self.fm.view.formatDate(f.date));
f.dim && self.add.append('<span>'+f.dim+' px</span>').show();
f.tmb && self.ico.css('background', 'url("'+f.tmb+'") 0 0 no-repeat');
if (f.url) {
self.url.text(f.url).attr('href', f.url).show();
for (var i in self.plugins) {
if (self.plugins[i].test && self.plugins[i].test(f.mime, self.mimes, f.name)) {
self.plugins[i].show(self, f);
return;
}
}
} else {
self.url.hide();
}
self.win.css({
width : '420px',
height : 'auto'
});
}
|
javascript
|
{
"resource": ""
}
|
q55425
|
moveSelection
|
train
|
function moveSelection(forward, reset) {
var p, _p, cur;
if (!$('[key]', self.cwd).length) {
return;
}
if (self.fm.selected.length == 0) {
p = $('[key]:'+(forward ? 'first' : 'last'), self.cwd);
self.fm.select(p);
} else if (reset) {
p = $('.ui-selected:'+(forward ? 'last' : 'first'), self.cwd);
_p = p[forward ? 'next' : 'prev']('[key]');
if (_p.length) {
p = _p;
}
self.fm.select(p, true);
} else {
if (self.pointer) {
cur = $('[key="'+self.pointer+'"].ui-selected', self.cwd);
}
if (!cur || !cur.length) {
cur = $('.ui-selected:'+(forward ? 'last' : 'first'), self.cwd);
}
p = cur[forward ? 'next' : 'prev']('[key]');
if (!p.length) {
p = cur;
} else {
if (!p.hasClass('ui-selected')) {
self.fm.select(p);
} else {
if (!cur.hasClass('ui-selected')) {
self.fm.unselect(p);
} else {
_p = cur[forward ? 'prev' : 'next']('[key]')
if (!_p.length || !_p.hasClass('ui-selected')) {
self.fm.unselect(cur);
} else {
while ((_p = forward ? p.next('[key]') : p.prev('[key]')) && p.hasClass('ui-selected')) {
p = _p;
}
self.fm.select(p);
}
}
}
}
}
self.pointer = p.attr('key');
self.fm.checkSelectedPos(forward);
}
|
javascript
|
{
"resource": ""
}
|
q55426
|
train
|
function(oExpression, sIdentifierName) {
fCountPrimaryExpression(
EPrimaryExpressionCategories.N_IDENTIFIER_NAMES,
EValuePrefixes.S_STRING + sIdentifierName);
return ['dot', oWalker.walk(oExpression), sIdentifierName];
}
|
javascript
|
{
"resource": ""
}
|
|
q55427
|
train
|
function(oExpression, sIdentifierName) {
/**
* The prefixed String value that is equivalent to the
* sequence of terminal symbols that constitute the
* encountered identifier name.
* @type {string}
*/
var sPrefixed = EValuePrefixes.S_STRING + sIdentifierName;
return oSolutionBest.oPrimitiveValues.hasOwnProperty(
sPrefixed) &&
oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
['sub',
oWalker.walk(oExpression),
['name',
oSolutionBest.oPrimitiveValues[sPrefixed].sName]] :
['dot', oWalker.walk(oExpression), sIdentifierName];
}
|
javascript
|
{
"resource": ""
}
|
|
q55428
|
train
|
function(sIdentifier) {
/**
* The prefixed representation String of the identifier.
* @type {string}
*/
var sPrefixed = EValuePrefixes.S_SYMBOLIC + sIdentifier;
return [
'name',
oSolutionBest.oPrimitiveValues.hasOwnProperty(sPrefixed) &&
oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
oSolutionBest.oPrimitiveValues[sPrefixed].sName :
sIdentifier
];
}
|
javascript
|
{
"resource": ""
}
|
|
q55429
|
train
|
function(sStringValue) {
/**
* The prefixed representation String of the primitive value
* of the literal.
* @type {string}
*/
var sPrefixed =
EValuePrefixes.S_STRING + sStringValue;
return oSolutionBest.oPrimitiveValues.hasOwnProperty(
sPrefixed) &&
oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
['name',
oSolutionBest.oPrimitiveValues[sPrefixed].sName] :
['string', sStringValue];
}
|
javascript
|
{
"resource": ""
}
|
|
q55430
|
moveTopDown
|
train
|
function moveTopDown(node, dx, dy) {
var nodes = node.union(node.descendants());
nodes.filter(":childless").positions(function (node, i) {
if(typeof node === "number") {
node = i;
}
var pos = node.position();
return {
x: pos.x + dx,
y: pos.y + dy
};
});
}
|
javascript
|
{
"resource": ""
}
|
q55431
|
getOutputDir
|
train
|
function getOutputDir(output) {
var arr = output.split(path.sep);
arr.pop();
return arr.join(path.sep);
}
|
javascript
|
{
"resource": ""
}
|
q55432
|
getOutputFilePath
|
train
|
function getOutputFilePath(input, outputDir, suffix) {
var inputArr = input.split(path.sep);
var originFileName = inputArr[inputArr.length - 1];
var newFileName = originFileName.replace(/\.png$/, suffix + '.png');
var outputFilePath = path.join(outputDir, newFileName);
return outputFilePath;
}
|
javascript
|
{
"resource": ""
}
|
q55433
|
getBytes
|
train
|
function getBytes(key, callback) {
this.redisClient.get(key, function(err, valueBytes) {
if (err) { return callback(err) }
if (!valueBytes) { return callback(null, null) }
callback(null, valueBytes.toString())
})
}
|
javascript
|
{
"resource": ""
}
|
q55434
|
onDecision
|
train
|
function onDecision(err, target) {
//
// If there was no target then this is a 404 by definition
// even if it exists in the public registry because of a
// potential whitelist.
//
if (err || !target) {
return self.notFound(req, res, err || { message: 'Unknown pkg: ' + pkg });
}
// if X-Forwarded-Host is set, npm returns 404 {"error":"not_found","reason":"no_db_file"}
if (req.headers["x-forwarded-host"]) delete req.headers["x-forwarded-host"];
//
// If we get a valid target then we can proxy to it
//
self.log.info('[decide] %s - %s %s %s %j', address, req.method, req.url, target.vhost || target.host || target.hostname, req.headers);
self.emit('headers', req, req.headers, target);
req.headers.host = target.vhost || target.host || target.hostname;
proxy.web(req, res, {
target: target.href
});
}
|
javascript
|
{
"resource": ""
}
|
q55435
|
implicitGrant
|
train
|
function implicitGrant (iconfig) {
/* */
let link = iconfig.link ;
window.location.href = `${iconfig.host + link.href}?response_type=${link.responseType}&client_id=${iconfig.clientID}`;
return new Promise.resolve()
}
|
javascript
|
{
"resource": ""
}
|
q55436
|
apiSubmit
|
train
|
async function apiSubmit (store, iroute, payload, delay, jobContext, onCompletion, progress){
if (progress) {
progress('pending', jobContext);
}
let job = await iapiCall(store, iroute, API_CALL, payload, 0, null, null, jobContext);
if (job.links('state')) {
let status = await jobState(store, job, null, 'wait', delay, progress, jobContext);
completion(store, onCompletion,status.data,status.job, jobContext);
return status.job;
} else {
completion(store, onCompletion, 'unknown', job, jobContext);
return job;
}
}
|
javascript
|
{
"resource": ""
}
|
q55437
|
Command
|
train
|
function Command(command, options) {
var previousPath;
this.command = command;
// We're on Windows if `process.platform` starts with "win", i.e. "win32".
this.isWindows = (process.platform.lastIndexOf('win') === 0);
// the cwd and environment of the command are the same as the main node
// process by default.
this.options = defaults(options || {}, {
cwd: process.cwd(),
env: process.env,
verbosity: (options && options.silent) ? 1 : 2,
usePowerShell: false
});
// include node_modules/.bin on the path when we execute the command.
previousPath = this.options.env.PATH;
this.options.env.PATH = path.join(this.options.cwd, 'node_modules', '.bin');
this.options.env.PATH += path.delimiter;
this.options.env.PATH += previousPath;
}
|
javascript
|
{
"resource": ""
}
|
q55438
|
GulpRunner
|
train
|
function GulpRunner(template, options) {
if (!(this instanceof GulpRunner)) {
return new GulpRunner(template, options);
}
this.command = new Command(template, options || {});
Transform.call(this, { objectMode: true });
}
|
javascript
|
{
"resource": ""
}
|
q55439
|
train
|
function(arg1) {
if (arg1 == null) { return null; }
var args = [name, 'root'].concat(grunt.util.toArray(arguments));
return helpers.getFile.apply(helpers, args);
}
|
javascript
|
{
"resource": ""
}
|
|
q55440
|
train
|
function(files, licenses) {
licenses.forEach(function(license) {
var fileobj = helpers.expand({filter: 'isFile'}, 'licenses/LICENSE-' + license)[0];
if(fileobj) {
files['LICENSE-' + license] = fileobj.rel;
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q55441
|
train
|
function(srcpath, destpath, options) {
// Destpath is optional.
if (typeof destpath !== 'string') {
options = destpath;
destpath = srcpath;
}
// Ensure srcpath is absolute.
if (!grunt.file.isPathAbsolute(srcpath)) {
srcpath = init.srcpath(srcpath);
}
// Use placeholder file if no src exists.
if (!srcpath) {
srcpath = helpers.getFile('misc/placeholder');
}
grunt.verbose.or.write('Writing ' + destpath + '...');
try {
grunt.file.copy(srcpath, init.destpath(destpath), options);
grunt.verbose.or.ok();
} catch(e) {
grunt.verbose.or.error().error(e);
throw e;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55442
|
train
|
function(files, props, options) {
options = _.defaults(options || {}, {
process: function(contents) {
return grunt.template.process(contents, {data: props, delimiters: 'init'});
}
});
Object.keys(files).forEach(function(destpath) {
var o = Object.create(options);
var srcpath = files[destpath];
// If srcpath is relative, match it against options.noProcess if
// necessary, then make srcpath absolute.
var relpath;
if (srcpath && !grunt.file.isPathAbsolute(srcpath)) {
if (o.noProcess) {
relpath = srcpath.slice(pathPrefix.length);
o.noProcess = grunt.file.isMatch({matchBase: true}, o.noProcess, relpath);
}
srcpath = helpers.getFile(srcpath);
}
// Copy!
init.copy(srcpath, destpath, o);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q55443
|
Validator
|
train
|
function Validator(validatorsNamesList) {
// add default embedded validator name
validatorsNamesList.unshift('vsGooglePlace');
this._embeddedValidators = vsEmbeddedValidatorsInjector.get(validatorsNamesList);
this.error = {};
this.valid = true;
}
|
javascript
|
{
"resource": ""
}
|
q55444
|
parseValidatorNames
|
train
|
function parseValidatorNames(attrs) {
var attrValue = attrs.vsAutocompleteValidator,
validatorNames = (attrValue!=="") ? attrValue.trim().split(',') : [];
// normalize validator names
for (var i = 0; i < validatorNames.length; i++) {
validatorNames[i] = attrs.$normalize(validatorNames[i]);
}
return validatorNames;
}
|
javascript
|
{
"resource": ""
}
|
q55445
|
serialize
|
train
|
function serialize(value) {
if (Array.isArray(value) === true) {
return serializeArray(value);
}
if (isObject(value) === false) {
return serializePrimitive(value);
}
return serializeObject(value);
}
|
javascript
|
{
"resource": ""
}
|
q55446
|
train
|
function () {
var filter = can.route.attr('filter');
return this.todos.filter(function (todo) {
if (filter === 'completed') {
return todo.attr('complete');
}
if (filter === 'active') {
return !todo.attr('complete');
}
return true;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q55447
|
train
|
function(el, val) {
if (val == null || val === "") {
el.removeAttribute("src");
return null;
} else {
el.setAttribute("src", val);
return val;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55448
|
train
|
function() {
if (arguments.length === 0 && can.Control && this instanceof can.Control) {
return can.Control.prototype.on.call(this);
} else {
return can.addEvent.apply(this, arguments);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55449
|
train
|
function(fullName, klass, proto) {
// Figure out what was passed and normalize it.
if (typeof fullName !== 'string') {
proto = klass;
klass = fullName;
fullName = null;
}
if (!proto) {
proto = klass;
klass = null;
}
proto = proto || {};
var _super_class = this,
_super = this.prototype,
parts, current, _fullName, _shortName, name, shortName, namespace, prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor).
prototype = this.instance();
// Copy the properties over onto the new prototype.
can.Construct._inherit(proto, _super, prototype);
// The dummy class constructor.
function Constructor() {
// All construction is actually done in the init method.
if (!initializing) {
return this.constructor !== Constructor &&
// We are being called without `new` or we are extending.
arguments.length && Constructor.constructorExtends ? Constructor.extend.apply(Constructor, arguments) :
// We are being called with `new`.
Constructor.newInstance.apply(Constructor, arguments);
}
}
// Copy old stuff onto class (can probably be merged w/ inherit)
for (name in _super_class) {
if (_super_class.hasOwnProperty(name)) {
Constructor[name] = _super_class[name];
}
}
// Copy new static properties on class.
can.Construct._inherit(klass, _super_class, Constructor);
// Setup namespaces.
if (fullName) {
parts = fullName.split('.');
shortName = parts.pop();
current = can.getObject(parts.join('.'), window, true);
namespace = current;
_fullName = can.underscore(fullName.replace(/\./g, "_"));
_shortName = can.underscore(shortName);
current[shortName] = Constructor;
}
// Set things that shouldn't be overwritten.
can.extend(Constructor, {
constructor: Constructor,
prototype: prototype,
namespace: namespace,
_shortName: _shortName,
fullName: fullName,
_fullName: _fullName
});
// Dojo and YUI extend undefined
if (shortName !== undefined) {
Constructor.shortName = shortName;
}
// Make sure our prototype looks nice.
Constructor.prototype.constructor = Constructor;
// Call the class `setup` and `init`
var t = [_super_class].concat(can.makeArray(arguments)),
args = Constructor.setup.apply(Constructor, t);
if (Constructor.init) {
Constructor.init.apply(Constructor, args || t);
}
return Constructor;
}
|
javascript
|
{
"resource": ""
}
|
|
q55450
|
train
|
function() {
for (var cid in madeMap) {
if (madeMap[cid].added) {
delete madeMap[cid].obj._cid;
}
}
madeMap = null;
}
|
javascript
|
{
"resource": ""
}
|
|
q55451
|
train
|
function() {
var computes = this.constructor._computes;
this._computedBindings = {};
for (var i = 0, len = computes.length, prop; i < len; i++) {
prop = computes[i];
// Make the context of the compute the current Map
this[prop] = this[prop].clone(this);
// Keep track of computed properties
this._computedBindings[prop] = {
count: 0
};
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55452
|
train
|
function(ev, attr, how, newVal, oldVal) {
// when a change happens, create the named event.
can.batch.trigger(this, {
type: attr,
batchNum: ev.batchNum
}, [newVal, oldVal]);
if (how === "remove" || how === "add") {
can.batch.trigger(this, {
type: "__keys",
batchNum: ev.batchNum
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55453
|
train
|
function(attr, how, newVal, oldVal) {
can.batch.trigger(this, "change", can.makeArray(arguments));
}
|
javascript
|
{
"resource": ""
}
|
|
q55454
|
train
|
function(callback) {
var data = this.__get();
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
callback(data[prop], prop);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55455
|
train
|
function(prop, current) {
if (prop in this._data) {
// Delete the property from `_data` and the Map
// as long as it isn't part of the Map's prototype.
delete this._data[prop];
if (!(prop in this.constructor.prototype)) {
delete this[prop];
}
// Let others now this property has been removed.
this._triggerChange(prop, "remove", undefined, current);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55456
|
train
|
function(value, prop) {
// If we are getting an object.
if (!(value instanceof can.Map) && can.Map.helpers.canMakeObserve(value)) {
var cached = getMapFromObject(value);
if (cached) {
return cached;
}
if (can.isArray(value)) {
var List = can.List;
return new List(value);
} else {
var Map = this.constructor.Map || can.Map;
return new Map(value);
}
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
|
q55457
|
train
|
function(updater) {
for (var name in readInfo.observed) {
var ob = readInfo.observed[name];
ob.obj.unbind(ob.event, onchanged);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55458
|
train
|
function(newValue, oldValue, batchNum) {
setCached(newValue);
updateOnChange(computed, newValue, oldValue, batchNum);
}
|
javascript
|
{
"resource": ""
}
|
|
q55459
|
train
|
function() {
for (var i = 0, len = computes.length; i < len; i++) {
computes[i].unbind('change', k);
}
computes = null;
}
|
javascript
|
{
"resource": ""
}
|
|
q55460
|
train
|
function(parentValue, nameIndex) {
if (nameIndex > defaultPropertyDepth) {
defaultObserve = currentObserve;
defaultReads = currentReads;
defaultPropertyDepth = nameIndex;
defaultScope = scope;
defaultComputeReadings = can.__clearReading();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55461
|
train
|
function() {
if (!tornDown) {
tornDown = true;
unbind(data);
can.unbind.call(el, 'removed', teardown);
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q55462
|
train
|
function(expr, options) {
var value;
// if it's a function, wrap its value in a compute
// that will only change values from true to false
if (can.isFunction(expr)) {
value = can.compute.truthy(expr)();
} else {
value = !! Mustache.resolve(expr);
}
if (value) {
return options.fn(options.contexts || this);
} else {
return options.inverse(options.contexts || this);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55463
|
train
|
function(expr, options) {
var fn = options.fn;
options.fn = options.inverse;
options.inverse = fn;
return Mustache._helpers['if'].fn.apply(this, arguments);
}
|
javascript
|
{
"resource": ""
}
|
|
q55464
|
train
|
function(expr, options) {
// Check if this is a list or a compute that resolves to a list, and setup
// the incremental live-binding
// First, see what we are dealing with. It's ok to read the compute
// because can.view.text is only temporarily binding to what is going on here.
// Calling can.view.lists prevents anything from listening on that compute.
var resolved = Mustache.resolve(expr),
result = [],
keys,
key,
i;
// When resolved === undefined, the property hasn't been defined yet
// Assume it is intended to be a list
if (can.view.lists && (resolved instanceof can.List || (expr && expr.isComputed && resolved === undefined))) {
return can.view.lists(expr, function(item, index) {
return options.fn(options.scope.add({
"@index": index
})
.add(item));
});
}
expr = resolved;
if ( !! expr && isArrayLike(expr)) {
for (i = 0; i < expr.length; i++) {
result.push(options.fn(options.scope.add({
"@index": i
})
.add(expr[i])));
}
return result.join('');
} else if (isObserveLike(expr)) {
keys = can.Map.keys(expr);
// listen to keys changing so we can livebind lists of attributes.
for (i = 0; i < keys.length; i++) {
key = keys[i];
result.push(options.fn(options.scope.add({
"@key": key
})
.add(expr[key])));
}
return result.join('');
} else if (expr instanceof Object) {
for (key in expr) {
result.push(options.fn(options.scope.add({
"@key": key
})
.add(expr[key])));
}
return result.join('');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55465
|
train
|
function(expr, options) {
var ctx = expr;
expr = Mustache.resolve(expr);
if ( !! expr) {
return options.fn(ctx);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55466
|
train
|
function(id, src) {
return "can.Mustache(function(" + ARG_NAMES + ") { " + new Mustache({
text: src,
name: id
})
.template.out + " })";
}
|
javascript
|
{
"resource": ""
}
|
|
q55467
|
train
|
function(value) {
if (value[0] === "{" && value[value.length - 1] === "}") {
return value.substr(1, value.length - 2);
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
|
q55468
|
train
|
function(ev) {
// The attribute value, representing the name of the method to call (i.e. can-submit="foo" foo is the
// name of the method)
var attr = removeCurly(el.getAttribute(attributeName)),
scopeData = data.scope.read(attr, {
returnObserveMethods: true,
isArgument: true
});
return scopeData.value.call(scopeData.parent, data.scope._context, can.$(this), ev);
}
|
javascript
|
{
"resource": ""
}
|
|
q55469
|
train
|
function() {
// Get an array of the currently selected values
var value = this.get(),
currentValue = this.options.value();
// If the compute is a string, set its value to the joined version of the values array (i.e. "foo;bar")
if (this.isString || typeof currentValue === "string") {
this.isString = true;
this.options.value(value.join(this.delimiter));
}
// If the compute is a can.List, replace its current contents with the new array of values
else if (currentValue instanceof can.List) {
currentValue.attr(value, true);
}
// Otherwise set the value to the array of values selected in the input.
else {
this.options.value(value);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55470
|
train
|
function(ev, newVal) {
scopePropertyUpdating = name;
componentScope.attr(name, newVal);
scopePropertyUpdating = null;
}
|
javascript
|
{
"resource": ""
}
|
|
q55471
|
train
|
function(name) {
var parseName = "parse" + can.capitalize(name);
return function(data) {
// If there's a `parse...` function, use its output.
if (this[parseName]) {
data = this[parseName].apply(this, arguments);
}
// Run our maybe-parsed data through `model` or `models`.
return this[name](data);
};
}
|
javascript
|
{
"resource": ""
}
|
|
q55472
|
train
|
function() {
if (!can.route.currentBinding) {
can.route._call("bind");
can.route.bind("change", onRouteDataChange);
can.route.currentBinding = can.route.defaultBinding;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55473
|
train
|
function() {
var args = can.makeArray(arguments),
prop = args.shift(),
binding = can.route.bindings[can.route.currentBinding || can.route.defaultBinding],
method = binding[prop];
if (method.apply) {
return method.apply(binding, args);
} else {
return method;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55474
|
toIdentifier
|
train
|
function toIdentifier (str) {
return str
.split(' ')
.map(function (token) {
return token.slice(0, 1).toUpperCase() + token.slice(1)
})
.join('')
.replace(/[^ _0-9a-z]/gi, '')
}
|
javascript
|
{
"resource": ""
}
|
q55475
|
runCompile
|
train
|
function runCompile(file, options) {
if (!file) {
throw new PluginError('can-compile', 'Missing file option for can-compile');
}
var templatePaths = [],
latestFile;
options = options || {};
function bufferStream (file, enc, cb) {
// ignore empty files
if (file.isNull()) {
cb();
return;
}
// can't do streams yet
if (file.isStream()) {
this.emit('error', new PluginError('can-compile', 'Streaming not supported for can-compile'));
cb();
return;
}
// set latest file if not already set,
// or if the current file was modified more recently.
if (!latestFile || file.stat && file.stat.mtime > latestFile.stat.mtime) {
latestFile = file;
}
templatePaths.push(file.path);
cb();
}
function endStream(cb) {
var self = this;
// no files passed in, no file goes out
if (!latestFile || !templatePaths.length) {
cb();
return;
}
compile(templatePaths, options, function (err, result) {
if (err) {
self.emit('error', new PluginError('can-compile', err));
return cb(err);
}
var joinedFile;
// if file opt was a file path
// clone everything from the latest file
if (typeof file === 'string') {
joinedFile = latestFile.clone({ contents: false });
joinedFile.path = path.join(latestFile.base, file);
} else {
joinedFile = new File(file);
}
joinedFile.contents = new Buffer(result);
self.push(joinedFile);
cb();
});
}
return through.obj(bufferStream, endStream);
}
|
javascript
|
{
"resource": ""
}
|
q55476
|
oxdSocketRequest
|
train
|
function oxdSocketRequest(port, host, params, command, callback) {
// OXD data
let data = {
command,
params
};
// Create socket object
const client = new net.Socket();
// Initiate a connection on a given socket.
client.connect(port, host, () => {
data = JSON.stringify(data);
console.log('Connected');
try {
if (data.length > 0 && data.length <= 100) {
console.log(`Send data : 00${data.length + data}`);
client.write(`00${data.length + data}`);
} else if (data.length > 100 && data.length < 1000) {
console.log(`Send data : 0${data.length + data}`);
client.write(`0${data.length + data}`);
}
} catch (err) {
console.log('Send data error:', err);
}
});
// Emitted when data is received
client.on('data', (req) => {
data = req.toString();
console.log('Response : ', data);
callback(null, JSON.parse(data.substring(4, data.length)));
client.end(); // kill client after server's response
});
// Emitted when an error occurs. The 'close' event will be called directly following this event.
client.on('error', (err) => {
console.log('Error: ', err);
callback(err, null);
client.end(); // kill client after server's response
});
// Emitted when the server closes.
client.on('close', () => {
console.log('Connection closed');
});
}
|
javascript
|
{
"resource": ""
}
|
q55477
|
showTableData
|
train
|
function showTableData() {
connection.runSql('select * from Student').then(function (students) {
var HtmlString = "";
students.forEach(function (student) {
HtmlString += "<tr ItemId=" + student.Id + "><td>" +
student.Name + "</td><td>" +
student.Gender + "</td><td>" +
student.Country + "</td><td>" +
student.City + "</td><td>" +
"<a href='#' class='edit'>Edit</a></td>" +
"<td><a href='#' class='delete''>Delete</a></td>";
})
$('#tblGrid tbody').html(HtmlString);
}).catch(function (error) {
console.log(error);
});
}
|
javascript
|
{
"resource": ""
}
|
q55478
|
Client
|
train
|
function Client (options, cb) {
if (typeof options == 'string')
options = url.parse(options)
var req;
if (options.protocol == "https:")
req = https.request(options);
else
req = http.request(options);
// add the "Icy-MetaData" header
req.setHeader('Icy-MetaData', '1');
if ('function' == typeof cb) {
req.once('icyResponse', cb);
}
req.once('response', icyOnResponse);
req.once('socket', icyOnSocket);
return req;
}
|
javascript
|
{
"resource": ""
}
|
q55479
|
icyOnResponse
|
train
|
function icyOnResponse (res) {
debug('request "response" event');
var s = res;
var metaint = res.headers['icy-metaint'];
if (metaint) {
debug('got metaint: %d', metaint);
s = new Reader(metaint);
res.pipe(s);
s.res = res;
Object.keys(res).forEach(function (k) {
if ('_' === k[0]) return;
debug('proxying %j', k);
proxy(s, k);
});
}
if (res.connection._wasIcy) {
s.httpVersion = 'ICY';
}
this.emit('icyResponse', s);
}
|
javascript
|
{
"resource": ""
}
|
q55480
|
proxy
|
train
|
function proxy (stream, key) {
if (key in stream) {
debug('not proxying prop "%s" because it already exists on target stream', key);
return;
}
function get () {
return stream.res[key];
}
function set (v) {
return stream.res[key] = v;
}
Object.defineProperty(stream, key, {
configurable: true,
enumerable: true,
get: get,
set: set
});
}
|
javascript
|
{
"resource": ""
}
|
q55481
|
stringify
|
train
|
function stringify (obj) {
var s = [];
Object.keys(obj).forEach(function (key) {
s.push(key);
s.push('=\'');
s.push(obj[key]);
s.push('\';');
});
return s.join('');
}
|
javascript
|
{
"resource": ""
}
|
q55482
|
onMetadata
|
train
|
function onMetadata (metadata) {
metadata = icy.parse(metadata);
console.error('METADATA EVENT:');
console.error(metadata);
}
|
javascript
|
{
"resource": ""
}
|
q55483
|
preprocessor
|
train
|
function preprocessor (socket) {
debug('setting up "data" preprocessor');
function ondata (chunk) {
// TODO: don't be lazy, buffer if needed...
assert(chunk.length >= 3, 'buffer too small! ' + chunk.length);
if (/icy/i.test(chunk.slice(0, 3))) {
debug('got ICY response!');
var b = new Buffer(chunk.length + HTTP10.length - 'icy'.length);
var i = 0;
i += HTTP10.copy(b);
i += chunk.copy(b, i, 3);
assert.equal(i, b.length);
chunk = b;
socket._wasIcy = true;
} else {
socket._wasIcy = false;
}
return chunk;
}
var listeners;
function icyOnData (buf) {
var chunk = ondata(buf);
// clean up, and re-emit "data" event
socket.removeListener('data', icyOnData);
listeners.forEach(function (listener) {
socket.on('data', listener);
});
listeners = null;
socket.emit('data', chunk);
}
if ('function' == typeof socket.ondata) {
// node < v0.11.3, the `ondata` function is set on the socket
var origOnData = socket.ondata;
socket.ondata = function (buf, start, length) {
var chunk = ondata(buf.slice(start, length));
// now clean up and inject the modified `chunk`
socket.ondata = origOnData;
origOnData = null;
socket.ondata(chunk, 0, chunk.length);
};
} else if (socket.listeners('data').length > 0) {
// node >= v0.11.3, the "data" event is listened for directly
// add our own "data" listener, and remove all the old ones
listeners = socket.listeners('data');
socket.removeAllListeners('data');
socket.on('data', icyOnData);
} else {
// never?
throw new Error('should not happen...');
}
}
|
javascript
|
{
"resource": ""
}
|
q55484
|
writeLocationFile
|
train
|
function writeLocationFile(location) {
log.info('Writing location.js file');
if (process.platform === 'win32') {
location = location.replace(/\\/g, '\\\\');
}
fs.writeFileSync(path.join(libPath, 'location.js'),
'module.exports.location = \'' + location + '\';');
}
|
javascript
|
{
"resource": ""
}
|
q55485
|
findSuitableTempDirectory
|
train
|
function findSuitableTempDirectory(npmConf) {
const now = Date.now();
const candidateTmpDirs = [
process.env.TMPDIR || process.env.TEMP || npmConf.get('tmp'),
path.join(process.cwd(), 'tmp',
'/tmp')
];
for (let i = 0; i < candidateTmpDirs.length; i++) {
const candidatePath = path.join(candidateTmpDirs[i], 'galenframework');
try {
fs.mkdirsSync(candidatePath, '0777');
// Make double sure we have 0777 permissions; some operating systems
// default umask does not allow write by default.
fs.chmodSync(candidatePath, '0777');
const testFile = path.join(candidatePath, now + '.tmp');
fs.writeFileSync(testFile, 'test');
fs.unlinkSync(testFile);
return candidatePath;
} catch (e) {
log.info(candidatePath, 'is not writable:', e.message);
}
}
log.error('Can not find a writable tmp directory.');
exit(1);
}
|
javascript
|
{
"resource": ""
}
|
q55486
|
getRequestOptions
|
train
|
function getRequestOptions(conf) {
const strictSSL = conf.get('strict-ssl');
let options = {
uri: downloadUrl,
encoding: null, // Get response as a buffer
followRedirect: true, // The default download path redirects to a CDN URL.
headers: {},
strictSSL: strictSSL
};
let proxyUrl = conf.get('https-proxy') || conf.get('http-proxy') || conf.get('proxy');
if (proxyUrl) {
// Print using proxy
let proxy = url.parse(proxyUrl);
if (proxy.auth) {
// Mask password
proxy.auth = proxy.auth.replace(/:.*$/, ':******');
}
log.info('Using proxy ' + url.format(proxy));
// Enable proxy
options.proxy = proxyUrl;
// If going through proxy, use the user-agent string from the npm config
options.headers['User-Agent'] = conf.get('user-agent');
}
// Use certificate authority settings from npm
const ca = conf.get('ca');
if (ca) {
log.info('Using npmconf ca');
options.ca = ca;
}
return options;
}
|
javascript
|
{
"resource": ""
}
|
q55487
|
requestBinary
|
train
|
function requestBinary(requestOptions, filePath) {
const deferred = kew.defer();
const writePath = filePath + '-download-' + Date.now();
log.info('Receiving...');
let bar = null;
requestProgress(request(requestOptions, (error, response, body) => {
log.info('');
if (!error && response.statusCode === 200) {
fs.writeFileSync(writePath, body);
log.info('Received ' + Math.floor(body.length / 1024) + 'K total.');
fs.renameSync(writePath, filePath);
deferred.resolve({
requestOptions: requestOptions,
downloadedFile: filePath
});
} else if (response) {
log.error('Error requesting archive.\n' +
'Status: ' + response.statusCode + '\n' +
'Request options: ' + JSON.stringify(requestOptions, null, 2) + '\n' +
'Response headers: ' + JSON.stringify(response.headers, null, 2) + '\n' +
'Make sure your network and proxy settings are correct.\n\n');
exit(1);
} else if (error && error.stack && error.stack.indexOf('SELF_SIGNED_CERT_IN_CHAIN') != -1) {
log.error('Error making request.');
exit(1);
} else if (error) {
log.error('Error making request.\n' + error.stack + '\n\n' +
'Please report this full log at https://github.com/hypery2k/galenframework-cli/issues');
exit(1);
} else {
log.error('Something unexpected happened, please report this full ' +
'log at https://github.com/hypery2k/galenframework-cli/issues');
exit(1);
}
})).on('progress', (state) => {
if (!bar) {
bar = new Progress(' [:bar] :percent :etas', { total: state.total, width: 40 });
}
bar.curr = state.received;
bar.tick(0);
});
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
q55488
|
extractDownload
|
train
|
function extractDownload(filePath, requestOptions, retry) {
const deferred = kew.defer();
// extract to a unique directory in case multiple processes are
// installing and extracting at once
const extractedPath = filePath + '-extract-' + Date.now();
let options = { cwd: extractedPath };
fs.mkdirsSync(extractedPath, '0777');
// Make double sure we have 0777 permissions; some operating systems
// default umask does not allow write by default.
fs.chmodSync(extractedPath, '0777');
if (filePath.substr(-4) === '.zip') {
log.info('Extracting zip contents');
try {
let zip = new AdmZip(filePath);
zip.extractAllTo(extractedPath, true);
deferred.resolve(extractedPath);
} catch (err) {
log.error('Error extracting zip');
deferred.reject(err);
}
} else {
log.info('Extracting tar contents (via spawned process)');
cp.execFile('tar', ['jxf', filePath], options, function (err) {
if (err) {
if (!retry) {
log.info('Error during extracting. Trying to download again.');
fs.unlinkSync(filePath);
return requestBinary(requestOptions, filePath).then(function (downloadedFile) {
return extractDownload(downloadedFile, requestOptions, true);
});
} else {
deferred.reject(err);
log.error('Error extracting archive');
}
} else {
deferred.resolve(extractedPath);
}
});
}
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
q55489
|
copyIntoPlace
|
train
|
function copyIntoPlace(extractedPath, targetPath) {
log.info('Removing', targetPath);
return kew.nfcall(fs.remove, targetPath).then(function () {
// Look for the extracted directory, so we can rename it.
const files = fs.readdirSync(extractedPath);
for (let i = 0; i < files.length; i++) {
const file = path.join(extractedPath, files[i]);
if (fs.statSync(file).isDirectory() && file.indexOf(helper.version) !== -1) {
log.info('Copying extracted folder', file, '->', targetPath);
return kew.nfcall(fs.move, file, targetPath);
}
}
log.info('Could not find extracted file', files);
throw new Error('Could not find extracted file');
});
}
|
javascript
|
{
"resource": ""
}
|
q55490
|
getPathVariableName
|
train
|
function getPathVariableName() {
// windows calls it's path 'Path' usually, but this is not guaranteed.
if (process.platform === 'win32') {
for (const key of Object.keys(process.env))
if (key.match(/^PATH$/i))
return key;
return 'Path';
}
return "PATH";
}
|
javascript
|
{
"resource": ""
}
|
q55491
|
put
|
train
|
function put(key, value, testCacheEnabled) {
const cacheEnabled = testCacheEnabled || CACHE_ENABLED;
return postgres.put(key, value)
.then((res) => {
// persist to cache only if cache is set up/enabled, return postgres result regardless
if (cacheEnabled) {
return redis.put(key, value).then(() => res);
}
return res;
});
}
|
javascript
|
{
"resource": ""
}
|
q55492
|
get
|
train
|
function get(key) {
return redis.get(key)
.then(data => {
if (isUri(key)) return data;
return JSON.parse(data); // Parse non-uri data to match Postgres
})
.catch(() => postgres.get(key));
}
|
javascript
|
{
"resource": ""
}
|
q55493
|
batch
|
train
|
function batch(ops, testCacheEnabled) {
const cacheEnabled = testCacheEnabled || CACHE_ENABLED;
return postgres.batch(ops)
.then((res) => {
if (cacheEnabled) {
return redis.batch(ops).then(() => res);
}
return res;
});
}
|
javascript
|
{
"resource": ""
}
|
q55494
|
createDBIfNotExists
|
train
|
function createDBIfNotExists() {
const tmpClient = knexLib({
client: 'pg',
connection: {
host: POSTGRES_HOST,
user: POSTGRES_USER,
password: POSTGRES_PASSWORD,
database: 'postgres',
port: POSTGRES_PORT
},
pool: { min: CONNECTION_POOL_MIN, max: CONNECTION_POOL_MAX }
});
// https://github.com/clay/amphora-storage-postgres/pull/7/files/16d3429767943a593ad9667b0d471fefc15088d3#diff-6a1e11a6146d3a5a01f955a44a2ac07a
return tmpClient.raw('CREATE DATABASE ??', [POSTGRES_DB])
.then(() => tmpClient.destroy())
.then(connect);
}
|
javascript
|
{
"resource": ""
}
|
q55495
|
connect
|
train
|
function connect() {
log('debug', `Connecting to Postgres at ${POSTGRES_HOST}:${POSTGRES_PORT}`);
knex = knexLib({
client: 'pg',
connection: {
host: POSTGRES_HOST,
user: POSTGRES_USER,
password: POSTGRES_PASSWORD,
database: POSTGRES_DB,
port: POSTGRES_PORT
},
pool: { min: CONNECTION_POOL_MIN, max: CONNECTION_POOL_MAX }
});
// TODO: improve error catch! https://github.com/clay/amphora-storage-postgres/pull/7/files/16d3429767943a593ad9667b0d471fefc15088d3#diff-6a1e11a6146d3a5a01f955a44a2ac07a
return knex.table('information_schema.tables').first()
.catch(createDBIfNotExists);
}
|
javascript
|
{
"resource": ""
}
|
q55496
|
get
|
train
|
function get(key) {
const dataProp = 'data';
return baseQuery(key)
.select(dataProp)
.where('id', key)
.then(pullValFromRows(key, dataProp));
}
|
javascript
|
{
"resource": ""
}
|
q55497
|
put
|
train
|
function put(key, value) {
const { schema, table } = findSchemaAndTable(key),
map = columnToValueMap('id', key); // create the value map
// add data to the map
columnToValueMap('data', wrapInObject(key, parseOrNot(value)), map);
let url;
if (isUri(key)) {
url = decode(key.split('/_uris/').pop());
// add url column to map if we're PUTting a uri
columnToValueMap('url', url, map);
}
return onConflictPut(map, schema, table)
.then(() => map.data);
}
|
javascript
|
{
"resource": ""
}
|
q55498
|
patch
|
train
|
function patch(prop) {
return (key, value) => {
const { schema, table } = findSchemaAndTable(key);
return raw('UPDATE ?? SET ?? = ?? || ? WHERE id = ?', [`${schema ? `${schema}.` : ''}${table}`, prop, prop, JSON.stringify(value), key]);
};
}
|
javascript
|
{
"resource": ""
}
|
q55499
|
createReadStream
|
train
|
function createReadStream(options) {
const { prefix, values, keys } = options,
transform = TransformStream(options),
selects = [];
if (keys) selects.push('id');
if (values) selects.push('data');
baseQuery(prefix)
.select(...selects)
.where('id', 'like', `${prefix}%`)
.pipe(transform);
return transform;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.