id int32 0 58k | repo stringlengths 5 67 | path stringlengths 4 116 | func_name stringlengths 0 58 | original_string stringlengths 52 373k | language stringclasses 1 value | code stringlengths 52 373k | code_tokens list | docstring stringlengths 4 11.8k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 86 226 |
|---|---|---|---|---|---|---|---|---|---|---|---|
28,800 | turf-junkyard/turf-isolines | conrec.js | Conrec | function Conrec(drawContour) {
if (!drawContour) {
var c = this;
c.contours = {};
/**
* drawContour - interface for implementing the user supplied method to
* render the countours.
*
* Draws a line between the start and end coordinates.
*
* @param startX - start coordinate for X
* @param startY - start coordinate for Y
* @param endX - end coordinate for X
* @param endY - end coordinate for Y
* @param contourLevel - Contour level for line.
*/
this.drawContour = function(startX, startY, endX, endY, contourLevel, k) {
var cb = c.contours[k];
if (!cb) {
cb = c.contours[k] = new ContourBuilder(contourLevel);
}
cb.addSegment({x: startX, y: startY}, {x: endX, y: endY});
}
this.contourList = function() {
var l = [];
var a = c.contours;
for (var k in a) {
var s = a[k].s;
var level = a[k].level;
while (s) {
var h = s.head;
var l2 = [];
l2.level = level;
l2.k = k;
while (h && h.p) {
l2.push(h.p);
h = h.next;
}
l.push(l2);
s = s.next;
}
}
l.sort(function(a, b) { return a.k - b.k });
return l;
}
} else {
this.drawContour = drawContour;
}
this.h = new Array(5);
this.sh = new Array(5);
this.xh = new Array(5);
this.yh = new Array(5);
} | javascript | function Conrec(drawContour) {
if (!drawContour) {
var c = this;
c.contours = {};
/**
* drawContour - interface for implementing the user supplied method to
* render the countours.
*
* Draws a line between the start and end coordinates.
*
* @param startX - start coordinate for X
* @param startY - start coordinate for Y
* @param endX - end coordinate for X
* @param endY - end coordinate for Y
* @param contourLevel - Contour level for line.
*/
this.drawContour = function(startX, startY, endX, endY, contourLevel, k) {
var cb = c.contours[k];
if (!cb) {
cb = c.contours[k] = new ContourBuilder(contourLevel);
}
cb.addSegment({x: startX, y: startY}, {x: endX, y: endY});
}
this.contourList = function() {
var l = [];
var a = c.contours;
for (var k in a) {
var s = a[k].s;
var level = a[k].level;
while (s) {
var h = s.head;
var l2 = [];
l2.level = level;
l2.k = k;
while (h && h.p) {
l2.push(h.p);
h = h.next;
}
l.push(l2);
s = s.next;
}
}
l.sort(function(a, b) { return a.k - b.k });
return l;
}
} else {
this.drawContour = drawContour;
}
this.h = new Array(5);
this.sh = new Array(5);
this.xh = new Array(5);
this.yh = new Array(5);
} | [
"function",
"Conrec",
"(",
"drawContour",
")",
"{",
"if",
"(",
"!",
"drawContour",
")",
"{",
"var",
"c",
"=",
"this",
";",
"c",
".",
"contours",
"=",
"{",
"}",
";",
"/**\n * drawContour - interface for implementing the user supplied method to\n * render th... | Implements CONREC.
@param {function} drawContour function for drawing contour. Defaults to a
custom "contour builder", which populates the
contours property. | [
"Implements",
"CONREC",
"."
] | 379514fea9bbd458dd4e5beb32d5051796c2026f | https://github.com/turf-junkyard/turf-isolines/blob/379514fea9bbd458dd4e5beb32d5051796c2026f/conrec.js#L254-L306 |
28,801 | c9/smith.io | server-plugin/plugin.js | failFirstRequest | function failFirstRequest(server) {
var listeners = server.listeners("request"),
existingListeners = [];
for (var i = 0, l = listeners.length; i < l; i++) {
existingListeners[i] = listeners[i];
}
server.removeAllListeners("request");
server.on("request", function (req, res) {
var fireExisting = true;
if (/^\/transport\/server\//.test(req.url)) {
fireExisting = onTransportRequest(req, res);
}
if (fireExisting) {
for (var i = 0, l = existingListeners.length; i < l; i++) {
existingListeners[i].call(server, req, res);
}
}
});
var count = 0;
function onTransportRequest(req, res) {
count += 1;
console.log("REQUEST", req.url, count);
if (count === 1) {
console.log(" Fail request");
res.end("<An unparsable response>");
return false;
}
return true;
}
} | javascript | function failFirstRequest(server) {
var listeners = server.listeners("request"),
existingListeners = [];
for (var i = 0, l = listeners.length; i < l; i++) {
existingListeners[i] = listeners[i];
}
server.removeAllListeners("request");
server.on("request", function (req, res) {
var fireExisting = true;
if (/^\/transport\/server\//.test(req.url)) {
fireExisting = onTransportRequest(req, res);
}
if (fireExisting) {
for (var i = 0, l = existingListeners.length; i < l; i++) {
existingListeners[i].call(server, req, res);
}
}
});
var count = 0;
function onTransportRequest(req, res) {
count += 1;
console.log("REQUEST", req.url, count);
if (count === 1) {
console.log(" Fail request");
res.end("<An unparsable response>");
return false;
}
return true;
}
} | [
"function",
"failFirstRequest",
"(",
"server",
")",
"{",
"var",
"listeners",
"=",
"server",
".",
"listeners",
"(",
"\"request\"",
")",
",",
"existingListeners",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"listeners",
".",
"len... | Used to test re-connect when connect request fails. | [
"Used",
"to",
"test",
"re",
"-",
"connect",
"when",
"connect",
"request",
"fails",
"."
] | 282ed97e043732ef0785318d597172e57931c55c | https://github.com/c9/smith.io/blob/282ed97e043732ef0785318d597172e57931c55c/server-plugin/plugin.js#L213-L243 |
28,802 | Instrumental/statsd-instrumental-backend | lib/instrumental.js | instrumental_send | function instrumental_send(payload) {
var state = "cold";
var tlsOptionsVariation = selectTlsOptionsVariation();
var client = instrumental_connection(host, port, tlsOptionsVariation, function(_client){
state = "connected";
var cleanString = function(value) {
return String(value).replace(/\s+/g, "_");
}
// Write the authentication header
_client.write(
"hello version node/statsd-instrumental-backend/" + cleanString(package.version) +
" hostname " + cleanString(hostname) +
" pid " + cleanString(process.pid) +
" runtime " + cleanString("node/" + process.versions.node) +
" platform " + cleanString(process.platform + "-" + process.arch) + "\n" +
"authenticate " + key + "\n"
);
});
// We need to handle the timeout. I think we should only care about read
// timeouts. That is we write out data, if we don't hear back in timeout
// seconds then the data probably hasn't reached the server.
client.setTimeout(timeout, function() {
// ZOMG FAILED WRITING WE ARE BAD AT COMPUTER SCIENCE
if(state == "connected") {
// We're waiting to hear back from the server and it has timed out. It's
// unlikely that the server will suddenly wake up and send us our data so
// lets disconnect and go shopping.
client.end();
}
});
// HOW WE HANDLE ERRORS. We should probably reconnect, maybe retry.
client.addListener("error", function(exception){
if(debug) {
log("Client error:", exception);
}
instrumentalStats.last_exception = Math.round(new Date().getTime() / 1000);
});
// What do we do when instrumental talks to us
var totalBuffer = "";
client.on("data", function(buffer) {
totalBuffer = totalBuffer + buffer;
if(debug) {
log("Received:", buffer);
}
// Authorization success
if(totalBuffer == "ok\nok\n") {
error = false;
if(debug) {
log("Sending:", payload.join("\n"));
}
client.end(payload.join("\n") + "\n", function() {
tlsOptionsVariation.lastSuccessAt = new Date();
if (debug) log("payload sent, tlsOptionsVariation: ", tlsOptionsVariation);
state = "sent";
});
instrumentalStats.last_flush = Math.round(new Date().getTime() / 1000);
// Authorization failure
} else if(totalBuffer.length >= "ok\nok\n".length) {
// TODO: Actually do something with this
error = true;
instrumentalStats.last_exception = Math.round(new Date().getTime() / 1000);
}
});
} | javascript | function instrumental_send(payload) {
var state = "cold";
var tlsOptionsVariation = selectTlsOptionsVariation();
var client = instrumental_connection(host, port, tlsOptionsVariation, function(_client){
state = "connected";
var cleanString = function(value) {
return String(value).replace(/\s+/g, "_");
}
// Write the authentication header
_client.write(
"hello version node/statsd-instrumental-backend/" + cleanString(package.version) +
" hostname " + cleanString(hostname) +
" pid " + cleanString(process.pid) +
" runtime " + cleanString("node/" + process.versions.node) +
" platform " + cleanString(process.platform + "-" + process.arch) + "\n" +
"authenticate " + key + "\n"
);
});
// We need to handle the timeout. I think we should only care about read
// timeouts. That is we write out data, if we don't hear back in timeout
// seconds then the data probably hasn't reached the server.
client.setTimeout(timeout, function() {
// ZOMG FAILED WRITING WE ARE BAD AT COMPUTER SCIENCE
if(state == "connected") {
// We're waiting to hear back from the server and it has timed out. It's
// unlikely that the server will suddenly wake up and send us our data so
// lets disconnect and go shopping.
client.end();
}
});
// HOW WE HANDLE ERRORS. We should probably reconnect, maybe retry.
client.addListener("error", function(exception){
if(debug) {
log("Client error:", exception);
}
instrumentalStats.last_exception = Math.round(new Date().getTime() / 1000);
});
// What do we do when instrumental talks to us
var totalBuffer = "";
client.on("data", function(buffer) {
totalBuffer = totalBuffer + buffer;
if(debug) {
log("Received:", buffer);
}
// Authorization success
if(totalBuffer == "ok\nok\n") {
error = false;
if(debug) {
log("Sending:", payload.join("\n"));
}
client.end(payload.join("\n") + "\n", function() {
tlsOptionsVariation.lastSuccessAt = new Date();
if (debug) log("payload sent, tlsOptionsVariation: ", tlsOptionsVariation);
state = "sent";
});
instrumentalStats.last_flush = Math.round(new Date().getTime() / 1000);
// Authorization failure
} else if(totalBuffer.length >= "ok\nok\n".length) {
// TODO: Actually do something with this
error = true;
instrumentalStats.last_exception = Math.round(new Date().getTime() / 1000);
}
});
} | [
"function",
"instrumental_send",
"(",
"payload",
")",
"{",
"var",
"state",
"=",
"\"cold\"",
";",
"var",
"tlsOptionsVariation",
"=",
"selectTlsOptionsVariation",
"(",
")",
";",
"var",
"client",
"=",
"instrumental_connection",
"(",
"host",
",",
"port",
",",
"tlsOp... | Push data to instrumental | [
"Push",
"data",
"to",
"instrumental"
] | e7e32ce75cd770114589447a2caf72eb673b8327 | https://github.com/Instrumental/statsd-instrumental-backend/blob/e7e32ce75cd770114589447a2caf72eb673b8327/lib/instrumental.js#L176-L252 |
28,803 | rekit/rekit-core | plugins/rekit-react/app.js | getRoutes | function getRoutes(feature) {
const targetPath = `src/features/${feature}/route.js`; //utils.mapFeatureFile(feature, 'route.js');
if (vio.fileNotExists(targetPath)) return [];
const theAst = ast.getAst(targetPath);
const arr = [];
let rootPath = '';
let indexRoute = null;
traverse(theAst, {
ObjectExpression(path) {
const node = path.node;
const props = node.properties;
if (!props.length) return;
const obj = {};
props.forEach(p => {
if (_.has(p, 'key.name') && !p.computed) {
obj[p.key.name] = p;
}
});
if (obj.path && obj.component) {
// in a route config, if an object expression has both 'path' and 'component' property, then it's a route config
arr.push({
path: _.get(obj.path, 'value.value'), // only string literal supported
component: _.get(obj.component, 'value.name'), // only identifier supported
isIndex: !!obj.isIndex && _.get(obj.isIndex, 'value.value'), // suppose to be boolean
node: {
start: node.start,
end: node.end,
},
});
}
if (obj.isIndex && obj.component && !indexRoute) {
// only find the first index route
indexRoute = {
component: _.get(obj.component, 'value.name'),
};
}
if (obj.path && obj.childRoutes && !rootPath) {
rootPath = _.get(obj.path, 'value.value');
if (!rootPath) rootPath = '$none'; // only find the first rootPath
}
},
});
const prjRootPath = getRootRoutePath();
if (rootPath === '$none') rootPath = prjRootPath;
else if (!/^\//.test(rootPath)) rootPath = prjRootPath + '/' + rootPath;
rootPath = rootPath.replace(/\/+/, '/');
arr.forEach(item => {
if (!/^\//.test(item.path)) {
item.path = (rootPath + '/' + item.path).replace(/\/+/, '/');
}
});
if (indexRoute) {
indexRoute.path = rootPath;
arr.unshift(indexRoute);
}
return arr;
} | javascript | function getRoutes(feature) {
const targetPath = `src/features/${feature}/route.js`; //utils.mapFeatureFile(feature, 'route.js');
if (vio.fileNotExists(targetPath)) return [];
const theAst = ast.getAst(targetPath);
const arr = [];
let rootPath = '';
let indexRoute = null;
traverse(theAst, {
ObjectExpression(path) {
const node = path.node;
const props = node.properties;
if (!props.length) return;
const obj = {};
props.forEach(p => {
if (_.has(p, 'key.name') && !p.computed) {
obj[p.key.name] = p;
}
});
if (obj.path && obj.component) {
// in a route config, if an object expression has both 'path' and 'component' property, then it's a route config
arr.push({
path: _.get(obj.path, 'value.value'), // only string literal supported
component: _.get(obj.component, 'value.name'), // only identifier supported
isIndex: !!obj.isIndex && _.get(obj.isIndex, 'value.value'), // suppose to be boolean
node: {
start: node.start,
end: node.end,
},
});
}
if (obj.isIndex && obj.component && !indexRoute) {
// only find the first index route
indexRoute = {
component: _.get(obj.component, 'value.name'),
};
}
if (obj.path && obj.childRoutes && !rootPath) {
rootPath = _.get(obj.path, 'value.value');
if (!rootPath) rootPath = '$none'; // only find the first rootPath
}
},
});
const prjRootPath = getRootRoutePath();
if (rootPath === '$none') rootPath = prjRootPath;
else if (!/^\//.test(rootPath)) rootPath = prjRootPath + '/' + rootPath;
rootPath = rootPath.replace(/\/+/, '/');
arr.forEach(item => {
if (!/^\//.test(item.path)) {
item.path = (rootPath + '/' + item.path).replace(/\/+/, '/');
}
});
if (indexRoute) {
indexRoute.path = rootPath;
arr.unshift(indexRoute);
}
return arr;
} | [
"function",
"getRoutes",
"(",
"feature",
")",
"{",
"const",
"targetPath",
"=",
"`",
"${",
"feature",
"}",
"`",
";",
"//utils.mapFeatureFile(feature, 'route.js');",
"if",
"(",
"vio",
".",
"fileNotExists",
"(",
"targetPath",
")",
")",
"return",
"[",
"]",
";",
... | Get route rules defined in a feature.
@param {string} feature - The feature name. | [
"Get",
"route",
"rules",
"defined",
"in",
"a",
"feature",
"."
] | e98ab59da85a517717e1ff4e7c724d4c917a45b8 | https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/plugins/rekit-react/app.js#L194-L251 |
28,804 | jhudson8/react-backbone | react-backbone.js | getKey | function getKey(context) {
if (context.getModelKey) {
return context.getModelKey();
}
return context.props.name || context.props.key || context.props.ref;
} | javascript | function getKey(context) {
if (context.getModelKey) {
return context.getModelKey();
}
return context.props.name || context.props.key || context.props.ref;
} | [
"function",
"getKey",
"(",
"context",
")",
"{",
"if",
"(",
"context",
".",
"getModelKey",
")",
"{",
"return",
"context",
".",
"getModelKey",
"(",
")",
";",
"}",
"return",
"context",
".",
"props",
".",
"name",
"||",
"context",
".",
"props",
".",
"key",
... | Return a model attribute key used for attribute specific operations | [
"Return",
"a",
"model",
"attribute",
"key",
"used",
"for",
"attribute",
"specific",
"operations"
] | d9064510ae73f915444a11ec1100b53614bef177 | https://github.com/jhudson8/react-backbone/blob/d9064510ae73f915444a11ec1100b53614bef177/react-backbone.js#L131-L136 |
28,805 | jhudson8/react-backbone | react-backbone.js | modelOrCollectionOnOrOnce | function modelOrCollectionOnOrOnce(modelType, type, args, _this, _modelOrCollection) {
var modelEvents = getModelAndCollectionEvents(modelType, _this);
var ev = args[0];
var cb = args[1];
var ctx = args[2];
modelEvents[ev] = {
type: type,
ev: ev,
cb: cb,
ctx: ctx
};
function _on(modelOrCollection) {
_this[type === 'on' ? 'listenTo' : 'listenToOnce'](modelOrCollection, ev, cb, ctx);
}
if (modelEvents.__bound) {
if (_modelOrCollection) {
_on(_modelOrCollection);
} else {
getModelOrCollections(modelType, _this, _on);
}
}
} | javascript | function modelOrCollectionOnOrOnce(modelType, type, args, _this, _modelOrCollection) {
var modelEvents = getModelAndCollectionEvents(modelType, _this);
var ev = args[0];
var cb = args[1];
var ctx = args[2];
modelEvents[ev] = {
type: type,
ev: ev,
cb: cb,
ctx: ctx
};
function _on(modelOrCollection) {
_this[type === 'on' ? 'listenTo' : 'listenToOnce'](modelOrCollection, ev, cb, ctx);
}
if (modelEvents.__bound) {
if (_modelOrCollection) {
_on(_modelOrCollection);
} else {
getModelOrCollections(modelType, _this, _on);
}
}
} | [
"function",
"modelOrCollectionOnOrOnce",
"(",
"modelType",
",",
"type",
",",
"args",
",",
"_this",
",",
"_modelOrCollection",
")",
"{",
"var",
"modelEvents",
"=",
"getModelAndCollectionEvents",
"(",
"modelType",
",",
"_this",
")",
";",
"var",
"ev",
"=",
"args",
... | Provide modelOn and modelOnce argument with proxied arguments
arguments are event, callback, context | [
"Provide",
"modelOn",
"and",
"modelOnce",
"argument",
"with",
"proxied",
"arguments",
"arguments",
"are",
"event",
"callback",
"context"
] | d9064510ae73f915444a11ec1100b53614bef177 | https://github.com/jhudson8/react-backbone/blob/d9064510ae73f915444a11ec1100b53614bef177/react-backbone.js#L214-L236 |
28,806 | jhudson8/react-backbone | react-backbone.js | getModelAndCollectionEvents | function getModelAndCollectionEvents(type, context) {
var key = '__' + type + CAP_EVENTS,
modelEvents = getState(key, context);
if (!modelEvents) {
modelEvents = {};
var stateVar = {};
stateVar[key] = modelEvents;
setState(stateVar, context, false);
}
return modelEvents;
} | javascript | function getModelAndCollectionEvents(type, context) {
var key = '__' + type + CAP_EVENTS,
modelEvents = getState(key, context);
if (!modelEvents) {
modelEvents = {};
var stateVar = {};
stateVar[key] = modelEvents;
setState(stateVar, context, false);
}
return modelEvents;
} | [
"function",
"getModelAndCollectionEvents",
"(",
"type",
",",
"context",
")",
"{",
"var",
"key",
"=",
"'__'",
"+",
"type",
"+",
"CAP_EVENTS",
",",
"modelEvents",
"=",
"getState",
"(",
"key",
",",
"context",
")",
";",
"if",
"(",
"!",
"modelEvents",
")",
"{... | Return all bound model events | [
"Return",
"all",
"bound",
"model",
"events"
] | d9064510ae73f915444a11ec1100b53614bef177 | https://github.com/jhudson8/react-backbone/blob/d9064510ae73f915444a11ec1100b53614bef177/react-backbone.js#L282-L292 |
28,807 | jhudson8/react-backbone | react-backbone.js | pushLoadingState | function pushLoadingState(xhrEvent, stateName, modelOrCollection, context, force) {
var currentLoads = getState(stateName, context),
currentlyLoading = currentLoads && currentLoads.length;
if (!currentLoads) {
currentLoads = [];
}
if (_.isArray(currentLoads)) {
if (_.indexOf(currentLoads, xhrEvent) >= 0) {
if (!force) {
return;
}
} else {
currentLoads.push(xhrEvent);
}
if (!currentlyLoading) {
var toSet = {};
toSet[stateName] = currentLoads;
setState(toSet, context);
}
xhrEvent.on('complete', function() {
popLoadingState(xhrEvent, stateName, modelOrCollection, context);
});
}
} | javascript | function pushLoadingState(xhrEvent, stateName, modelOrCollection, context, force) {
var currentLoads = getState(stateName, context),
currentlyLoading = currentLoads && currentLoads.length;
if (!currentLoads) {
currentLoads = [];
}
if (_.isArray(currentLoads)) {
if (_.indexOf(currentLoads, xhrEvent) >= 0) {
if (!force) {
return;
}
} else {
currentLoads.push(xhrEvent);
}
if (!currentlyLoading) {
var toSet = {};
toSet[stateName] = currentLoads;
setState(toSet, context);
}
xhrEvent.on('complete', function() {
popLoadingState(xhrEvent, stateName, modelOrCollection, context);
});
}
} | [
"function",
"pushLoadingState",
"(",
"xhrEvent",
",",
"stateName",
",",
"modelOrCollection",
",",
"context",
",",
"force",
")",
"{",
"var",
"currentLoads",
"=",
"getState",
"(",
"stateName",
",",
"context",
")",
",",
"currentlyLoading",
"=",
"currentLoads",
"&&"... | loading state helpers | [
"loading",
"state",
"helpers"
] | d9064510ae73f915444a11ec1100b53614bef177 | https://github.com/jhudson8/react-backbone/blob/d9064510ae73f915444a11ec1100b53614bef177/react-backbone.js#L295-L321 |
28,808 | jhudson8/react-backbone | react-backbone.js | popLoadingState | function popLoadingState(xhrEvent, stateName, modelOrCollection, context) {
var currentLoads = getState(stateName, context);
if (_.isArray(currentLoads)) {
var i = currentLoads.indexOf(xhrEvent);
while (i >= 0) {
currentLoads.splice(i, 1);
i = currentLoads.indexOf(xhrEvent);
}
if (!currentLoads.length) {
var toSet = {};
toSet[stateName] = undefined;
setState(toSet, context);
}
}
} | javascript | function popLoadingState(xhrEvent, stateName, modelOrCollection, context) {
var currentLoads = getState(stateName, context);
if (_.isArray(currentLoads)) {
var i = currentLoads.indexOf(xhrEvent);
while (i >= 0) {
currentLoads.splice(i, 1);
i = currentLoads.indexOf(xhrEvent);
}
if (!currentLoads.length) {
var toSet = {};
toSet[stateName] = undefined;
setState(toSet, context);
}
}
} | [
"function",
"popLoadingState",
"(",
"xhrEvent",
",",
"stateName",
",",
"modelOrCollection",
",",
"context",
")",
"{",
"var",
"currentLoads",
"=",
"getState",
"(",
"stateName",
",",
"context",
")",
";",
"if",
"(",
"_",
".",
"isArray",
"(",
"currentLoads",
")"... | remove the xhrEvent from the loading state | [
"remove",
"the",
"xhrEvent",
"from",
"the",
"loading",
"state"
] | d9064510ae73f915444a11ec1100b53614bef177 | https://github.com/jhudson8/react-backbone/blob/d9064510ae73f915444a11ec1100b53614bef177/react-backbone.js#L324-L338 |
28,809 | jhudson8/react-backbone | react-backbone.js | joinCurrentModelActivity | function joinCurrentModelActivity(method, stateName, modelOrCollection, context, force) {
var xhrActivity = modelOrCollection[xhrModelLoadingAttribute];
if (xhrActivity) {
_.each(xhrActivity, function(xhrEvent) {
if (!method || method === ALL_XHR_ACTIVITY || xhrEvent.method === method) {
// this is one that is applicable
pushLoadingState(xhrEvent, stateName, modelOrCollection, context, force);
}
});
}
} | javascript | function joinCurrentModelActivity(method, stateName, modelOrCollection, context, force) {
var xhrActivity = modelOrCollection[xhrModelLoadingAttribute];
if (xhrActivity) {
_.each(xhrActivity, function(xhrEvent) {
if (!method || method === ALL_XHR_ACTIVITY || xhrEvent.method === method) {
// this is one that is applicable
pushLoadingState(xhrEvent, stateName, modelOrCollection, context, force);
}
});
}
} | [
"function",
"joinCurrentModelActivity",
"(",
"method",
",",
"stateName",
",",
"modelOrCollection",
",",
"context",
",",
"force",
")",
"{",
"var",
"xhrActivity",
"=",
"modelOrCollection",
"[",
"xhrModelLoadingAttribute",
"]",
";",
"if",
"(",
"xhrActivity",
")",
"{"... | if there is any current xhrEvent that match the method, add a reference to it with this context | [
"if",
"there",
"is",
"any",
"current",
"xhrEvent",
"that",
"match",
"the",
"method",
"add",
"a",
"reference",
"to",
"it",
"with",
"this",
"context"
] | d9064510ae73f915444a11ec1100b53614bef177 | https://github.com/jhudson8/react-backbone/blob/d9064510ae73f915444a11ec1100b53614bef177/react-backbone.js#L341-L351 |
28,810 | jhudson8/react-backbone | react-backbone.js | function() {
var keys = arguments.length > 0 ? Array.prototype.slice.call(arguments, 0) : undefined;
return {
getInitialState: function() {
var self = this;
modelOrCollectionEventHandler(typeData.type, keys || 'updateOn', this, '{key}', function() {
self.deferUpdate();
});
}
};
} | javascript | function() {
var keys = arguments.length > 0 ? Array.prototype.slice.call(arguments, 0) : undefined;
return {
getInitialState: function() {
var self = this;
modelOrCollectionEventHandler(typeData.type, keys || 'updateOn', this, '{key}', function() {
self.deferUpdate();
});
}
};
} | [
"function",
"(",
")",
"{",
"var",
"keys",
"=",
"arguments",
".",
"length",
">",
"0",
"?",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
")",
":",
"undefined",
";",
"return",
"{",
"getInitialState",
":",
"function",
... | Gives any comonent the ability to force an update when an event is fired | [
"Gives",
"any",
"comonent",
"the",
"ability",
"to",
"force",
"an",
"update",
"when",
"an",
"event",
"is",
"fired"
] | d9064510ae73f915444a11ec1100b53614bef177 | https://github.com/jhudson8/react-backbone/blob/d9064510ae73f915444a11ec1100b53614bef177/react-backbone.js#L669-L679 | |
28,811 | jhudson8/react-backbone | react-backbone.js | function(type, attributes, isCheckable, classAttributes) {
return React.createClass(_.extend({
mixins: ['modelAware'],
render: function() {
var props = {};
var defaultValue = getModelValue(this);
if (isCheckable) {
props.defaultChecked = defaultValue;
} else {
props.defaultValue = defaultValue;
}
return React.DOM[type](_.extend(props, attributes, this.props,
{onChange: twoWayBinding(this)}), this.props.children);
},
getValue: function() {
if (this.isMounted()) {
if (isCheckable) {
var el = this.getDOMNode();
return el.checked ? true : false;
} else {
return getElementValue(this);
}
}
},
getDOMValue: function() {
if (this.isMounted()) {
return getElementValue(this);
}
}
}, classAttributes));
} | javascript | function(type, attributes, isCheckable, classAttributes) {
return React.createClass(_.extend({
mixins: ['modelAware'],
render: function() {
var props = {};
var defaultValue = getModelValue(this);
if (isCheckable) {
props.defaultChecked = defaultValue;
} else {
props.defaultValue = defaultValue;
}
return React.DOM[type](_.extend(props, attributes, this.props,
{onChange: twoWayBinding(this)}), this.props.children);
},
getValue: function() {
if (this.isMounted()) {
if (isCheckable) {
var el = this.getDOMNode();
return el.checked ? true : false;
} else {
return getElementValue(this);
}
}
},
getDOMValue: function() {
if (this.isMounted()) {
return getElementValue(this);
}
}
}, classAttributes));
} | [
"function",
"(",
"type",
",",
"attributes",
",",
"isCheckable",
",",
"classAttributes",
")",
"{",
"return",
"React",
".",
"createClass",
"(",
"_",
".",
"extend",
"(",
"{",
"mixins",
":",
"[",
"'modelAware'",
"]",
",",
"render",
":",
"function",
"(",
")",... | Standard input components that implement react-backbone model awareness | [
"Standard",
"input",
"components",
"that",
"implement",
"react",
"-",
"backbone",
"model",
"awareness"
] | d9064510ae73f915444a11ec1100b53614bef177 | https://github.com/jhudson8/react-backbone/blob/d9064510ae73f915444a11ec1100b53614bef177/react-backbone.js#L942-L972 | |
28,812 | rekit/rekit-core | core/plugin.js | loadPlugin | function loadPlugin(pluginRoot, noUI) {
// noUI flag is used for loading dev plugins whose ui is from webpack dev server
try {
// const pkgJson = require(paths.join(pluginRoot, 'package.json'));
const pluginInstance = {};
// Core part
const coreIndex = paths.join(pluginRoot, 'core/index.js');
if (fs.existsSync(coreIndex)) {
Object.assign(pluginInstance, require(coreIndex));
}
// UI part
if (!noUI && fs.existsSync(path.join(pluginRoot, 'build/main.js'))) {
pluginInstance.ui = {
root: path.join(pluginRoot, 'build'),
};
}
// Plugin meta defined in package.json
const pkgJsonPath = path.join(pluginRoot, 'package.json');
let pkgJson = null;
if (fs.existsSync(pkgJsonPath)) {
pkgJson = fs.readJsonSync(pkgJsonPath);
['appType', 'name', 'featureFiles'].forEach(key => {
if (!pluginInstance.hasOwnProperty(key) && pkgJson.hasOwnProperty(key)) {
if (key === 'name') {
let name = pkgJson.name;
if (name.startsWith('rekit-plugin')) name = name.replace('rekit-plugin-', '');
pluginInstance.name = name;
} else {
pluginInstance[key] = pkgJson[key] || null;
}
}
});
if (pkgJson.rekitPlugin) {
Object.keys(pkgJson.rekitPlugin).forEach(key => {
if (!pluginInstance.hasOwnProperty(key)) {
pluginInstance[key] = pkgJson.rekitPlugin[key];
}
});
}
}
return pluginInstance;
} catch (e) {
logger.warn(`Failed to load plugin: ${pluginRoot}`, e);
}
return null;
} | javascript | function loadPlugin(pluginRoot, noUI) {
// noUI flag is used for loading dev plugins whose ui is from webpack dev server
try {
// const pkgJson = require(paths.join(pluginRoot, 'package.json'));
const pluginInstance = {};
// Core part
const coreIndex = paths.join(pluginRoot, 'core/index.js');
if (fs.existsSync(coreIndex)) {
Object.assign(pluginInstance, require(coreIndex));
}
// UI part
if (!noUI && fs.existsSync(path.join(pluginRoot, 'build/main.js'))) {
pluginInstance.ui = {
root: path.join(pluginRoot, 'build'),
};
}
// Plugin meta defined in package.json
const pkgJsonPath = path.join(pluginRoot, 'package.json');
let pkgJson = null;
if (fs.existsSync(pkgJsonPath)) {
pkgJson = fs.readJsonSync(pkgJsonPath);
['appType', 'name', 'featureFiles'].forEach(key => {
if (!pluginInstance.hasOwnProperty(key) && pkgJson.hasOwnProperty(key)) {
if (key === 'name') {
let name = pkgJson.name;
if (name.startsWith('rekit-plugin')) name = name.replace('rekit-plugin-', '');
pluginInstance.name = name;
} else {
pluginInstance[key] = pkgJson[key] || null;
}
}
});
if (pkgJson.rekitPlugin) {
Object.keys(pkgJson.rekitPlugin).forEach(key => {
if (!pluginInstance.hasOwnProperty(key)) {
pluginInstance[key] = pkgJson.rekitPlugin[key];
}
});
}
}
return pluginInstance;
} catch (e) {
logger.warn(`Failed to load plugin: ${pluginRoot}`, e);
}
return null;
} | [
"function",
"loadPlugin",
"(",
"pluginRoot",
",",
"noUI",
")",
"{",
"// noUI flag is used for loading dev plugins whose ui is from webpack dev server",
"try",
"{",
"// const pkgJson = require(paths.join(pluginRoot, 'package.json'));",
"const",
"pluginInstance",
"=",
"{",
"}",
";",
... | Load plugin instance, plugin depends on project config | [
"Load",
"plugin",
"instance",
"plugin",
"depends",
"on",
"project",
"config"
] | e98ab59da85a517717e1ff4e7c724d4c917a45b8 | https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/core/plugin.js#L112-L160 |
28,813 | rekit/rekit-core | core/plugin.js | addPlugin | function addPlugin(plugin) {
if (!plugin) {
return;
}
if (!needFilterPlugin) {
console.warn('You are adding a plugin after getPlugins is called.');
}
needFilterPlugin = true;
if (!plugin.name) {
console.log('plugin: ', plugin);
throw new Error('Each plugin should have a name.');
}
if (_.find(allPlugins, { name: plugin.name })) {
console.warn('You should not add a plugin with same name: ' + plugin.name);
return;
}
allPlugins.push(plugin);
} | javascript | function addPlugin(plugin) {
if (!plugin) {
return;
}
if (!needFilterPlugin) {
console.warn('You are adding a plugin after getPlugins is called.');
}
needFilterPlugin = true;
if (!plugin.name) {
console.log('plugin: ', plugin);
throw new Error('Each plugin should have a name.');
}
if (_.find(allPlugins, { name: plugin.name })) {
console.warn('You should not add a plugin with same name: ' + plugin.name);
return;
}
allPlugins.push(plugin);
} | [
"function",
"addPlugin",
"(",
"plugin",
")",
"{",
"if",
"(",
"!",
"plugin",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"needFilterPlugin",
")",
"{",
"console",
".",
"warn",
"(",
"'You are adding a plugin after getPlugins is called.'",
")",
";",
"}",
"need... | Dynamically add an plugin | [
"Dynamically",
"add",
"an",
"plugin"
] | e98ab59da85a517717e1ff4e7c724d4c917a45b8 | https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/core/plugin.js#L173-L190 |
28,814 | rekit/rekit-core | core/template.js | generate | function generate(targetPath, args) {
if (
!args.template &&
(!args.templateFile || (args.templateFile && !vio.fileExists(args.templateFile)))
) {
const err = new Error(`No template file found: ${args.templateFile}`);
err.code = 'TEMPLATE_FILE_NOT_FOUND';
throw err;
}
const tpl = args.template || vio.getContent(args.templateFile);
const compiled = _.template(tpl, args.templateOptions || {});
const result = compiled(args.context || {});
vio.save(targetPath, result);
} | javascript | function generate(targetPath, args) {
if (
!args.template &&
(!args.templateFile || (args.templateFile && !vio.fileExists(args.templateFile)))
) {
const err = new Error(`No template file found: ${args.templateFile}`);
err.code = 'TEMPLATE_FILE_NOT_FOUND';
throw err;
}
const tpl = args.template || vio.getContent(args.templateFile);
const compiled = _.template(tpl, args.templateOptions || {});
const result = compiled(args.context || {});
vio.save(targetPath, result);
} | [
"function",
"generate",
"(",
"targetPath",
",",
"args",
")",
"{",
"if",
"(",
"!",
"args",
".",
"template",
"&&",
"(",
"!",
"args",
".",
"templateFile",
"||",
"(",
"args",
".",
"templateFile",
"&&",
"!",
"vio",
".",
"fileExists",
"(",
"args",
".",
"te... | Process the template file and save the result to virtual IO.
If the target file has existed, throw fatal error and exit.
@param {string} targetPath - The path to save the result.
@param {Object} args - The path to save the result.
@param {string} args.template - The template string to process.
@param {string} args.templateFile - If no 'template' defined, read the template file to process. One of template and templateFile should be provided.
@param {Object} args.context - The context to process the template.
@alias module:template.generate
@example
const template = require('rekit-core').template;
const tpl = 'hello ${user}!';
template.generate('path/to/result.txt', { template: tpl, context: { user: 'Nate' } });
// Result => create a file 'path/to/result.txt' which contains text: 'hello Nate!'
// NOTE the result is only in vio, you need to call vio.flush() to write to disk. | [
"Process",
"the",
"template",
"file",
"and",
"save",
"the",
"result",
"to",
"virtual",
"IO",
".",
"If",
"the",
"target",
"file",
"has",
"existed",
"throw",
"fatal",
"error",
"and",
"exit",
"."
] | e98ab59da85a517717e1ff4e7c724d4c917a45b8 | https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/core/template.js#L41-L55 |
28,815 | crcn/caplet.js | lib/model.js | function() {
var data = {};
if (this.data && !isObject(this.data)) {
return this.data;
}
// TODO - don't do this yet until virt properties are checked
// var keys = Object.keys(this);
var keys = Object.keys(this.data ? this.data : this);
for (var i = 0, n = keys.length; i < n; i++) {
var key = keys[i];
if (key in this.constructor.prototype || key.charCodeAt(0) === 95) {
continue;
}
data[key] = this[key];
}
return data;
} | javascript | function() {
var data = {};
if (this.data && !isObject(this.data)) {
return this.data;
}
// TODO - don't do this yet until virt properties are checked
// var keys = Object.keys(this);
var keys = Object.keys(this.data ? this.data : this);
for (var i = 0, n = keys.length; i < n; i++) {
var key = keys[i];
if (key in this.constructor.prototype || key.charCodeAt(0) === 95) {
continue;
}
data[key] = this[key];
}
return data;
} | [
"function",
"(",
")",
"{",
"var",
"data",
"=",
"{",
"}",
";",
"if",
"(",
"this",
".",
"data",
"&&",
"!",
"isObject",
"(",
"this",
".",
"data",
")",
")",
"{",
"return",
"this",
".",
"data",
";",
"}",
"// TODO - don't do this yet until virt properties are ... | serialize this model back into a data object | [
"serialize",
"this",
"model",
"back",
"into",
"a",
"data",
"object"
] | 63af94de8ddab8576f6df3a384e40157d7f7c5b1 | https://github.com/crcn/caplet.js/blob/63af94de8ddab8576f6df3a384e40157d7f7c5b1/lib/model.js#L64-L86 | |
28,816 | rekit/rekit-core | core/refactor/cls.js | renameClassName | function renameClassName(ast, oldName, newName) {
let defNode = null;
// Find the definition node of the class
traverse(ast, {
ClassDeclaration(path) {
if (path.node.id && path.node.id.name === oldName) {
defNode = path.node.id;
}
}
});
if (defNode) {
return identifier.renameIdentifier(ast, oldName, newName, defNode);
}
return [];
} | javascript | function renameClassName(ast, oldName, newName) {
let defNode = null;
// Find the definition node of the class
traverse(ast, {
ClassDeclaration(path) {
if (path.node.id && path.node.id.name === oldName) {
defNode = path.node.id;
}
}
});
if (defNode) {
return identifier.renameIdentifier(ast, oldName, newName, defNode);
}
return [];
} | [
"function",
"renameClassName",
"(",
"ast",
",",
"oldName",
",",
"newName",
")",
"{",
"let",
"defNode",
"=",
"null",
";",
"// Find the definition node of the class",
"traverse",
"(",
"ast",
",",
"{",
"ClassDeclaration",
"(",
"path",
")",
"{",
"if",
"(",
"path",... | Rename a es6 class name in a module. Only rename the class definition and its reference in the module.
It will not find other files to rename reference.
@param {string} ast - Which module to rename class name.
@param {string} oldName - The old class name.
@index {number} newName - The new class name.
@alias module:refactor.renameClassName
@example
// class MyClass {
// ...
// }
const refactor = require('rekit-core').refactor;
refactor.renameClassName(file, 'MyClass', 'NewMyClass');
// => class NewMyClass {
// => ...
// => } | [
"Rename",
"a",
"es6",
"class",
"name",
"in",
"a",
"module",
".",
"Only",
"rename",
"the",
"class",
"definition",
"and",
"its",
"reference",
"in",
"the",
"module",
".",
"It",
"will",
"not",
"find",
"other",
"files",
"to",
"rename",
"reference",
"."
] | e98ab59da85a517717e1ff4e7c724d4c917a45b8 | https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/core/refactor/cls.js#L24-L39 |
28,817 | rekit/rekit-core | core/refactor/identifier.js | renameIdentifier | function renameIdentifier(ast, oldName, newName, defNode) {
// Summary:
// Rename identifiers with oldName in ast
const changes = [];
if (!defNode) {
let scope;
traverse(ast, {
Identifier(path) {
if (path.node.name === oldName) {
scope = path.scope;
path.stop();
}
},
});
if (!scope) return changes;
defNode = getDefNode(oldName, scope);
}
function rename(path) {
if (
path.node.name === oldName &&
path.key !== 'imported' && // it should NOT be imported specifier
getDefNode(path.node.name, path.scope) === defNode
) {
path.node.name = newName;
changes.push({
start: path.node.start,
end: path.node.end,
replacement: newName,
});
}
}
traverse(ast, {
JSXIdentifier: rename,
Identifier: rename,
});
return changes;
} | javascript | function renameIdentifier(ast, oldName, newName, defNode) {
// Summary:
// Rename identifiers with oldName in ast
const changes = [];
if (!defNode) {
let scope;
traverse(ast, {
Identifier(path) {
if (path.node.name === oldName) {
scope = path.scope;
path.stop();
}
},
});
if (!scope) return changes;
defNode = getDefNode(oldName, scope);
}
function rename(path) {
if (
path.node.name === oldName &&
path.key !== 'imported' && // it should NOT be imported specifier
getDefNode(path.node.name, path.scope) === defNode
) {
path.node.name = newName;
changes.push({
start: path.node.start,
end: path.node.end,
replacement: newName,
});
}
}
traverse(ast, {
JSXIdentifier: rename,
Identifier: rename,
});
return changes;
} | [
"function",
"renameIdentifier",
"(",
"ast",
",",
"oldName",
",",
"newName",
",",
"defNode",
")",
"{",
"// Summary:",
"// Rename identifiers with oldName in ast",
"const",
"changes",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"defNode",
")",
"{",
"let",
"scope",
";",... | Rename an top scope identifier in a module. If first finds the definition node of the given name.
Then rename all identifiers those refer to that definition node.
@param {string} ast - Which module to rename an identifier.
@param {string} oldName - The old identifier name.
@index {string} newName - The new identifier name.
@index {object} defNode - The definition node of the identifier. If not provided, then find the first definition in the module.
@alias module:refactor.renameIdentifier
@example
// import { m1 } from './some-module';
// m1.doSomething();
// function () { const m1 = 'abc'; }
const refactor = require('rekit-core').refactor;
refactor.renameIdentifier(file, 'm1', 'm2');
// => import { m2 } from './some-module';
// => m2.doSomething();
// => function () { const m1 = 'abc'; } // m1 is not renamed. | [
"Rename",
"an",
"top",
"scope",
"identifier",
"in",
"a",
"module",
".",
"If",
"first",
"finds",
"the",
"definition",
"node",
"of",
"the",
"given",
"name",
".",
"Then",
"rename",
"all",
"identifiers",
"those",
"refer",
"to",
"that",
"definition",
"node",
".... | e98ab59da85a517717e1ff4e7c724d4c917a45b8 | https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/core/refactor/identifier.js#L35-L72 |
28,818 | rekit/rekit-core | core/refactor/common.js | isLocalModule | function isLocalModule(modulePath) {
// TODO: handle alias module path like src
const alias = getModuleResolverAlias();
return /^\./.test(modulePath) || _.keys(alias).some(a => modulePath === a || _.startsWith(modulePath, a + '/'));
} | javascript | function isLocalModule(modulePath) {
// TODO: handle alias module path like src
const alias = getModuleResolverAlias();
return /^\./.test(modulePath) || _.keys(alias).some(a => modulePath === a || _.startsWith(modulePath, a + '/'));
} | [
"function",
"isLocalModule",
"(",
"modulePath",
")",
"{",
"// TODO: handle alias module path like src",
"const",
"alias",
"=",
"getModuleResolverAlias",
"(",
")",
";",
"return",
"/",
"^\\.",
"/",
".",
"test",
"(",
"modulePath",
")",
"||",
"_",
".",
"keys",
"(",
... | Check if a module is local module. It will check alias defined by babel plugin module-resolver.
@param {string} modulePath - The module path. i.e.: import * from './abc'; './abc' is the module path.
@alias module:common.isLocalModule | [
"Check",
"if",
"a",
"module",
"is",
"local",
"module",
".",
"It",
"will",
"check",
"alias",
"defined",
"by",
"babel",
"plugin",
"module",
"-",
"resolver",
"."
] | e98ab59da85a517717e1ff4e7c724d4c917a45b8 | https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/core/refactor/common.js#L72-L76 |
28,819 | rekit/rekit-core | core/refactor/common.js | resolveModulePath | function resolveModulePath(relativeToFile, modulePath) {
if (!isLocalModule(modulePath)) {
return modulePath;
}
const alias = getModuleResolverAlias();
const matched = _.find(_.keys(alias), k => _.startsWith(modulePath, k));
let res = null;
if (matched) {
const resolveTo = alias[matched];
const relativePath = modulePath.replace(new RegExp(`^${matched}`), '').replace(/^\//, '');
res = paths.map(resolveTo, relativePath);
// res = utils.joinPath(utils.getProjectRoot(), resolveTo, relativePath);
} else {
res = paths.join(path.dirname(relativeToFile), modulePath);
}
let relPath = res.replace(paths.getProjectRoot(), '').replace(/^\/?/, '');
if (vio.dirExists(relPath)) {
// if import from a folder, then resolve to index.js
relPath = paths.join(relPath, 'index');
}
return relPath;
} | javascript | function resolveModulePath(relativeToFile, modulePath) {
if (!isLocalModule(modulePath)) {
return modulePath;
}
const alias = getModuleResolverAlias();
const matched = _.find(_.keys(alias), k => _.startsWith(modulePath, k));
let res = null;
if (matched) {
const resolveTo = alias[matched];
const relativePath = modulePath.replace(new RegExp(`^${matched}`), '').replace(/^\//, '');
res = paths.map(resolveTo, relativePath);
// res = utils.joinPath(utils.getProjectRoot(), resolveTo, relativePath);
} else {
res = paths.join(path.dirname(relativeToFile), modulePath);
}
let relPath = res.replace(paths.getProjectRoot(), '').replace(/^\/?/, '');
if (vio.dirExists(relPath)) {
// if import from a folder, then resolve to index.js
relPath = paths.join(relPath, 'index');
}
return relPath;
} | [
"function",
"resolveModulePath",
"(",
"relativeToFile",
",",
"modulePath",
")",
"{",
"if",
"(",
"!",
"isLocalModule",
"(",
"modulePath",
")",
")",
"{",
"return",
"modulePath",
";",
"}",
"const",
"alias",
"=",
"getModuleResolverAlias",
"(",
")",
";",
"const",
... | Resolve the module path.
@param {string} relativeTo - Relative to which file to resolve. That is the file in which import the module.
@param {string} modulePath - The relative module path.
@alias module:common.resolveModulePath | [
"Resolve",
"the",
"module",
"path",
"."
] | e98ab59da85a517717e1ff4e7c724d4c917a45b8 | https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/core/refactor/common.js#L84-L108 |
28,820 | rekit/rekit-core | core/refactor/func.js | renameFunctionName | function renameFunctionName(ast, oldName, newName) {
// Summary:
// Rename the name of the function first found. Usually used by
// flat function definition file.
let defNode = null;
// Find the definition node of the class
traverse(ast, {
FunctionDeclaration(path) {
if (path.node.id && path.node.id.name === oldName) {
defNode = path.node.id;
}
}
});
if (defNode) {
return identifier.renameIdentifier(ast, oldName, newName, defNode);
}
return [];
} | javascript | function renameFunctionName(ast, oldName, newName) {
// Summary:
// Rename the name of the function first found. Usually used by
// flat function definition file.
let defNode = null;
// Find the definition node of the class
traverse(ast, {
FunctionDeclaration(path) {
if (path.node.id && path.node.id.name === oldName) {
defNode = path.node.id;
}
}
});
if (defNode) {
return identifier.renameIdentifier(ast, oldName, newName, defNode);
}
return [];
} | [
"function",
"renameFunctionName",
"(",
"ast",
",",
"oldName",
",",
"newName",
")",
"{",
"// Summary:",
"// Rename the name of the function first found. Usually used by",
"// flat function definition file.",
"let",
"defNode",
"=",
"null",
";",
"// Find the definition node of the... | Rename a function name in a module.
@param {string} ast - Which module to rename function.
@param {string} oldName - The old function name.
@index {number} newName - The new function name.
@alias module:refactor.renameFunctionName
@example
// function MyFunc() {
// ...
// }
const refactor = require('rekit-core').refactor;
refactor.renameFunctionName(file, 'MyFunc', 'NewMyFunc');
// => function NewMyFunc {
// => ...
// => } | [
"Rename",
"a",
"function",
"name",
"in",
"a",
"module",
"."
] | e98ab59da85a517717e1ff4e7c724d4c917a45b8 | https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/core/refactor/func.js#L23-L42 |
28,821 | rekit/rekit-core | core/refactor/array.js | nearestCharAfter | function nearestCharAfter(char, str, index) {
// Find the nearest char index before given index. skip white space strings
// If not found, return -1
let i = index + 1;
while (i < str.length) {
if (str.charAt(i) === char) return i;
if (!/\s/.test(str.charAt(i))) return -1;
i += 1;
}
return -1;
} | javascript | function nearestCharAfter(char, str, index) {
// Find the nearest char index before given index. skip white space strings
// If not found, return -1
let i = index + 1;
while (i < str.length) {
if (str.charAt(i) === char) return i;
if (!/\s/.test(str.charAt(i))) return -1;
i += 1;
}
return -1;
} | [
"function",
"nearestCharAfter",
"(",
"char",
",",
"str",
",",
"index",
")",
"{",
"// Find the nearest char index before given index. skip white space strings",
"// If not found, return -1",
"let",
"i",
"=",
"index",
"+",
"1",
";",
"while",
"(",
"i",
"<",
"str",
".",
... | Similar with nearestCharBefore, but find the char after the given index.
If not found, return -1
@param {string} char - Which char to find
@param {string} str - The string to to search.
@index {number} index - From which index start to find
@ | [
"Similar",
"with",
"nearestCharBefore",
"but",
"find",
"the",
"char",
"after",
"the",
"given",
"index",
".",
"If",
"not",
"found",
"return",
"-",
"1"
] | e98ab59da85a517717e1ff4e7c724d4c917a45b8 | https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/core/refactor/array.js#L39-L49 |
28,822 | rekit/rekit-core | core/refactor/array.js | addToArrayByNode | function addToArrayByNode(node, code) {
// node: the arr expression node
// code: added as the last element of the array
const multilines = node.loc.start.line !== node.loc.end.line;
let insertPos = node.start + 1; // insert after '['
if (node.elements.length) {
const ele = _.last(node.elements);
insertPos = ele.end;
}
let replacement;
if (multilines) {
const indent = _.repeat(' ', node.loc.end.column - 1);
replacement = `\n${indent} ${code}`;
if (node.elements.length) {
replacement = `,${replacement}`;
} else {
replacement = `${replacement},`;
}
} else {
replacement = code;
if (node.elements.length > 0) {
replacement = `, ${code}`;
}
}
return [
{
start: insertPos,
end: insertPos,
replacement,
},
];
} | javascript | function addToArrayByNode(node, code) {
// node: the arr expression node
// code: added as the last element of the array
const multilines = node.loc.start.line !== node.loc.end.line;
let insertPos = node.start + 1; // insert after '['
if (node.elements.length) {
const ele = _.last(node.elements);
insertPos = ele.end;
}
let replacement;
if (multilines) {
const indent = _.repeat(' ', node.loc.end.column - 1);
replacement = `\n${indent} ${code}`;
if (node.elements.length) {
replacement = `,${replacement}`;
} else {
replacement = `${replacement},`;
}
} else {
replacement = code;
if (node.elements.length > 0) {
replacement = `, ${code}`;
}
}
return [
{
start: insertPos,
end: insertPos,
replacement,
},
];
} | [
"function",
"addToArrayByNode",
"(",
"node",
",",
"code",
")",
"{",
"// node: the arr expression node",
"// code: added as the last element of the array",
"const",
"multilines",
"=",
"node",
".",
"loc",
".",
"start",
".",
"line",
"!==",
"node",
".",
"loc",
".",
"end... | Add an element to an array definition.
@param {object} node - The ast node of the array definition.
@param {string} code - The code to append to the array.
@alias module:refactor.addToArrayByNode
@ | [
"Add",
"an",
"element",
"to",
"an",
"array",
"definition",
"."
] | e98ab59da85a517717e1ff4e7c724d4c917a45b8 | https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/core/refactor/array.js#L58-L92 |
28,823 | rekit/rekit-core | core/refactor/array.js | removeFromArrayByNode | function removeFromArrayByNode(node, eleNode) {
const elements = node.elements;
if (!elements.includes(eleNode)) {
logger.warn('Failed to find element when trying to remove element from array.');
return [];
}
if (!node._filePath) {
throw new Error('No _filePath property found on node when removing element from array');
}
const content = vio.getContent(node._filePath);
let startPos = nearestCharBefore(',', content, eleNode.start);
let isFirstElement = false;
if (startPos < 0) {
// it's the first element
isFirstElement = true;
startPos = node.start + 1; // start from the char just after the '['
}
let endPos = eleNode.end;
if (elements.length === 1 || isFirstElement) {
// if the element is the only element, try to remove the trailing comma if exists
const nextComma = nearestCharAfter(',', content, endPos - 1);
if (nextComma >= 0) endPos = nextComma + 1;
}
return [
{
start: startPos,
end: endPos,
replacement: '',
},
];
} | javascript | function removeFromArrayByNode(node, eleNode) {
const elements = node.elements;
if (!elements.includes(eleNode)) {
logger.warn('Failed to find element when trying to remove element from array.');
return [];
}
if (!node._filePath) {
throw new Error('No _filePath property found on node when removing element from array');
}
const content = vio.getContent(node._filePath);
let startPos = nearestCharBefore(',', content, eleNode.start);
let isFirstElement = false;
if (startPos < 0) {
// it's the first element
isFirstElement = true;
startPos = node.start + 1; // start from the char just after the '['
}
let endPos = eleNode.end;
if (elements.length === 1 || isFirstElement) {
// if the element is the only element, try to remove the trailing comma if exists
const nextComma = nearestCharAfter(',', content, endPos - 1);
if (nextComma >= 0) endPos = nextComma + 1;
}
return [
{
start: startPos,
end: endPos,
replacement: '',
},
];
} | [
"function",
"removeFromArrayByNode",
"(",
"node",
",",
"eleNode",
")",
"{",
"const",
"elements",
"=",
"node",
".",
"elements",
";",
"if",
"(",
"!",
"elements",
".",
"includes",
"(",
"eleNode",
")",
")",
"{",
"logger",
".",
"warn",
"(",
"'Failed to find ele... | Remove an element from an array definition.
@param {object} node - The ast node of the array definition.
@param {object} eleNode - The ast node to be removed.
@alias module:refactor.removeFromArrayByNode
@ | [
"Remove",
"an",
"element",
"from",
"an",
"array",
"definition",
"."
] | e98ab59da85a517717e1ff4e7c724d4c917a45b8 | https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/core/refactor/array.js#L101-L138 |
28,824 | rekit/rekit-core | core/refactor/array.js | addToArray | function addToArray(ast, varName, identifierName) {
let changes = [];
traverse(ast, {
VariableDeclarator(path) {
const node = path.node;
if (_.get(node, 'id.name') !== varName || _.get(node, 'init.type') !== 'ArrayExpression')
return;
node.init._filePath = ast._filePath;
changes = addToArrayByNode(node.init, identifierName);
path.stop();
},
});
return changes;
} | javascript | function addToArray(ast, varName, identifierName) {
let changes = [];
traverse(ast, {
VariableDeclarator(path) {
const node = path.node;
if (_.get(node, 'id.name') !== varName || _.get(node, 'init.type') !== 'ArrayExpression')
return;
node.init._filePath = ast._filePath;
changes = addToArrayByNode(node.init, identifierName);
path.stop();
},
});
return changes;
} | [
"function",
"addToArray",
"(",
"ast",
",",
"varName",
",",
"identifierName",
")",
"{",
"let",
"changes",
"=",
"[",
"]",
";",
"traverse",
"(",
"ast",
",",
"{",
"VariableDeclarator",
"(",
"path",
")",
"{",
"const",
"node",
"=",
"path",
".",
"node",
";",
... | Add an identifier to the array of the name 'varName'.
It only finds the first matched array in the top scope of ast.
@param {object|string} ast - The ast tree or the js file path to find the array.
@param {string} varName - The variable name of the array definition.
@param {string} identifierName - The identifier to append to array.
@alias module:refactor.addToArray
@example
const refactor = require('rekit-core').refactor;
// code in ast: const arr = [a, b, c];
refactor.addToArray(file, 'arr', 'd');
// code changes to: const arr = [a, b, c, d]; | [
"Add",
"an",
"identifier",
"to",
"the",
"array",
"of",
"the",
"name",
"varName",
".",
"It",
"only",
"finds",
"the",
"first",
"matched",
"array",
"in",
"the",
"top",
"scope",
"of",
"ast",
"."
] | e98ab59da85a517717e1ff4e7c724d4c917a45b8 | https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/core/refactor/array.js#L155-L168 |
28,825 | rekit/rekit-core | core/refactor/array.js | removeFromArray | function removeFromArray(ast, varName, identifierName) {
let changes = [];
traverse(ast, {
VariableDeclarator(path) {
const node = path.node;
if (_.get(node, 'id.name') !== varName || _.get(node, 'init.type') !== 'ArrayExpression')
return;
node.init._filePath = ast._filePath;
const toRemove = _.find(node.init.elements, ele => ele.name === identifierName);
changes = removeFromArrayByNode(node.init, toRemove);
path.stop();
},
});
return changes;
} | javascript | function removeFromArray(ast, varName, identifierName) {
let changes = [];
traverse(ast, {
VariableDeclarator(path) {
const node = path.node;
if (_.get(node, 'id.name') !== varName || _.get(node, 'init.type') !== 'ArrayExpression')
return;
node.init._filePath = ast._filePath;
const toRemove = _.find(node.init.elements, ele => ele.name === identifierName);
changes = removeFromArrayByNode(node.init, toRemove);
path.stop();
},
});
return changes;
} | [
"function",
"removeFromArray",
"(",
"ast",
",",
"varName",
",",
"identifierName",
")",
"{",
"let",
"changes",
"=",
"[",
"]",
";",
"traverse",
"(",
"ast",
",",
"{",
"VariableDeclarator",
"(",
"path",
")",
"{",
"const",
"node",
"=",
"path",
".",
"node",
... | Remove an identifier from the array of the name 'varName'.
It only finds the first matched array in the global scope of ast.
@param {object|string} ast - The ast tree or the js file path to find the array.
@param {string} varName - The variable name of the array definition.
@param {string} identifierName - The identifier to append to array.
@alias module:refactor.removeFromArray
@example
const refactor = require('rekit-core').refactor;
// code in ast: const arr = [a, b, c];
refactor.removeFromArray(file, 'arr', 'a');
// code changes to: const arr = [b, c]; | [
"Remove",
"an",
"identifier",
"from",
"the",
"array",
"of",
"the",
"name",
"varName",
".",
"It",
"only",
"finds",
"the",
"first",
"matched",
"array",
"in",
"the",
"global",
"scope",
"of",
"ast",
"."
] | e98ab59da85a517717e1ff4e7c724d4c917a45b8 | https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/core/refactor/array.js#L185-L199 |
28,826 | bustle/mobiledoc-text-renderer | lib/renderer-factory.js | validateCards | function validateCards(cards) {
if (!Array.isArray(cards)) {
throw new Error('`cards` must be passed as an array');
}
for (let i=0; i < cards.length; i++) {
let card = cards[i];
if (card.type !== RENDER_TYPE) {
throw new Error(`Card "${card.name}" must be type "${RENDER_TYPE}", was "${card.type}"`);
}
if (!card.render) {
throw new Error(`Card "${card.name}" must define \`render\``);
}
}
} | javascript | function validateCards(cards) {
if (!Array.isArray(cards)) {
throw new Error('`cards` must be passed as an array');
}
for (let i=0; i < cards.length; i++) {
let card = cards[i];
if (card.type !== RENDER_TYPE) {
throw new Error(`Card "${card.name}" must be type "${RENDER_TYPE}", was "${card.type}"`);
}
if (!card.render) {
throw new Error(`Card "${card.name}" must define \`render\``);
}
}
} | [
"function",
"validateCards",
"(",
"cards",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"cards",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'`cards` must be passed as an array'",
")",
";",
"}",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
... | runtime Text renderer
renders a mobiledoc to Text
input: mobiledoc
output: Text (string) | [
"runtime",
"Text",
"renderer",
"renders",
"a",
"mobiledoc",
"to",
"Text"
] | 097710a577415311897ef03821bb2b00e9766790 | https://github.com/bustle/mobiledoc-text-renderer/blob/097710a577415311897ef03821bb2b00e9766790/lib/renderer-factory.js#L17-L30 |
28,827 | rekit/rekit-core | plugins/rekit-react/utils.js | parseElePath | function parseElePath(elePath, type = 'component') {
const arr = elePath.split('/');
const feature = _.kebabCase(arr.shift());
let name = arr.pop();
if (type === 'action') name = _.camelCase(name);
else if (type === 'component') name = pascalCase(name);
else throw new Error('Unknown element type: ' + type + ' of ' + elePath);
elePath = [feature, ...arr, name].join('/');
const ele = {
name,
path: elePath,
feature,
};
if (type === 'component') {
ele.modulePath = `src/features/${elePath}.js`;
ele.testPath = `tests/features/${elePath}.test.js`;
ele.stylePath = `src/features/${elePath}.${config.getRekitConfig().css}`;
} else if (type === 'action') {
ele.modulePath = `src/features/${feature}/redux/${name}.js`;
ele.testPath = `tests/features/${feature}/redux/${name}.test.js`;
}
return ele;
} | javascript | function parseElePath(elePath, type = 'component') {
const arr = elePath.split('/');
const feature = _.kebabCase(arr.shift());
let name = arr.pop();
if (type === 'action') name = _.camelCase(name);
else if (type === 'component') name = pascalCase(name);
else throw new Error('Unknown element type: ' + type + ' of ' + elePath);
elePath = [feature, ...arr, name].join('/');
const ele = {
name,
path: elePath,
feature,
};
if (type === 'component') {
ele.modulePath = `src/features/${elePath}.js`;
ele.testPath = `tests/features/${elePath}.test.js`;
ele.stylePath = `src/features/${elePath}.${config.getRekitConfig().css}`;
} else if (type === 'action') {
ele.modulePath = `src/features/${feature}/redux/${name}.js`;
ele.testPath = `tests/features/${feature}/redux/${name}.test.js`;
}
return ele;
} | [
"function",
"parseElePath",
"(",
"elePath",
",",
"type",
"=",
"'component'",
")",
"{",
"const",
"arr",
"=",
"elePath",
".",
"split",
"(",
"'/'",
")",
";",
"const",
"feature",
"=",
"_",
".",
"kebabCase",
"(",
"arr",
".",
"shift",
"(",
")",
")",
";",
... | Parse and normalize an element paths, names | [
"Parse",
"and",
"normalize",
"an",
"element",
"paths",
"names"
] | e98ab59da85a517717e1ff4e7c724d4c917a45b8 | https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/plugins/rekit-react/utils.js#L19-L43 |
28,828 | rekit/rekit-core | plugins/rekit-react/utils.js | getTplPath | function getTplPath(tpl) {
const tplFile = path.join(__dirname, './templates', tpl);
const customTplDir =
_.get(config.getRekitConfig(), 'rekitReact.templateDir') ||
path.join(paths.map('.rekit-react/templates'));
const customTplFile = path.join(customTplDir, tpl);
return fs.existsSync(customTplFile) ? customTplFile : tplFile;
} | javascript | function getTplPath(tpl) {
const tplFile = path.join(__dirname, './templates', tpl);
const customTplDir =
_.get(config.getRekitConfig(), 'rekitReact.templateDir') ||
path.join(paths.map('.rekit-react/templates'));
const customTplFile = path.join(customTplDir, tpl);
return fs.existsSync(customTplFile) ? customTplFile : tplFile;
} | [
"function",
"getTplPath",
"(",
"tpl",
")",
"{",
"const",
"tplFile",
"=",
"path",
".",
"join",
"(",
"__dirname",
",",
"'./templates'",
",",
"tpl",
")",
";",
"const",
"customTplDir",
"=",
"_",
".",
"get",
"(",
"config",
".",
"getRekitConfig",
"(",
")",
"... | Get the template file path | [
"Get",
"the",
"template",
"file",
"path"
] | e98ab59da85a517717e1ff4e7c724d4c917a45b8 | https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/plugins/rekit-react/utils.js#L90-L97 |
28,829 | callumacrae/gulp-w3cjs | index.js | handleMessages | function handleMessages(file, messages, options) {
var success = true;
var errorText = colors.bold(colors.red('HTML Error:'));
var warningText = colors.bold(colors.yellow('HTML Warning:'));
var infoText = colors.bold(colors.green('HTML Info:'));
var lines = file.contents.toString().split(/\r\n|\r|\n/g);
if (!Array.isArray(messages)) {
fancyLog(warningText, 'Failed to run validation on', file.relative);
// Not sure whether this should be true or false
return true;
}
messages.forEach(function (message) {
// allows you to intercept info, warnings or errors, using `options.verifyMessage` methed, returning false will skip the log output
if(options.verifyMessage && !options.verifyMessage(message.type, message.message)) return;
if (message.type === 'info' && !options.showInfo) {
return;
}
if (message.type === 'error') {
success = false;
}
var type = (message.type === 'error') ? errorText : ((message.type === 'info') ? infoText : warningText);
var location = 'Line ' + (message.lastLine || 0) + ', Column ' + (message.lastColumn || 0) + ':';
var erroredLine = lines[message.lastLine - 1];
// If this is false, stream was changed since validation
if (erroredLine) {
var errorColumn = message.lastColumn;
// Trim before if the error is too late in the line
if (errorColumn > 60) {
erroredLine = erroredLine.slice(errorColumn - 50);
errorColumn = 50;
}
// Trim after so the line is not too long
erroredLine = erroredLine.slice(0, 60);
// Highlight character with error
erroredLine =
colors.grey(erroredLine.substring(0, errorColumn - 1)) +
colors.bold(colors.red(erroredLine[ errorColumn - 1 ])) +
colors.grey(erroredLine.substring(errorColumn));
}
if (typeof(message.lastLine) !== 'undefined' || typeof(lastColumn) !== 'undefined') {
fancyLog(type, file.relative, location, message.message);
} else {
fancyLog(type, file.relative, message.message);
}
if (erroredLine) {
fancyLog(erroredLine);
}
});
return success;
} | javascript | function handleMessages(file, messages, options) {
var success = true;
var errorText = colors.bold(colors.red('HTML Error:'));
var warningText = colors.bold(colors.yellow('HTML Warning:'));
var infoText = colors.bold(colors.green('HTML Info:'));
var lines = file.contents.toString().split(/\r\n|\r|\n/g);
if (!Array.isArray(messages)) {
fancyLog(warningText, 'Failed to run validation on', file.relative);
// Not sure whether this should be true or false
return true;
}
messages.forEach(function (message) {
// allows you to intercept info, warnings or errors, using `options.verifyMessage` methed, returning false will skip the log output
if(options.verifyMessage && !options.verifyMessage(message.type, message.message)) return;
if (message.type === 'info' && !options.showInfo) {
return;
}
if (message.type === 'error') {
success = false;
}
var type = (message.type === 'error') ? errorText : ((message.type === 'info') ? infoText : warningText);
var location = 'Line ' + (message.lastLine || 0) + ', Column ' + (message.lastColumn || 0) + ':';
var erroredLine = lines[message.lastLine - 1];
// If this is false, stream was changed since validation
if (erroredLine) {
var errorColumn = message.lastColumn;
// Trim before if the error is too late in the line
if (errorColumn > 60) {
erroredLine = erroredLine.slice(errorColumn - 50);
errorColumn = 50;
}
// Trim after so the line is not too long
erroredLine = erroredLine.slice(0, 60);
// Highlight character with error
erroredLine =
colors.grey(erroredLine.substring(0, errorColumn - 1)) +
colors.bold(colors.red(erroredLine[ errorColumn - 1 ])) +
colors.grey(erroredLine.substring(errorColumn));
}
if (typeof(message.lastLine) !== 'undefined' || typeof(lastColumn) !== 'undefined') {
fancyLog(type, file.relative, location, message.message);
} else {
fancyLog(type, file.relative, message.message);
}
if (erroredLine) {
fancyLog(erroredLine);
}
});
return success;
} | [
"function",
"handleMessages",
"(",
"file",
",",
"messages",
",",
"options",
")",
"{",
"var",
"success",
"=",
"true",
";",
"var",
"errorText",
"=",
"colors",
".",
"bold",
"(",
"colors",
".",
"red",
"(",
"'HTML Error:'",
")",
")",
";",
"var",
"warningText"... | Handles messages.
@param file The file array.
@param messages Array of messages returned by w3cjs.
@return boolean Return false if errors have occurred. | [
"Handles",
"messages",
"."
] | 90ff72a4e2837c174a82c53820555cbe08bf0ece | https://github.com/callumacrae/gulp-w3cjs/blob/90ff72a4e2837c174a82c53820555cbe08bf0ece/index.js#L16-L81 |
28,830 | jhudson8/react-backbone | tutorials/responsive-design/step4/example.js | getStateValues | function getStateValues (size, self) {
var width = $(self.getDOMNode()).width();
return {
profile: width > size ? 'large' : 'small'
};
} | javascript | function getStateValues (size, self) {
var width = $(self.getDOMNode()).width();
return {
profile: width > size ? 'large' : 'small'
};
} | [
"function",
"getStateValues",
"(",
"size",
",",
"self",
")",
"{",
"var",
"width",
"=",
"$",
"(",
"self",
".",
"getDOMNode",
"(",
")",
")",
".",
"width",
"(",
")",
";",
"return",
"{",
"profile",
":",
"width",
">",
"size",
"?",
"'large'",
":",
"'smal... | simple function to return the state object that contains the "profile" value | [
"simple",
"function",
"to",
"return",
"the",
"state",
"object",
"that",
"contains",
"the",
"profile",
"value"
] | d9064510ae73f915444a11ec1100b53614bef177 | https://github.com/jhudson8/react-backbone/blob/d9064510ae73f915444a11ec1100b53614bef177/tutorials/responsive-design/step4/example.js#L9-L14 |
28,831 | rekit/rekit-core | plugins/rekit-react/route.js | add | function add(elePath, args) {
if (!args || !args.urlPath) return;
const ele = parseElePath(elePath, 'component');
const routePath = `src/features/${ele.feature}/route.js`;
if (!vio.fileExists(routePath)) {
throw new Error(`route.add failed: file not found ${routePath}`);
}
const { urlPath } = args;
refactor.addImportFrom(routePath, './', '', ele.name);
const ast1 = ast.getAst(routePath, true);
const arrNode = getChildRoutesNode(ast1);
if (arrNode) {
const rule = `{ path: '${urlPath}', component: ${ele.name}${
args.isIndex ? ', isIndex: true' : ''
} }`;
const changes = refactor.addToArrayByNode(arrNode, rule);
const code = refactor.updateSourceCode(vio.getContent(routePath), changes);
vio.save(routePath, code);
} else {
throw new Error(
`You are adding a route rule, but can't find childRoutes property in '${routePath}', please check.`
);
}
} | javascript | function add(elePath, args) {
if (!args || !args.urlPath) return;
const ele = parseElePath(elePath, 'component');
const routePath = `src/features/${ele.feature}/route.js`;
if (!vio.fileExists(routePath)) {
throw new Error(`route.add failed: file not found ${routePath}`);
}
const { urlPath } = args;
refactor.addImportFrom(routePath, './', '', ele.name);
const ast1 = ast.getAst(routePath, true);
const arrNode = getChildRoutesNode(ast1);
if (arrNode) {
const rule = `{ path: '${urlPath}', component: ${ele.name}${
args.isIndex ? ', isIndex: true' : ''
} }`;
const changes = refactor.addToArrayByNode(arrNode, rule);
const code = refactor.updateSourceCode(vio.getContent(routePath), changes);
vio.save(routePath, code);
} else {
throw new Error(
`You are adding a route rule, but can't find childRoutes property in '${routePath}', please check.`
);
}
} | [
"function",
"add",
"(",
"elePath",
",",
"args",
")",
"{",
"if",
"(",
"!",
"args",
"||",
"!",
"args",
".",
"urlPath",
")",
"return",
";",
"const",
"ele",
"=",
"parseElePath",
"(",
"elePath",
",",
"'component'",
")",
";",
"const",
"routePath",
"=",
"`"... | Add component to a route.js under a feature. It imports all component from index.js | [
"Add",
"component",
"to",
"a",
"route",
".",
"js",
"under",
"a",
"feature",
".",
"It",
"imports",
"all",
"component",
"from",
"index",
".",
"js"
] | e98ab59da85a517717e1ff4e7c724d4c917a45b8 | https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/plugins/rekit-react/route.js#L29-L54 |
28,832 | crcn/caplet.js | examples/chatroom/models/thread.js | function() {
var messages = app.database.messages.find({ threadId: this.uid }, ok(this.set.bind(this, "messages")));
// update unreadMessageCount whenever the messages collection
// changes
messages.watch(function() {
this.set("unreadMessageCount", messages.filter(function(message) {
return !message.read;
}).length);
}.bind(this));
} | javascript | function() {
var messages = app.database.messages.find({ threadId: this.uid }, ok(this.set.bind(this, "messages")));
// update unreadMessageCount whenever the messages collection
// changes
messages.watch(function() {
this.set("unreadMessageCount", messages.filter(function(message) {
return !message.read;
}).length);
}.bind(this));
} | [
"function",
"(",
")",
"{",
"var",
"messages",
"=",
"app",
".",
"database",
".",
"messages",
".",
"find",
"(",
"{",
"threadId",
":",
"this",
".",
"uid",
"}",
",",
"ok",
"(",
"this",
".",
"set",
".",
"bind",
"(",
"this",
",",
"\"messages\"",
")",
"... | start computations on messages only as they're demanded by the application | [
"start",
"computations",
"on",
"messages",
"only",
"as",
"they",
"re",
"demanded",
"by",
"the",
"application"
] | 63af94de8ddab8576f6df3a384e40157d7f7c5b1 | https://github.com/crcn/caplet.js/blob/63af94de8ddab8576f6df3a384e40157d7f7c5b1/examples/chatroom/models/thread.js#L18-L28 | |
28,833 | crcn/caplet.js | examples/chatroom/models/thread.js | function(onLoad) {
// create the collection immediately so we only
// apply an update to an existing collection (Users)
// whenever messages changes
var users = app.models.Users();
// pluck participants from the messages & update users
caplet.watchProperty(this, "messages", function(messages) {
var participants = [];
var used = {};
messages.forEach(function(message) {
if (used[message.userId]) return;
used[message.userId] = 1;
participants.push({ uid: message.userId });
});
users.set("data", participants);
this.set("participants", users);
}).trigger();
} | javascript | function(onLoad) {
// create the collection immediately so we only
// apply an update to an existing collection (Users)
// whenever messages changes
var users = app.models.Users();
// pluck participants from the messages & update users
caplet.watchProperty(this, "messages", function(messages) {
var participants = [];
var used = {};
messages.forEach(function(message) {
if (used[message.userId]) return;
used[message.userId] = 1;
participants.push({ uid: message.userId });
});
users.set("data", participants);
this.set("participants", users);
}).trigger();
} | [
"function",
"(",
"onLoad",
")",
"{",
"// create the collection immediately so we only",
"// apply an update to an existing collection (Users)",
"// whenever messages changes",
"var",
"users",
"=",
"app",
".",
"models",
".",
"Users",
"(",
")",
";",
"// pluck participants from th... | start computing participants | [
"start",
"computing",
"participants"
] | 63af94de8ddab8576f6df3a384e40157d7f7c5b1 | https://github.com/crcn/caplet.js/blob/63af94de8ddab8576f6df3a384e40157d7f7c5b1/examples/chatroom/models/thread.js#L31-L53 | |
28,834 | willwashburn/rescuetime.js | lib/RescuetimeError.js | AbstractError | function AbstractError(message, constr) {
Error.apply(this, arguments);
Error.captureStackTrace(this, constr || this);
this.name = 'AbstractError';
this.message = message;
} | javascript | function AbstractError(message, constr) {
Error.apply(this, arguments);
Error.captureStackTrace(this, constr || this);
this.name = 'AbstractError';
this.message = message;
} | [
"function",
"AbstractError",
"(",
"message",
",",
"constr",
")",
"{",
"Error",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"constr",
"||",
"this",
")",
";",
"this",
".",
"name",
"=",
"'Abs... | `AbstractError` error.
@api private | [
"AbstractError",
"error",
"."
] | 9d2f15eede3d25f622d633e580a3fc8443984424 | https://github.com/willwashburn/rescuetime.js/blob/9d2f15eede3d25f622d633e580a3fc8443984424/lib/RescuetimeError.js#L11-L17 |
28,835 | willwashburn/rescuetime.js | lib/rescuetime.js | Rescuetime | function Rescuetime(apiKey, options) {
// The api key is required
if (!apiKey) {
throw new RescuetimeError('Invalid API Key: ' + apiKey);
}
// Copy over the relavant data
this.apiKey = apiKey;
// Extend the defaults
this.options = _.defaults(options || {}, Rescuetime.defaultOptions);
// Contruct the endpoint with the correct auth from the appId and apiKey
this.endpoint = this.options.endpoint;
} | javascript | function Rescuetime(apiKey, options) {
// The api key is required
if (!apiKey) {
throw new RescuetimeError('Invalid API Key: ' + apiKey);
}
// Copy over the relavant data
this.apiKey = apiKey;
// Extend the defaults
this.options = _.defaults(options || {}, Rescuetime.defaultOptions);
// Contruct the endpoint with the correct auth from the appId and apiKey
this.endpoint = this.options.endpoint;
} | [
"function",
"Rescuetime",
"(",
"apiKey",
",",
"options",
")",
"{",
"// The api key is required",
"if",
"(",
"!",
"apiKey",
")",
"{",
"throw",
"new",
"RescuetimeError",
"(",
"'Invalid API Key: '",
"+",
"apiKey",
")",
";",
"}",
"// Copy over the relavant data",
"thi... | Rescuetime constructor.
@param {String} apiKey - your api key
@param {Object} options - an options object
@api public | [
"Rescuetime",
"constructor",
"."
] | 9d2f15eede3d25f622d633e580a3fc8443984424 | https://github.com/willwashburn/rescuetime.js/blob/9d2f15eede3d25f622d633e580a3fc8443984424/lib/rescuetime.js#L29-L44 |
28,836 | incompl/cloak | src/server/cloak/room.js | function(user) {
if (!this._shouldAllowUser(user)) {
return false;
}
user.leaveRoom();
this.members.push(user);
user.room = this;
if (this.minRoomMembers !== null &&
this.members.length >= this.minRoomMembers) {
this._hasReachedMin = true;
}
this._emitEvent('newMember', this, user);
this._serverMessageMembers(this.isLobby ? 'lobbyMemberJoined' : 'roomMemberJoined', _.pick(user, 'id', 'name'));
user._serverMessage('joinedRoom', _.pick(this, 'name'));
return true;
} | javascript | function(user) {
if (!this._shouldAllowUser(user)) {
return false;
}
user.leaveRoom();
this.members.push(user);
user.room = this;
if (this.minRoomMembers !== null &&
this.members.length >= this.minRoomMembers) {
this._hasReachedMin = true;
}
this._emitEvent('newMember', this, user);
this._serverMessageMembers(this.isLobby ? 'lobbyMemberJoined' : 'roomMemberJoined', _.pick(user, 'id', 'name'));
user._serverMessage('joinedRoom', _.pick(this, 'name'));
return true;
} | [
"function",
"(",
"user",
")",
"{",
"if",
"(",
"!",
"this",
".",
"_shouldAllowUser",
"(",
"user",
")",
")",
"{",
"return",
"false",
";",
"}",
"user",
".",
"leaveRoom",
"(",
")",
";",
"this",
".",
"members",
".",
"push",
"(",
"user",
")",
";",
"use... | return true if successful | [
"return",
"true",
"if",
"successful"
] | fc5c8382c4fdb8de129af4f54287aac09ce75cc8 | https://github.com/incompl/cloak/blob/fc5c8382c4fdb8de129af4f54287aac09ce75cc8/src/server/cloak/room.js#L30-L45 | |
28,837 | Cimpress/cimpress-customizr | src/mcpHelpers.js | getMcpSettings | async function getMcpSettings(accessToken) {
let data = await mcpCustomizr.getSettings(accessToken);
if (Object.keys(data).length === 0) {
return {
language: ['en'],
regionalSettings: 'en',
timezone: 'America/New_York',
};
}
return data;
} | javascript | async function getMcpSettings(accessToken) {
let data = await mcpCustomizr.getSettings(accessToken);
if (Object.keys(data).length === 0) {
return {
language: ['en'],
regionalSettings: 'en',
timezone: 'America/New_York',
};
}
return data;
} | [
"async",
"function",
"getMcpSettings",
"(",
"accessToken",
")",
"{",
"let",
"data",
"=",
"await",
"mcpCustomizr",
".",
"getSettings",
"(",
"accessToken",
")",
";",
"if",
"(",
"Object",
".",
"keys",
"(",
"data",
")",
".",
"length",
"===",
"0",
")",
"{",
... | Return raw settings as stored in Customizr
@param {string} accessToken - Access token to use to call Customizr
@return {Promise<*|void>} | [
"Return",
"raw",
"settings",
"as",
"stored",
"in",
"Customizr"
] | e2f206c6cae475a6b18fa71b2611547b0be2620c | https://github.com/Cimpress/cimpress-customizr/blob/e2f206c6cae475a6b18fa71b2611547b0be2620c/src/mcpHelpers.js#L20-L30 |
28,838 | Cimpress/cimpress-customizr | src/mcpHelpers.js | setMcpSettings | async function setMcpSettings(accessToken, settings) {
return await mcpCustomizr.putSettings(accessToken, {
language: settings.language,
regionalSettings: settings.regionalSettings,
timezone: settings.timezone,
});
} | javascript | async function setMcpSettings(accessToken, settings) {
return await mcpCustomizr.putSettings(accessToken, {
language: settings.language,
regionalSettings: settings.regionalSettings,
timezone: settings.timezone,
});
} | [
"async",
"function",
"setMcpSettings",
"(",
"accessToken",
",",
"settings",
")",
"{",
"return",
"await",
"mcpCustomizr",
".",
"putSettings",
"(",
"accessToken",
",",
"{",
"language",
":",
"settings",
".",
"language",
",",
"regionalSettings",
":",
"settings",
"."... | Set raw settings in Customizr without any validation
@param {string} accessToken - Access token to use to call Customizr
@param {object} settings - Settings object. Only language, regionalSettings and timezone will be read
@return {Promise<void>} | [
"Set",
"raw",
"settings",
"in",
"Customizr",
"without",
"any",
"validation"
] | e2f206c6cae475a6b18fa71b2611547b0be2620c | https://github.com/Cimpress/cimpress-customizr/blob/e2f206c6cae475a6b18fa71b2611547b0be2620c/src/mcpHelpers.js#L38-L44 |
28,839 | Cimpress/cimpress-customizr | src/mcpHelpers.js | setPreferredMcpSettings | async function setPreferredMcpSettings(accessToken, languageCode, languageTag, timezone) {
let preferredLanguage = getValidLanguageOrThrow(languageCode);
let preferredRegionalSettings = getValidLanguageTagOrThrow(languageTag);
let preferredTimezone = getValidTimezoneOrThrow(timezone);
const mcpSettings = await getMcpSettings(accessToken);
return await mcpCustomizr.putSettings(accessToken, {
language: updatePreferredLanguage(preferredLanguage, mcpSettings.language),
regionalSettings: preferredRegionalSettings,
timezone: preferredTimezone,
});
} | javascript | async function setPreferredMcpSettings(accessToken, languageCode, languageTag, timezone) {
let preferredLanguage = getValidLanguageOrThrow(languageCode);
let preferredRegionalSettings = getValidLanguageTagOrThrow(languageTag);
let preferredTimezone = getValidTimezoneOrThrow(timezone);
const mcpSettings = await getMcpSettings(accessToken);
return await mcpCustomizr.putSettings(accessToken, {
language: updatePreferredLanguage(preferredLanguage, mcpSettings.language),
regionalSettings: preferredRegionalSettings,
timezone: preferredTimezone,
});
} | [
"async",
"function",
"setPreferredMcpSettings",
"(",
"accessToken",
",",
"languageCode",
",",
"languageTag",
",",
"timezone",
")",
"{",
"let",
"preferredLanguage",
"=",
"getValidLanguageOrThrow",
"(",
"languageCode",
")",
";",
"let",
"preferredRegionalSettings",
"=",
... | Validate and update the preferred user settings at once
@param {string} accessToken - Access token to use to call Customizr
@param {string} languageCode - ISO-639 language code (eg. bul, en, eng, de)
@param {string} languageTag - RFC 4656 compliant language code (eg. en, en-US)
@param {string} timezone - IANA timezone (eg. Europe/Amsterdam)
@return {Promise<void>} | [
"Validate",
"and",
"update",
"the",
"preferred",
"user",
"settings",
"at",
"once"
] | e2f206c6cae475a6b18fa71b2611547b0be2620c | https://github.com/Cimpress/cimpress-customizr/blob/e2f206c6cae475a6b18fa71b2611547b0be2620c/src/mcpHelpers.js#L54-L66 |
28,840 | Cimpress/cimpress-customizr | src/mcpHelpers.js | getPreferredMcpLanguages | async function getPreferredMcpLanguages(accessToken) {
const mcpSettings = await getMcpSettings(accessToken);
const twoLetterArray = mcpSettings.language || [];
return twoLetterArray.map((twoLetter) => {
let language = countryLanguage.getLanguages().find((a) => a.iso639_1 === twoLetter);
return {
lang: twoLetter,
iso639_1: language ? language.iso639_1 : twoLetter,
iso639_2: language ? language.iso639_2 : undefined,
iso639_3: language ? language.iso639_3 : undefined,
};
});
} | javascript | async function getPreferredMcpLanguages(accessToken) {
const mcpSettings = await getMcpSettings(accessToken);
const twoLetterArray = mcpSettings.language || [];
return twoLetterArray.map((twoLetter) => {
let language = countryLanguage.getLanguages().find((a) => a.iso639_1 === twoLetter);
return {
lang: twoLetter,
iso639_1: language ? language.iso639_1 : twoLetter,
iso639_2: language ? language.iso639_2 : undefined,
iso639_3: language ? language.iso639_3 : undefined,
};
});
} | [
"async",
"function",
"getPreferredMcpLanguages",
"(",
"accessToken",
")",
"{",
"const",
"mcpSettings",
"=",
"await",
"getMcpSettings",
"(",
"accessToken",
")",
";",
"const",
"twoLetterArray",
"=",
"mcpSettings",
".",
"language",
"||",
"[",
"]",
";",
"return",
"t... | Get the preferred language from Customizr
@param {string} accessToken
@return {Promise<*|Uint8Array|BigInt64Array|{lang: *, iso639_1: (string), iso639_2: *, iso639_3: *}[]|Float64Array|Int8Array|Float32Array|Int32Array|Uint32Array|Uint8ClampedArray|BigUint64Array|Int16Array|Uint16Array>} | [
"Get",
"the",
"preferred",
"language",
"from",
"Customizr"
] | e2f206c6cae475a6b18fa71b2611547b0be2620c | https://github.com/Cimpress/cimpress-customizr/blob/e2f206c6cae475a6b18fa71b2611547b0be2620c/src/mcpHelpers.js#L73-L86 |
28,841 | Cimpress/cimpress-customizr | src/mcpHelpers.js | setPreferredMcpLanguage | async function setPreferredMcpLanguage(accessToken, languageCode) {
let language = getValidLanguageOrThrow(languageCode);
let currentLanguages = await getPreferredMcpLanguages(accessToken);
return mcpCustomizr.putSettings(accessToken, {
language: updatePreferredLanguage(language, currentLanguages),
});
} | javascript | async function setPreferredMcpLanguage(accessToken, languageCode) {
let language = getValidLanguageOrThrow(languageCode);
let currentLanguages = await getPreferredMcpLanguages(accessToken);
return mcpCustomizr.putSettings(accessToken, {
language: updatePreferredLanguage(language, currentLanguages),
});
} | [
"async",
"function",
"setPreferredMcpLanguage",
"(",
"accessToken",
",",
"languageCode",
")",
"{",
"let",
"language",
"=",
"getValidLanguageOrThrow",
"(",
"languageCode",
")",
";",
"let",
"currentLanguages",
"=",
"await",
"getPreferredMcpLanguages",
"(",
"accessToken",
... | Update the preferred language in Customizr
@param {string} accessToken - Access token to use to call Customizr
@param {string} languageCode - ISO-639 language code (eg. bul, en, eng, de)
@return {Promise<void>} | [
"Update",
"the",
"preferred",
"language",
"in",
"Customizr"
] | e2f206c6cae475a6b18fa71b2611547b0be2620c | https://github.com/Cimpress/cimpress-customizr/blob/e2f206c6cae475a6b18fa71b2611547b0be2620c/src/mcpHelpers.js#L94-L102 |
28,842 | Cimpress/cimpress-customizr | src/mcpHelpers.js | getPreferredMcpRegionalSettings | async function getPreferredMcpRegionalSettings(accessToken) {
const mcpSettings = await mcpCustomizr.getSettings(accessToken);
return mcpSettings.regionalSettings;
} | javascript | async function getPreferredMcpRegionalSettings(accessToken) {
const mcpSettings = await mcpCustomizr.getSettings(accessToken);
return mcpSettings.regionalSettings;
} | [
"async",
"function",
"getPreferredMcpRegionalSettings",
"(",
"accessToken",
")",
"{",
"const",
"mcpSettings",
"=",
"await",
"mcpCustomizr",
".",
"getSettings",
"(",
"accessToken",
")",
";",
"return",
"mcpSettings",
".",
"regionalSettings",
";",
"}"
] | Get the preferred regional settings from Customizr
@param {string} accessToken - Access token to use to call Customizr
@return {Promise<string>} | [
"Get",
"the",
"preferred",
"regional",
"settings",
"from",
"Customizr"
] | e2f206c6cae475a6b18fa71b2611547b0be2620c | https://github.com/Cimpress/cimpress-customizr/blob/e2f206c6cae475a6b18fa71b2611547b0be2620c/src/mcpHelpers.js#L109-L112 |
28,843 | Cimpress/cimpress-customizr | src/mcpHelpers.js | setPreferredMcpRegionalSettings | async function setPreferredMcpRegionalSettings(accessToken, languageTag) {
let regionalSettings = getValidLanguageTagOrThrow(languageTag);
return mcpCustomizr.putSettings(accessToken, {
regionalSettings: regionalSettings,
});
} | javascript | async function setPreferredMcpRegionalSettings(accessToken, languageTag) {
let regionalSettings = getValidLanguageTagOrThrow(languageTag);
return mcpCustomizr.putSettings(accessToken, {
regionalSettings: regionalSettings,
});
} | [
"async",
"function",
"setPreferredMcpRegionalSettings",
"(",
"accessToken",
",",
"languageTag",
")",
"{",
"let",
"regionalSettings",
"=",
"getValidLanguageTagOrThrow",
"(",
"languageTag",
")",
";",
"return",
"mcpCustomizr",
".",
"putSettings",
"(",
"accessToken",
",",
... | Update the preferred regional format in Customizr
@param {string} accessToken - Access token to use to call Customizr
@param {string} languageTag - RFC 4656 compliant language code (eg. en, en-US)
@return {Promise<void>} | [
"Update",
"the",
"preferred",
"regional",
"format",
"in",
"Customizr"
] | e2f206c6cae475a6b18fa71b2611547b0be2620c | https://github.com/Cimpress/cimpress-customizr/blob/e2f206c6cae475a6b18fa71b2611547b0be2620c/src/mcpHelpers.js#L120-L126 |
28,844 | Cimpress/cimpress-customizr | src/mcpHelpers.js | setPreferredMcpTimezone | async function setPreferredMcpTimezone(accessToken, timezone) {
let tz = getValidTimezoneOrThrow(timezone);
return mcpCustomizr.putSettings(accessToken, {
timezone: tz,
});
} | javascript | async function setPreferredMcpTimezone(accessToken, timezone) {
let tz = getValidTimezoneOrThrow(timezone);
return mcpCustomizr.putSettings(accessToken, {
timezone: tz,
});
} | [
"async",
"function",
"setPreferredMcpTimezone",
"(",
"accessToken",
",",
"timezone",
")",
"{",
"let",
"tz",
"=",
"getValidTimezoneOrThrow",
"(",
"timezone",
")",
";",
"return",
"mcpCustomizr",
".",
"putSettings",
"(",
"accessToken",
",",
"{",
"timezone",
":",
"t... | Update the preferred timezone from Customizr
@param {string} accessToken - Access token to use to call Customizr
@param {string} timezone - IANA timezone (eg. Europe/Amsterdam)
@return {Promise<void>} | [
"Update",
"the",
"preferred",
"timezone",
"from",
"Customizr"
] | e2f206c6cae475a6b18fa71b2611547b0be2620c | https://github.com/Cimpress/cimpress-customizr/blob/e2f206c6cae475a6b18fa71b2611547b0be2620c/src/mcpHelpers.js#L145-L151 |
28,845 | incompl/cloak | examples/grow21/client/js/Game.js | function(msg) {
var gameOverElement = document.getElementById('gameOver'),
gameOverMsgElement = document.getElementById('gameOverMsg'),
waitingForPlayerElem = document.getElementById('waitingForPlayer');
if (msg === false) {
gameOverElement.style.display = 'none';
}
else {
gameOverMsgElement.innerText = msg;
gameOverElement.style.display = 'block';
waitingForPlayerElem.style.display = 'none';
}
} | javascript | function(msg) {
var gameOverElement = document.getElementById('gameOver'),
gameOverMsgElement = document.getElementById('gameOverMsg'),
waitingForPlayerElem = document.getElementById('waitingForPlayer');
if (msg === false) {
gameOverElement.style.display = 'none';
}
else {
gameOverMsgElement.innerText = msg;
gameOverElement.style.display = 'block';
waitingForPlayerElem.style.display = 'none';
}
} | [
"function",
"(",
"msg",
")",
"{",
"var",
"gameOverElement",
"=",
"document",
".",
"getElementById",
"(",
"'gameOver'",
")",
",",
"gameOverMsgElement",
"=",
"document",
".",
"getElementById",
"(",
"'gameOverMsg'",
")",
",",
"waitingForPlayerElem",
"=",
"document",
... | If passed "false", hides the gameOver dialog, otherwise displays string | [
"If",
"passed",
"false",
"hides",
"the",
"gameOver",
"dialog",
"otherwise",
"displays",
"string"
] | fc5c8382c4fdb8de129af4f54287aac09ce75cc8 | https://github.com/incompl/cloak/blob/fc5c8382c4fdb8de129af4f54287aac09ce75cc8/examples/grow21/client/js/Game.js#L271-L283 | |
28,846 | wombatsecurity/dust-loader-complete | index.js | loader | function loader(source) {
// dust files don't have side effects, so loader results are cacheable
if (this.cacheable) this.cacheable();
// Set up default options & override them with other options
const default_options = {
root: '',
dustAlias: 'dustjs-linkedin',
namingFn: defaultNamingFunction,
preserveWhitespace: false,
wrapOutput: false,
verbose: false,
ignoreImages: false,
excludeImageRegex: undefined
};
// webpack 4 'this.options' was deprecated in webpack 3 and removed in webpack 4
// if you want to use global loader options, use dust-loader-complete < v4.0.0
// var query = this.options || this.query || {};
// var global_options = query['dust-loader-complete'] || {};
// get user supplied loader options from `this.query`
const loader_options = getOptions(this) || {};
// merge user options with default options
const options = Object.assign({}, default_options, loader_options);
// Fix slashes & resolve root
options.root = path.resolve(options.root.replace('/', path.sep));
// Get the path
const template_path = path.relative(options.root, this.resourcePath);
// Create the template name
const name = options.namingFn(template_path, options);
// Log
log(options, 'Loading DustJS module from "' + template_path + '": naming template "' + name + '"');
// Find different styles of dependencies
const deps = [];
// Find regular dust partials, updating the source as needed for relatively-pathed partials
source = findPartials(source, template_path + '/../', options, deps);
// Find image dependencies
if (!options.ignoreImages) {
source = findImages(name, source, deps, options);
}
// Find require comments
findRequireComments(source, template_path + '/../', options, deps);
// Do not trim whitespace in case preserveWhitespace option is enabled
dust.config.whitespace = options.preserveWhitespace;
// Compile the template
const template = dust.compile(source, name);
// Build the returned string
let returnedString;
if (options.wrapOutput) {
returnedString = "var dust = require('" + options.dustAlias + "/lib/dust'); "
+ deps.join(' ') + template
+ "var fn = " + defaultWrapperGenerator(name)
+ '; fn.templateName = "' + name + '"; '
+ "module.exports = fn;";
} else {
returnedString = "var dust = require('" + options.dustAlias + "'); "
+ deps.join(' ')
+ 'var template = ' + template + ';'
+ 'template.templateName = "' + name + '";'
+ "module.exports = template;";
}
// Return the string to be used
return returnedString
} | javascript | function loader(source) {
// dust files don't have side effects, so loader results are cacheable
if (this.cacheable) this.cacheable();
// Set up default options & override them with other options
const default_options = {
root: '',
dustAlias: 'dustjs-linkedin',
namingFn: defaultNamingFunction,
preserveWhitespace: false,
wrapOutput: false,
verbose: false,
ignoreImages: false,
excludeImageRegex: undefined
};
// webpack 4 'this.options' was deprecated in webpack 3 and removed in webpack 4
// if you want to use global loader options, use dust-loader-complete < v4.0.0
// var query = this.options || this.query || {};
// var global_options = query['dust-loader-complete'] || {};
// get user supplied loader options from `this.query`
const loader_options = getOptions(this) || {};
// merge user options with default options
const options = Object.assign({}, default_options, loader_options);
// Fix slashes & resolve root
options.root = path.resolve(options.root.replace('/', path.sep));
// Get the path
const template_path = path.relative(options.root, this.resourcePath);
// Create the template name
const name = options.namingFn(template_path, options);
// Log
log(options, 'Loading DustJS module from "' + template_path + '": naming template "' + name + '"');
// Find different styles of dependencies
const deps = [];
// Find regular dust partials, updating the source as needed for relatively-pathed partials
source = findPartials(source, template_path + '/../', options, deps);
// Find image dependencies
if (!options.ignoreImages) {
source = findImages(name, source, deps, options);
}
// Find require comments
findRequireComments(source, template_path + '/../', options, deps);
// Do not trim whitespace in case preserveWhitespace option is enabled
dust.config.whitespace = options.preserveWhitespace;
// Compile the template
const template = dust.compile(source, name);
// Build the returned string
let returnedString;
if (options.wrapOutput) {
returnedString = "var dust = require('" + options.dustAlias + "/lib/dust'); "
+ deps.join(' ') + template
+ "var fn = " + defaultWrapperGenerator(name)
+ '; fn.templateName = "' + name + '"; '
+ "module.exports = fn;";
} else {
returnedString = "var dust = require('" + options.dustAlias + "'); "
+ deps.join(' ')
+ 'var template = ' + template + ';'
+ 'template.templateName = "' + name + '";'
+ "module.exports = template;";
}
// Return the string to be used
return returnedString
} | [
"function",
"loader",
"(",
"source",
")",
"{",
"// dust files don't have side effects, so loader results are cacheable",
"if",
"(",
"this",
".",
"cacheable",
")",
"this",
".",
"cacheable",
"(",
")",
";",
"// Set up default options & override them with other options",
"const",... | Main loader function | [
"Main",
"loader",
"function"
] | 43da8de04eafa6efd4a951143b728f283327858e | https://github.com/wombatsecurity/dust-loader-complete/blob/43da8de04eafa6efd4a951143b728f283327858e/index.js#L11-L89 |
28,847 | wombatsecurity/dust-loader-complete | index.js | findPartials | function findPartials(source, source_path, options, deps) {
var reg = /({>\s?")([^"{}]+)("[\s\S]*?\/})/g, // matches dust partial syntax
result = null, partial,
dep, name, replace;
// search source & add a dependency for each match
while ((result = reg.exec(source)) !== null) {
partial = {
prefix: result[1],
name: result[2],
suffix: result[3]
};
// add to dependencies
name = addDustDependency(partial.name, source_path, options, deps);
// retrieve newest dependency
dep = deps[deps.length - 1];
// log
log(options, 'found partial dependency "' + partial.name + '"');
// if the partial has been renamed, update the name in the template
if (name != partial.name) {
log(options, 'renaming partial "' + partial.name + '" to "' + name + '"')
// build replacement for partial tag
replace = partial.prefix + name + partial.suffix;
// replace the original partial path with the new "absolute" path (relative to root)
source = source.substring(0, result.index) + replace + source.substring(result.index + result[0].length);
// update regex index
reg.lastIndex += (replace.length - result[0].length);
}
}
return source;
} | javascript | function findPartials(source, source_path, options, deps) {
var reg = /({>\s?")([^"{}]+)("[\s\S]*?\/})/g, // matches dust partial syntax
result = null, partial,
dep, name, replace;
// search source & add a dependency for each match
while ((result = reg.exec(source)) !== null) {
partial = {
prefix: result[1],
name: result[2],
suffix: result[3]
};
// add to dependencies
name = addDustDependency(partial.name, source_path, options, deps);
// retrieve newest dependency
dep = deps[deps.length - 1];
// log
log(options, 'found partial dependency "' + partial.name + '"');
// if the partial has been renamed, update the name in the template
if (name != partial.name) {
log(options, 'renaming partial "' + partial.name + '" to "' + name + '"')
// build replacement for partial tag
replace = partial.prefix + name + partial.suffix;
// replace the original partial path with the new "absolute" path (relative to root)
source = source.substring(0, result.index) + replace + source.substring(result.index + result[0].length);
// update regex index
reg.lastIndex += (replace.length - result[0].length);
}
}
return source;
} | [
"function",
"findPartials",
"(",
"source",
",",
"source_path",
",",
"options",
",",
"deps",
")",
"{",
"var",
"reg",
"=",
"/",
"({>\\s?\")([^\"{}]+)(\"[\\s\\S]*?\\/})",
"/",
"g",
",",
"// matches dust partial syntax",
"result",
"=",
"null",
",",
"partial",
",",
"... | Find DustJS partials | [
"Find",
"DustJS",
"partials"
] | 43da8de04eafa6efd4a951143b728f283327858e | https://github.com/wombatsecurity/dust-loader-complete/blob/43da8de04eafa6efd4a951143b728f283327858e/index.js#L104-L142 |
28,848 | wombatsecurity/dust-loader-complete | index.js | determinePartialName | function determinePartialName(partial_path, source_path, options) {
var match, rel, abs,
path_reg = /(\.\.?\/)?(.+)/;
// use a regex to find whether or not this is a relative path
match = path_reg.exec(partial_path);
if (match[1]) {
// use os-appropriate separator
rel = partial_path.replace('/', path.sep);
// join the root, the source_path, and the relative path, then find the relative path from the root
// this is the new "absolute"" path
abs = path.relative(options.root, path.join(options.root, source_path, rel));
} else {
// use os-appropriate separator
abs = match[2].replace('/', path.sep);
}
// now use the naming function to get the name
return options.namingFn(abs, options);
} | javascript | function determinePartialName(partial_path, source_path, options) {
var match, rel, abs,
path_reg = /(\.\.?\/)?(.+)/;
// use a regex to find whether or not this is a relative path
match = path_reg.exec(partial_path);
if (match[1]) {
// use os-appropriate separator
rel = partial_path.replace('/', path.sep);
// join the root, the source_path, and the relative path, then find the relative path from the root
// this is the new "absolute"" path
abs = path.relative(options.root, path.join(options.root, source_path, rel));
} else {
// use os-appropriate separator
abs = match[2].replace('/', path.sep);
}
// now use the naming function to get the name
return options.namingFn(abs, options);
} | [
"function",
"determinePartialName",
"(",
"partial_path",
",",
"source_path",
",",
"options",
")",
"{",
"var",
"match",
",",
"rel",
",",
"abs",
",",
"path_reg",
"=",
"/",
"(\\.\\.?\\/)?(.+)",
"/",
";",
"// use a regex to find whether or not this is a relative path ",
... | Figure out the name for a dust dependency | [
"Figure",
"out",
"the",
"name",
"for",
"a",
"dust",
"dependency"
] | 43da8de04eafa6efd4a951143b728f283327858e | https://github.com/wombatsecurity/dust-loader-complete/blob/43da8de04eafa6efd4a951143b728f283327858e/index.js#L228-L248 |
28,849 | incompl/cloak | src/server/cloak/index.js | function(configArg) {
config = _.extend({}, defaults);
events = {};
_(configArg).forEach(function(val, key) {
if (key === 'room' ||
key === 'lobby') {
events[key] = val;
}
else {
config[key] = val;
}
});
} | javascript | function(configArg) {
config = _.extend({}, defaults);
events = {};
_(configArg).forEach(function(val, key) {
if (key === 'room' ||
key === 'lobby') {
events[key] = val;
}
else {
config[key] = val;
}
});
} | [
"function",
"(",
"configArg",
")",
"{",
"config",
"=",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"defaults",
")",
";",
"events",
"=",
"{",
"}",
";",
"_",
"(",
"configArg",
")",
".",
"forEach",
"(",
"function",
"(",
"val",
",",
"key",
")",
"{",
"i... | configure the server | [
"configure",
"the",
"server"
] | fc5c8382c4fdb8de129af4f54287aac09ce75cc8 | https://github.com/incompl/cloak/blob/fc5c8382c4fdb8de129af4f54287aac09ce75cc8/src/server/cloak/index.js#L53-L67 | |
28,850 | nonplus/angular-ui-router-default | sample/common/utils/utils-service.js | findById | function findById(a, id) {
for (var i = 0; i < a.length; i++) {
if (a[i].id == id) return a[i];
}
return null;
} | javascript | function findById(a, id) {
for (var i = 0; i < a.length; i++) {
if (a[i].id == id) return a[i];
}
return null;
} | [
"function",
"findById",
"(",
"a",
",",
"id",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"a",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"a",
"[",
"i",
"]",
".",
"id",
"==",
"id",
")",
"return",
"a",
"[",
"i",
"]... | Util for finding an object by its 'id' property among an array | [
"Util",
"for",
"finding",
"an",
"object",
"by",
"its",
"id",
"property",
"among",
"an",
"array"
] | 8d9f618577f8a81950e3a47dda32264e1514c0f3 | https://github.com/nonplus/angular-ui-router-default/blob/8d9f618577f8a81950e3a47dda32264e1514c0f3/sample/common/utils/utils-service.js#L8-L13 |
28,851 | nonplus/angular-ui-router-default | sample/common/utils/utils-service.js | newRandomKey | function newRandomKey(coll, key, currentKey){
var randKey;
do {
randKey = coll[Math.floor(coll.length * Math.random())][key];
} while (randKey == currentKey);
return randKey;
} | javascript | function newRandomKey(coll, key, currentKey){
var randKey;
do {
randKey = coll[Math.floor(coll.length * Math.random())][key];
} while (randKey == currentKey);
return randKey;
} | [
"function",
"newRandomKey",
"(",
"coll",
",",
"key",
",",
"currentKey",
")",
"{",
"var",
"randKey",
";",
"do",
"{",
"randKey",
"=",
"coll",
"[",
"Math",
".",
"floor",
"(",
"coll",
".",
"length",
"*",
"Math",
".",
"random",
"(",
")",
")",
"]",
"[",
... | Util for returning a random key from a collection that also isn't the current key | [
"Util",
"for",
"returning",
"a",
"random",
"key",
"from",
"a",
"collection",
"that",
"also",
"isn",
"t",
"the",
"current",
"key"
] | 8d9f618577f8a81950e3a47dda32264e1514c0f3 | https://github.com/nonplus/angular-ui-router-default/blob/8d9f618577f8a81950e3a47dda32264e1514c0f3/sample/common/utils/utils-service.js#L16-L22 |
28,852 | cludden/ajv-moment | lib/index.js | plugin | function plugin(options) {
if (!options || typeof options !== 'object') {
throw new Error('AjvMoment#plugin requires options');
}
if (!options.ajv) {
throw new Error(`AjvMoment#plugin options requries an 'ajv' attribute (ajv instance)`);
}
if (!options.moment) {
throw new Error(`AjvMoment#plugin options requries a 'moment' attribute (moment.js)`);
}
const { ajv, moment } = options;
ajv.moment = moment;
const keywordSettings = {
type: 'string',
statements: true,
errors: true,
inline
};
if (ajv) {
ajv.addKeyword('moment', keywordSettings);
}
return keywordSettings;
} | javascript | function plugin(options) {
if (!options || typeof options !== 'object') {
throw new Error('AjvMoment#plugin requires options');
}
if (!options.ajv) {
throw new Error(`AjvMoment#plugin options requries an 'ajv' attribute (ajv instance)`);
}
if (!options.moment) {
throw new Error(`AjvMoment#plugin options requries a 'moment' attribute (moment.js)`);
}
const { ajv, moment } = options;
ajv.moment = moment;
const keywordSettings = {
type: 'string',
statements: true,
errors: true,
inline
};
if (ajv) {
ajv.addKeyword('moment', keywordSettings);
}
return keywordSettings;
} | [
"function",
"plugin",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"options",
"||",
"typeof",
"options",
"!==",
"'object'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'AjvMoment#plugin requires options'",
")",
";",
"}",
"if",
"(",
"!",
"options",
".",
"ajv",
... | Configure the plugin by attaching moment to the ajv instance and defining the
'moment' custom keyword
@param {Object} options - plugin options
@return {Object} keywordSettings | [
"Configure",
"the",
"plugin",
"by",
"attaching",
"moment",
"to",
"the",
"ajv",
"instance",
"and",
"defining",
"the",
"moment",
"custom",
"keyword"
] | f441e7c28e8bab24af3ce2682727356535f83834 | https://github.com/cludden/ajv-moment/blob/f441e7c28e8bab24af3ce2682727356535f83834/lib/index.js#L13-L35 |
28,853 | incompl/cloak | examples/grow21/client/lib/crafty.js | getTimestamps | function getTimestamps() {
try {
var trans = db.transaction(['save'], "read"),
store = trans.objectStore('save'),
request = store.getAll();
request.onsuccess = function (e) {
var i = 0, a = event.target.result, l = a.length;
for (; i < l; i++) {
timestamps[a[i].key] = a[i].timestamp;
}
};
}
catch (e) {
}
} | javascript | function getTimestamps() {
try {
var trans = db.transaction(['save'], "read"),
store = trans.objectStore('save'),
request = store.getAll();
request.onsuccess = function (e) {
var i = 0, a = event.target.result, l = a.length;
for (; i < l; i++) {
timestamps[a[i].key] = a[i].timestamp;
}
};
}
catch (e) {
}
} | [
"function",
"getTimestamps",
"(",
")",
"{",
"try",
"{",
"var",
"trans",
"=",
"db",
".",
"transaction",
"(",
"[",
"'save'",
"]",
",",
"\"read\"",
")",
",",
"store",
"=",
"trans",
".",
"objectStore",
"(",
"'save'",
")",
",",
"request",
"=",
"store",
".... | get all the timestamps for existing keys | [
"get",
"all",
"the",
"timestamps",
"for",
"existing",
"keys"
] | fc5c8382c4fdb8de129af4f54287aac09ce75cc8 | https://github.com/incompl/cloak/blob/fc5c8382c4fdb8de129af4f54287aac09ce75cc8/examples/grow21/client/lib/crafty.js#L4080-L4094 |
28,854 | incompl/cloak | examples/grow21/client/lib/crafty.js | function (e) {
var e = e || window.event;
if (typeof callback === 'function') {
callback.call(ctx, e);
}
} | javascript | function (e) {
var e = e || window.event;
if (typeof callback === 'function') {
callback.call(ctx, e);
}
} | [
"function",
"(",
"e",
")",
"{",
"var",
"e",
"=",
"e",
"||",
"window",
".",
"event",
";",
"if",
"(",
"typeof",
"callback",
"===",
"'function'",
")",
"{",
"callback",
".",
"call",
"(",
"ctx",
",",
"e",
")",
";",
"}",
"}"
] | save anonymous function to be able to remove | [
"save",
"anonymous",
"function",
"to",
"be",
"able",
"to",
"remove"
] | fc5c8382c4fdb8de129af4f54287aac09ce75cc8 | https://github.com/incompl/cloak/blob/fc5c8382c4fdb8de129af4f54287aac09ce75cc8/examples/grow21/client/lib/crafty.js#L4685-L4691 | |
28,855 | incompl/cloak | examples/grow21/client/lib/crafty.js | function(a, b, target){
if (target == null)
target={}
// Doing it in this order means we can use either a or b as the target, with no conflict
// Round resulting values to integers; down for xy, up for wh
// Would be slightly off if negative w, h were allowed
target._h = Math.max(a._y + a._h, b._y + b._h);
target._w = Math.max(a._x + a._w, b._x + b._w);
target._x = ~~Math.min(a._x, b._x);
target._y = ~~Math.min(a._y, b._y);
target._w -= target._x;
target._h -= target._y
target._w = (target._w == ~~target._w) ? target._w : ~~target._w + 1 | 0;
target._h = (target._h == ~~target._h) ? target._h : ~~target._h + 1 | 0;
return target
} | javascript | function(a, b, target){
if (target == null)
target={}
// Doing it in this order means we can use either a or b as the target, with no conflict
// Round resulting values to integers; down for xy, up for wh
// Would be slightly off if negative w, h were allowed
target._h = Math.max(a._y + a._h, b._y + b._h);
target._w = Math.max(a._x + a._w, b._x + b._w);
target._x = ~~Math.min(a._x, b._x);
target._y = ~~Math.min(a._y, b._y);
target._w -= target._x;
target._h -= target._y
target._w = (target._w == ~~target._w) ? target._w : ~~target._w + 1 | 0;
target._h = (target._h == ~~target._h) ? target._h : ~~target._h + 1 | 0;
return target
} | [
"function",
"(",
"a",
",",
"b",
",",
"target",
")",
"{",
"if",
"(",
"target",
"==",
"null",
")",
"target",
"=",
"{",
"}",
"// Doing it in this order means we can use either a or b as the target, with no conflict",
"// Round resulting values to integers; down for xy, up for wh... | Finds smallest rectangles that overlaps a and b, merges them into target | [
"Finds",
"smallest",
"rectangles",
"that",
"overlaps",
"a",
"and",
"b",
"merges",
"them",
"into",
"target"
] | fc5c8382c4fdb8de129af4f54287aac09ce75cc8 | https://github.com/incompl/cloak/blob/fc5c8382c4fdb8de129af4f54287aac09ce75cc8/examples/grow21/client/lib/crafty.js#L7798-L7813 | |
28,856 | incompl/cloak | examples/grow21/client/lib/crafty.js | function(){
var rect, obj, i;
for (i=0, l=changed_objs.length; i<l; i++){
obj = changed_objs[i];
rect = obj._mbr || obj;
if (obj.staleRect == null)
obj.staleRect = {}
obj.staleRect._x = rect._x;
obj.staleRect._y = rect._y;
obj.staleRect._w = rect._w;
obj.staleRect._h = rect._h;
obj._changed = false
}
changed_objs.length = 0;
dirty_rects.length = 0
} | javascript | function(){
var rect, obj, i;
for (i=0, l=changed_objs.length; i<l; i++){
obj = changed_objs[i];
rect = obj._mbr || obj;
if (obj.staleRect == null)
obj.staleRect = {}
obj.staleRect._x = rect._x;
obj.staleRect._y = rect._y;
obj.staleRect._w = rect._w;
obj.staleRect._h = rect._h;
obj._changed = false
}
changed_objs.length = 0;
dirty_rects.length = 0
} | [
"function",
"(",
")",
"{",
"var",
"rect",
",",
"obj",
",",
"i",
";",
"for",
"(",
"i",
"=",
"0",
",",
"l",
"=",
"changed_objs",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"obj",
"=",
"changed_objs",
"[",
"i",
"]",
";",
"rec... | cleans up current dirty state, stores stale state for future passes | [
"cleans",
"up",
"current",
"dirty",
"state",
"stores",
"stale",
"state",
"for",
"future",
"passes"
] | fc5c8382c4fdb8de129af4f54287aac09ce75cc8 | https://github.com/incompl/cloak/blob/fc5c8382c4fdb8de129af4f54287aac09ce75cc8/examples/grow21/client/lib/crafty.js#L7816-L7833 | |
28,857 | incompl/cloak | examples/grow21/client/lib/crafty.js | function(a, b){
return (a._x < b._x + b._w && a._y < b._y + b._h
&& a._x + a._w > b._x && a._y + a._h > b._y)
} | javascript | function(a, b){
return (a._x < b._x + b._w && a._y < b._y + b._h
&& a._x + a._w > b._x && a._y + a._h > b._y)
} | [
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"(",
"a",
".",
"_x",
"<",
"b",
".",
"_x",
"+",
"b",
".",
"_w",
"&&",
"a",
".",
"_y",
"<",
"b",
".",
"_y",
"+",
"b",
".",
"_h",
"&&",
"a",
".",
"_x",
"+",
"a",
".",
"_w",
">",
"b",
... | Checks whether two rectangles overlap | [
"Checks",
"whether",
"two",
"rectangles",
"overlap"
] | fc5c8382c4fdb8de129af4f54287aac09ce75cc8 | https://github.com/incompl/cloak/blob/fc5c8382c4fdb8de129af4f54287aac09ce75cc8/examples/grow21/client/lib/crafty.js#L7862-L7865 | |
28,858 | tarunc/intercom.io | lib/IntercomError.js | IntercomError | function IntercomError(message, errors) {
AbstractError.apply(this, arguments);
this.name = 'IntercomError';
this.message = message;
this.errors = errors;
} | javascript | function IntercomError(message, errors) {
AbstractError.apply(this, arguments);
this.name = 'IntercomError';
this.message = message;
this.errors = errors;
} | [
"function",
"IntercomError",
"(",
"message",
",",
"errors",
")",
"{",
"AbstractError",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"this",
".",
"name",
"=",
"'IntercomError'",
";",
"this",
".",
"message",
"=",
"message",
";",
"this",
".",
"err... | `IntercomError` error.
@api private | [
"IntercomError",
"error",
"."
] | be2dedcbbdf456a02db09e8dcb2fba506c708088 | https://github.com/tarunc/intercom.io/blob/be2dedcbbdf456a02db09e8dcb2fba506c708088/lib/IntercomError.js#L29-L34 |
28,859 | incompl/cloak | examples/grow21/client/js/Target.js | function() {
var valid = false;
var destroy = true;
var target = this;
Crafty('Card').each(function() {
if (this.intersect(target.x + target.w + game.config.cardBuffer, target.y, target.w, target.h) ||
this.intersect(target.x - target.w - game.config.cardBuffer, target.y, target.w, target.h) ||
this.intersect(target.x, target.y + target.h + game.config.cardBuffer, target.w, target.h) ||
this.intersect(target.x, target.y - target.h - game.config.cardBuffer, target.w, target.h)
) {
valid = true;
destroy = false;
}
if (this.intersect(target.x, target.y, target.w, target.h)) {
destroy = false;
}
});
if (valid) {
this.used = false;
}
else if (destroy) {
this.destroy();
var currentTarget = this;
game.targets = _.reject(game.targets, function(thisTarget) { return _.isEqual(thisTarget, currentTarget); });
}
} | javascript | function() {
var valid = false;
var destroy = true;
var target = this;
Crafty('Card').each(function() {
if (this.intersect(target.x + target.w + game.config.cardBuffer, target.y, target.w, target.h) ||
this.intersect(target.x - target.w - game.config.cardBuffer, target.y, target.w, target.h) ||
this.intersect(target.x, target.y + target.h + game.config.cardBuffer, target.w, target.h) ||
this.intersect(target.x, target.y - target.h - game.config.cardBuffer, target.w, target.h)
) {
valid = true;
destroy = false;
}
if (this.intersect(target.x, target.y, target.w, target.h)) {
destroy = false;
}
});
if (valid) {
this.used = false;
}
else if (destroy) {
this.destroy();
var currentTarget = this;
game.targets = _.reject(game.targets, function(thisTarget) { return _.isEqual(thisTarget, currentTarget); });
}
} | [
"function",
"(",
")",
"{",
"var",
"valid",
"=",
"false",
";",
"var",
"destroy",
"=",
"true",
";",
"var",
"target",
"=",
"this",
";",
"Crafty",
"(",
"'Card'",
")",
".",
"each",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"intersect",
"... | if I am next to a card, then refresh me, I'm a valid target if I'm under a card, don't refresh me but I should continue to exist otherwise destroy me | [
"if",
"I",
"am",
"next",
"to",
"a",
"card",
"then",
"refresh",
"me",
"I",
"m",
"a",
"valid",
"target",
"if",
"I",
"m",
"under",
"a",
"card",
"don",
"t",
"refresh",
"me",
"but",
"I",
"should",
"continue",
"to",
"exist",
"otherwise",
"destroy",
"me"
] | fc5c8382c4fdb8de129af4f54287aac09ce75cc8 | https://github.com/incompl/cloak/blob/fc5c8382c4fdb8de129af4f54287aac09ce75cc8/examples/grow21/client/js/Target.js#L110-L135 | |
28,860 | tarunc/intercom.io | lib/intercom.io.js | Intercom | function Intercom(appId, apiKey, options) {
// Overload the contractor
// Parse out single option objects
if (_.isObject(appId) && !_.isString(appId) && ((appId.apiKey && appId.appId) || appId.personalAccessToken)) {
apiKey = appId.apiKey || '';
options = _.omit(appId, 'apiKey', 'appId');
appId = appId.appId || appId.personalAccessToken;
}
// Preform some sane validation checks and throw errors
// We need the appId
if (!appId) {
throw new IntercomError('Invalid App ID: ' + appId);
}
// Copy over the relavant data
this.appId = appId;
this.apiKey = apiKey || '';
// Extend the defaults
this.options = _.defaults(options || {}, Intercom.defaultOptions);
// Contruct the endpoint with the correct auth from the appId and apiKey
this.endpoint = this.options.endpoint;
} | javascript | function Intercom(appId, apiKey, options) {
// Overload the contractor
// Parse out single option objects
if (_.isObject(appId) && !_.isString(appId) && ((appId.apiKey && appId.appId) || appId.personalAccessToken)) {
apiKey = appId.apiKey || '';
options = _.omit(appId, 'apiKey', 'appId');
appId = appId.appId || appId.personalAccessToken;
}
// Preform some sane validation checks and throw errors
// We need the appId
if (!appId) {
throw new IntercomError('Invalid App ID: ' + appId);
}
// Copy over the relavant data
this.appId = appId;
this.apiKey = apiKey || '';
// Extend the defaults
this.options = _.defaults(options || {}, Intercom.defaultOptions);
// Contruct the endpoint with the correct auth from the appId and apiKey
this.endpoint = this.options.endpoint;
} | [
"function",
"Intercom",
"(",
"appId",
",",
"apiKey",
",",
"options",
")",
"{",
"// Overload the contractor",
"// Parse out single option objects",
"if",
"(",
"_",
".",
"isObject",
"(",
"appId",
")",
"&&",
"!",
"_",
".",
"isString",
"(",
"appId",
")",
"&&",
"... | `Intercom` constructor.
@param {String} appId - your app Id OR personalAccessToken
@param {String} apiKey - your api key
@param {Object} options - an options object
@api public | [
"Intercom",
"constructor",
"."
] | be2dedcbbdf456a02db09e8dcb2fba506c708088 | https://github.com/tarunc/intercom.io/blob/be2dedcbbdf456a02db09e8dcb2fba506c708088/lib/intercom.io.js#L31-L55 |
28,861 | ruslang02/atomos | front/api/0_wm.js | getError | function getError(errno, app) {
let errObj = {
errno: errno,
message: errors[errno].replace('$app', app)
};
return errObj.message;
} | javascript | function getError(errno, app) {
let errObj = {
errno: errno,
message: errors[errno].replace('$app', app)
};
return errObj.message;
} | [
"function",
"getError",
"(",
"errno",
",",
"app",
")",
"{",
"let",
"errObj",
"=",
"{",
"errno",
":",
"errno",
",",
"message",
":",
"errors",
"[",
"errno",
"]",
".",
"replace",
"(",
"'$app'",
",",
"app",
")",
"}",
";",
"return",
"errObj",
".",
"mess... | Contains all options that windows have. NOT RECOMMENDED to rely on. | [
"Contains",
"all",
"options",
"that",
"windows",
"have",
".",
"NOT",
"RECOMMENDED",
"to",
"rely",
"on",
"."
] | 6b9c2b744feed60a838affb083407f565aed3213 | https://github.com/ruslang02/atomos/blob/6b9c2b744feed60a838affb083407f565aed3213/front/api/0_wm.js#L33-L39 |
28,862 | demian85/gnip | lib/index.js | function (options) {
EventEmitter.call(this);
var self = this;
self.options = _.extend({
user: '',
password: '',
userAgent: null,
url: null,
debug: false,
parser: JSONBigInt
}, options || {});
self._req = null;
self.parser = new JSONParser(self.options.parser);
self.parser.on('object', function (object) {
self.emit('object', object);
if (object.error) self.emit('error', new Error('Stream response error: ' + (object.error.message || '-')));
else if (object['delete']) self.emit('delete', object);
else if (object.body || object.text) self.emit('tweet', object);
});
self.parser.on('error', function (err) {
self.emit('error', err);
});
} | javascript | function (options) {
EventEmitter.call(this);
var self = this;
self.options = _.extend({
user: '',
password: '',
userAgent: null,
url: null,
debug: false,
parser: JSONBigInt
}, options || {});
self._req = null;
self.parser = new JSONParser(self.options.parser);
self.parser.on('object', function (object) {
self.emit('object', object);
if (object.error) self.emit('error', new Error('Stream response error: ' + (object.error.message || '-')));
else if (object['delete']) self.emit('delete', object);
else if (object.body || object.text) self.emit('tweet', object);
});
self.parser.on('error', function (err) {
self.emit('error', err);
});
} | [
"function",
"(",
"options",
")",
"{",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"var",
"self",
"=",
"this",
";",
"self",
".",
"options",
"=",
"_",
".",
"extend",
"(",
"{",
"user",
":",
"''",
",",
"password",
":",
"''",
",",
"userAgent",
... | Connects to Gnip streaming api and tracks keywords.
@param options Object with the following properties:
- (String) user
- (String) password
- (String) userAgent
- (String) url
- (Boolean) debug
Events:
- data: function(String data) {...}
- object: function(Object object) {...}
- tweet: function(Object tweet) {...}
- delete: function(Number id) {...}
- error: function(Error error) {...}
- ready: function() {...}
- end: function() {...} | [
"Connects",
"to",
"Gnip",
"streaming",
"api",
"and",
"tracks",
"keywords",
"."
] | ec37f9131094cf4b829f6727cd2f45b14c5c21e0 | https://github.com/demian85/gnip/blob/ec37f9131094cf4b829f6727cd2f45b14c5c21e0/lib/index.js#L35-L61 | |
28,863 | benmills/robotskirt | benchmark/index.js | benchBatch | function benchBatch(targets, cb, idx) {
idx |= 0;
if (targets.length == 0) return cb(idx);
var target = targets.shift();
process.stdout.write(util.format('[%s] ', idx+1));
try {
main.bench(target.name, target.func);
idx++;
} catch (err) {
console.log('%s failed!', target.name);
}
//No more targets, no need to wait
if (targets.length == 0) return cb(idx);
//We need to wait some seconds before the next test,
//or the results could vary depending on the order
setTimeout(function() {
benchBatch(targets, cb, idx); //Yeah, recursivity...
}, 10000);
} | javascript | function benchBatch(targets, cb, idx) {
idx |= 0;
if (targets.length == 0) return cb(idx);
var target = targets.shift();
process.stdout.write(util.format('[%s] ', idx+1));
try {
main.bench(target.name, target.func);
idx++;
} catch (err) {
console.log('%s failed!', target.name);
}
//No more targets, no need to wait
if (targets.length == 0) return cb(idx);
//We need to wait some seconds before the next test,
//or the results could vary depending on the order
setTimeout(function() {
benchBatch(targets, cb, idx); //Yeah, recursivity...
}, 10000);
} | [
"function",
"benchBatch",
"(",
"targets",
",",
"cb",
",",
"idx",
")",
"{",
"idx",
"|=",
"0",
";",
"if",
"(",
"targets",
".",
"length",
"==",
"0",
")",
"return",
"cb",
"(",
"idx",
")",
";",
"var",
"target",
"=",
"targets",
".",
"shift",
"(",
")",
... | Benchmark a series of target functions | [
"Benchmark",
"a",
"series",
"of",
"target",
"functions"
] | b070272e5ee934cf1d12399e4425deb2dd1dad84 | https://github.com/benmills/robotskirt/blob/b070272e5ee934cf1d12399e4425deb2dd1dad84/benchmark/index.js#L135-L156 |
28,864 | asciidisco/grunt-imagine | tasks/inlineImg.js | function(cssFile, config, cb) {
var imgRegex = /url\s?\(['"]?(.*?)(?=['"]?\))/gi,
css = null,
img = null,
inlineImgPath = null,
imgPath = null,
base = _.isUndefined(config.base) ? '' : config.base,
processedImages = 0,
match = [],
mimetype = null;
// read css file contents
css = fs.readFileSync(cssFile, 'utf-8');
// find all occurences of images in the css file
while (match = imgRegex.exec(css)) {
imgPath = path.join(path.dirname(cssFile), match[1]);
inlineImgPath = imgPath;
// remove any query params from path (for cache busting etc.)
if (imgPath.lastIndexOf('?') !== -1) {
inlineImgPath = imgPath.substr(0, imgPath.lastIndexOf('?'));
}
// make sure that were only importing images
if (path.extname(inlineImgPath) !== '.css') {
try {
// try to load the file without a given base path,
// if that doesn´t work, try with
try {
img = fs.readFileSync(inlineImgPath, 'base64');
} catch (err) {
img = fs.readFileSync(base + '/' + path.basename(inlineImgPath), 'base64');
}
// replace file with bas64 data
mimetype = mime.lookup(inlineImgPath);
// check file size and ie8 compat mode
if (img.length > 32768 && config.ie8 === true) {
// i hate to write this, but can´t wrap my head around
// how to do this better: DO NOTHING
} else {
css = css.replace(match[1], 'data:' + mimetype + ';base64,' + img);
processedImages++;
}
} catch (err) {
// Catch image file not found error
grunt.verbose.error('Image file not found: ' + match[1]);
}
}
}
// check if a callback is given
if (_.isFunction(cb)) {
grunt.log.ok('Inlined: ' + processedImages + ' Images in file: ' + cssFile);
cb(cssFile, css);
}
} | javascript | function(cssFile, config, cb) {
var imgRegex = /url\s?\(['"]?(.*?)(?=['"]?\))/gi,
css = null,
img = null,
inlineImgPath = null,
imgPath = null,
base = _.isUndefined(config.base) ? '' : config.base,
processedImages = 0,
match = [],
mimetype = null;
// read css file contents
css = fs.readFileSync(cssFile, 'utf-8');
// find all occurences of images in the css file
while (match = imgRegex.exec(css)) {
imgPath = path.join(path.dirname(cssFile), match[1]);
inlineImgPath = imgPath;
// remove any query params from path (for cache busting etc.)
if (imgPath.lastIndexOf('?') !== -1) {
inlineImgPath = imgPath.substr(0, imgPath.lastIndexOf('?'));
}
// make sure that were only importing images
if (path.extname(inlineImgPath) !== '.css') {
try {
// try to load the file without a given base path,
// if that doesn´t work, try with
try {
img = fs.readFileSync(inlineImgPath, 'base64');
} catch (err) {
img = fs.readFileSync(base + '/' + path.basename(inlineImgPath), 'base64');
}
// replace file with bas64 data
mimetype = mime.lookup(inlineImgPath);
// check file size and ie8 compat mode
if (img.length > 32768 && config.ie8 === true) {
// i hate to write this, but can´t wrap my head around
// how to do this better: DO NOTHING
} else {
css = css.replace(match[1], 'data:' + mimetype + ';base64,' + img);
processedImages++;
}
} catch (err) {
// Catch image file not found error
grunt.verbose.error('Image file not found: ' + match[1]);
}
}
}
// check if a callback is given
if (_.isFunction(cb)) {
grunt.log.ok('Inlined: ' + processedImages + ' Images in file: ' + cssFile);
cb(cssFile, css);
}
} | [
"function",
"(",
"cssFile",
",",
"config",
",",
"cb",
")",
"{",
"var",
"imgRegex",
"=",
"/",
"url\\s?\\(['\"]?(.*?)(?=['\"]?\\))",
"/",
"gi",
",",
"css",
"=",
"null",
",",
"img",
"=",
"null",
",",
"inlineImgPath",
"=",
"null",
",",
"imgPath",
"=",
"null"... | inline images as base64 in css files | [
"inline",
"images",
"as",
"base64",
"in",
"css",
"files"
] | 88d276ce9865b4a10e31879537759bd7114c3134 | https://github.com/asciidisco/grunt-imagine/blob/88d276ce9865b4a10e31879537759bd7114c3134/tasks/inlineImg.js#L10-L68 | |
28,865 | asciidisco/grunt-imagine | tasks/inlineImg.js | function(htmlFile, config, cb) {
var html = fs.readFileSync(htmlFile, 'utf-8'),
processedImages = 0,
$ = cheerio.load(html);
// grab all <img/> elements from the document
$('img').each(function (idx, elm) {
var src = $(elm).attr('src'),
imgPath = null,
img = null,
mimetype = null,
inlineImgPath = null;
// check if the image src is already a data attribute
if (src.substr(0, 5) !== 'data:') {
// figure out the image path and load it
inlineImgPath = imgPath = path.join(path.dirname(htmlFile), src);
img = fs.readFileSync(imgPath, 'base64');
mimetype = mime.lookup(inlineImgPath);
// check file size and ie8 compat mode
if (img.length > 32768 && config.ie8 === true) {
// i hate to write this, but can´t wrap my head around
// how to do this better: DO NOTHING
} else {
$(elm).attr('src', 'data:' + mimetype + ';base64,' + img);
processedImages++;
}
}
});
html = $.html();
// check if a callback is given
if (_.isFunction(cb)) {
grunt.log.ok('Inlined: ' + processedImages + ' Images in file: ' + htmlFile);
cb(htmlFile, html);
}
} | javascript | function(htmlFile, config, cb) {
var html = fs.readFileSync(htmlFile, 'utf-8'),
processedImages = 0,
$ = cheerio.load(html);
// grab all <img/> elements from the document
$('img').each(function (idx, elm) {
var src = $(elm).attr('src'),
imgPath = null,
img = null,
mimetype = null,
inlineImgPath = null;
// check if the image src is already a data attribute
if (src.substr(0, 5) !== 'data:') {
// figure out the image path and load it
inlineImgPath = imgPath = path.join(path.dirname(htmlFile), src);
img = fs.readFileSync(imgPath, 'base64');
mimetype = mime.lookup(inlineImgPath);
// check file size and ie8 compat mode
if (img.length > 32768 && config.ie8 === true) {
// i hate to write this, but can´t wrap my head around
// how to do this better: DO NOTHING
} else {
$(elm).attr('src', 'data:' + mimetype + ';base64,' + img);
processedImages++;
}
}
});
html = $.html();
// check if a callback is given
if (_.isFunction(cb)) {
grunt.log.ok('Inlined: ' + processedImages + ' Images in file: ' + htmlFile);
cb(htmlFile, html);
}
} | [
"function",
"(",
"htmlFile",
",",
"config",
",",
"cb",
")",
"{",
"var",
"html",
"=",
"fs",
".",
"readFileSync",
"(",
"htmlFile",
",",
"'utf-8'",
")",
",",
"processedImages",
"=",
"0",
",",
"$",
"=",
"cheerio",
".",
"load",
"(",
"html",
")",
";",
"/... | inline images as base64 in html files | [
"inline",
"images",
"as",
"base64",
"in",
"html",
"files"
] | 88d276ce9865b4a10e31879537759bd7114c3134 | https://github.com/asciidisco/grunt-imagine/blob/88d276ce9865b4a10e31879537759bd7114c3134/tasks/inlineImg.js#L71-L110 | |
28,866 | IonicaBizau/node-cli-pie | lib/index.js | CliPie | function CliPie(r, data, options) {
this.data = [];
this.radius = r;
this.total = 0;
this.colors = {};
this.cChar = -1;
this.options = Ul.deepMerge(options, {
flat: true
, chr: " "
, no_ansi: false
, circle_opts: {
aRatio: 1
}
, chars: "abcdefghijklnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")
});
if (Array.isArray(data)) {
data.forEach(this.add.bind(this));
} else if (data && data.constructor === Object) {
options = data;
}
} | javascript | function CliPie(r, data, options) {
this.data = [];
this.radius = r;
this.total = 0;
this.colors = {};
this.cChar = -1;
this.options = Ul.deepMerge(options, {
flat: true
, chr: " "
, no_ansi: false
, circle_opts: {
aRatio: 1
}
, chars: "abcdefghijklnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")
});
if (Array.isArray(data)) {
data.forEach(this.add.bind(this));
} else if (data && data.constructor === Object) {
options = data;
}
} | [
"function",
"CliPie",
"(",
"r",
",",
"data",
",",
"options",
")",
"{",
"this",
".",
"data",
"=",
"[",
"]",
";",
"this",
".",
"radius",
"=",
"r",
";",
"this",
".",
"total",
"=",
"0",
";",
"this",
".",
"colors",
"=",
"{",
"}",
";",
"this",
".",... | CliPie
Creates a new instance of `CliPie`.
@name CliPie
@function
@param {Number} r The radius value.
@param {Array} data An array of objects in the following format:
@param {Object} options An object containing the following fields:
- `flat` (Boolean): If `true`, flat colors will be used (default: `true`).
- `chr` (String): The character to draw the pie (default: `" "`).
- `no_ansi` (Boolean): If `true`, ansi styles will not be used.
- `legend` (Boolean): If `true`, a legend is added next to the pie.
- `display_total` (Boolean): If `true`, the total is added to the legend.
- `total_label` (String): The label for the total (default: `Total`)
- `circle_opts` (Object): The options passed to the
[`cli-circle`](https://github.com/IonicaBizau/node-cli-circle) module,
which uses the
[`cli-graph`](https://github.com/IonicaBizau/node-cli-graph) module to
build the graph.
@return {CliPie} The `CliPie` instance. | [
"CliPie",
"Creates",
"a",
"new",
"instance",
"of",
"CliPie",
"."
] | eb856a8551d2a67e89f7238a4bacb7528092a70c | https://github.com/IonicaBizau/node-cli-pie/blob/eb856a8551d2a67e89f7238a4bacb7528092a70c/lib/index.js#L32-L52 |
28,867 | demian85/gnip | lib/search.js | function (options, limiter) {
EventEmitter.call(this);
this.limiter = limiter;
this.active = false;
this.options = _.extend({
user: '',
password: '',
url: '',
query: ''
}, options || {});
} | javascript | function (options, limiter) {
EventEmitter.call(this);
this.limiter = limiter;
this.active = false;
this.options = _.extend({
user: '',
password: '',
url: '',
query: ''
}, options || {});
} | [
"function",
"(",
"options",
",",
"limiter",
")",
"{",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"limiter",
"=",
"limiter",
";",
"this",
".",
"active",
"=",
"false",
";",
"this",
".",
"options",
"=",
"_",
".",
"extend",
"(",
"... | Connects to Gnip search api and tracks keywords.
@param options Object with the following properties:
- (String) user
- (String) password
- (String) url
Events:
- object: function(Object object) {...}
- tweet: function(Object tweet) {...}
- error: function(Error error) {...}
- ready: function() {...}
- end: function() {...} | [
"Connects",
"to",
"Gnip",
"search",
"api",
"and",
"tracks",
"keywords",
"."
] | ec37f9131094cf4b829f6727cd2f45b14c5c21e0 | https://github.com/demian85/gnip/blob/ec37f9131094cf4b829f6727cd2f45b14c5c21e0/lib/search.js#L21-L34 | |
28,868 | wavesjs/waves-masters | src/core/PriorityQueue.js | swap | function swap(arr, i1, i2) {
const tmp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = tmp;
} | javascript | function swap(arr, i1, i2) {
const tmp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = tmp;
} | [
"function",
"swap",
"(",
"arr",
",",
"i1",
",",
"i2",
")",
"{",
"const",
"tmp",
"=",
"arr",
"[",
"i1",
"]",
";",
"arr",
"[",
"i1",
"]",
"=",
"arr",
"[",
"i2",
"]",
";",
"arr",
"[",
"i2",
"]",
"=",
"tmp",
";",
"}"
] | works by reference | [
"works",
"by",
"reference"
] | 385a95cf84071c7eca6d8593b6db67a02bb12d30 | https://github.com/wavesjs/waves-masters/blob/385a95cf84071c7eca6d8593b6db67a02bb12d30/src/core/PriorityQueue.js#L2-L6 |
28,869 | meganz/jodid25519 | src/jodid25519/core.js | _bigintcmp | function _bigintcmp(a, b) {
// The following code is a bit tricky to avoid code branching
var c, abs_r, mask;
var r = 0;
for (c = 15; c >= 0; c--) {
var x = a[c];
var y = b[c];
r = r + (x - y) * (1 - r * r);
// http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs
// correct for [-294967295, 294967295]
mask = r >> 31;
abs_r = (r + mask) ^ mask;
// http://stackoverflow.com/questions/596467/how-do-i-convert-a-number-to-an-integer-in-javascript
// this rounds towards zero
r = ~~((r << 1) / (abs_r + 1));
}
return r;
} | javascript | function _bigintcmp(a, b) {
// The following code is a bit tricky to avoid code branching
var c, abs_r, mask;
var r = 0;
for (c = 15; c >= 0; c--) {
var x = a[c];
var y = b[c];
r = r + (x - y) * (1 - r * r);
// http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs
// correct for [-294967295, 294967295]
mask = r >> 31;
abs_r = (r + mask) ^ mask;
// http://stackoverflow.com/questions/596467/how-do-i-convert-a-number-to-an-integer-in-javascript
// this rounds towards zero
r = ~~((r << 1) / (abs_r + 1));
}
return r;
} | [
"function",
"_bigintcmp",
"(",
"a",
",",
"b",
")",
"{",
"// The following code is a bit tricky to avoid code branching",
"var",
"c",
",",
"abs_r",
",",
"mask",
";",
"var",
"r",
"=",
"0",
";",
"for",
"(",
"c",
"=",
"15",
";",
"c",
">=",
"0",
";",
"c",
"... | return -1, 0, +1 when a is less than, equal, or greater than b | [
"return",
"-",
"1",
"0",
"+",
"1",
"when",
"a",
"is",
"less",
"than",
"equal",
"or",
"greater",
"than",
"b"
] | 6bab9920f7beb34fc5a276fdfa68861b644925f7 | https://github.com/meganz/jodid25519/blob/6bab9920f7beb34fc5a276fdfa68861b644925f7/src/jodid25519/core.js#L60-L77 |
28,870 | pangolinjs/core | lib/utils/generate-imports.js | generateImports | function generateImports (context) {
const { files, tree } = getPageData(context)
store.state.components = tree
const output = files
.slice()
.map(file => `import '@/${file}'`)
.join('\n')
fs.ensureDirSync(path.join(context, '.temp'))
fs.writeFileSync(path.join(context, '.temp/html.js'), output)
} | javascript | function generateImports (context) {
const { files, tree } = getPageData(context)
store.state.components = tree
const output = files
.slice()
.map(file => `import '@/${file}'`)
.join('\n')
fs.ensureDirSync(path.join(context, '.temp'))
fs.writeFileSync(path.join(context, '.temp/html.js'), output)
} | [
"function",
"generateImports",
"(",
"context",
")",
"{",
"const",
"{",
"files",
",",
"tree",
"}",
"=",
"getPageData",
"(",
"context",
")",
"store",
".",
"state",
".",
"components",
"=",
"tree",
"const",
"output",
"=",
"files",
".",
"slice",
"(",
")",
"... | Generate components docs index file
@param {string} context Project directory | [
"Generate",
"components",
"docs",
"index",
"file"
] | 83c735da9eb641cf538fb61dcefebc096b30c123 | https://github.com/pangolinjs/core/blob/83c735da9eb641cf538fb61dcefebc096b30c123/lib/utils/generate-imports.js#L10-L22 |
28,871 | pangolinjs/core | lib/utils/generate-file-loader-options.js | generateFileLoaderOptions | function generateFileLoaderOptions (dir) {
const name = `assets/${dir}/[name]${store.state.config.fileNameHash ? '.[hash:8]' : ''}.[ext]`
const publicPath = process.env.NODE_ENV === 'production' ? '..' : undefined
return { name, publicPath }
} | javascript | function generateFileLoaderOptions (dir) {
const name = `assets/${dir}/[name]${store.state.config.fileNameHash ? '.[hash:8]' : ''}.[ext]`
const publicPath = process.env.NODE_ENV === 'production' ? '..' : undefined
return { name, publicPath }
} | [
"function",
"generateFileLoaderOptions",
"(",
"dir",
")",
"{",
"const",
"name",
"=",
"`",
"${",
"dir",
"}",
"${",
"store",
".",
"state",
".",
"config",
".",
"fileNameHash",
"?",
"'.[hash:8]'",
":",
"''",
"}",
"`",
"const",
"publicPath",
"=",
"process",
"... | Generate options for file-loader
@param {string} dir Asset sub-directory name
@returns {{name:string, publicPath:string}} file-loader options | [
"Generate",
"options",
"for",
"file",
"-",
"loader"
] | 83c735da9eb641cf538fb61dcefebc096b30c123 | https://github.com/pangolinjs/core/blob/83c735da9eb641cf538fb61dcefebc096b30c123/lib/utils/generate-file-loader-options.js#L8-L13 |
28,872 | pangolinjs/core | lib/utils/lint-js.js | lintJS | function lintJS (args = []) {
if (!Array.isArray(args)) {
throw new TypeError('arguments has to be an array')
}
const command = [
`node ${resolveBin('eslint')}`,
'--format codeframe',
'"src/**/*.js"',
...args
].join(' ')
console.log(chalk`\nCommand:\n{green ${command}}\n`)
try {
execSync(command, { stdio: 'inherit' })
} catch (error) {
return false
}
return true
} | javascript | function lintJS (args = []) {
if (!Array.isArray(args)) {
throw new TypeError('arguments has to be an array')
}
const command = [
`node ${resolveBin('eslint')}`,
'--format codeframe',
'"src/**/*.js"',
...args
].join(' ')
console.log(chalk`\nCommand:\n{green ${command}}\n`)
try {
execSync(command, { stdio: 'inherit' })
} catch (error) {
return false
}
return true
} | [
"function",
"lintJS",
"(",
"args",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"args",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'arguments has to be an array'",
")",
"}",
"const",
"command",
"=",
"[",
"`",
"${",
"r... | Lint JavaScript with ESLint
@param {Array<String>} [args=[]] Additional arguments
@returns {Boolean} Successfully linted code | [
"Lint",
"JavaScript",
"with",
"ESLint"
] | 83c735da9eb641cf538fb61dcefebc096b30c123 | https://github.com/pangolinjs/core/blob/83c735da9eb641cf538fb61dcefebc096b30c123/lib/utils/lint-js.js#L10-L31 |
28,873 | artdecocode/documentary | build/bin/run/extract.js | extractTypedef | async function extractTypedef(config) {
const {
source,
destination,
writable,
} = config
try {
const s = createReadStream(source)
const ts = createRegexTransformStream(typedefRe)
const ps = new Properties()
const readable = new PassThrough()
const xml = new XML()
await writeOnce(readable, '<types>\n')
s.pipe(ts).pipe(ps).pipe(xml).pipe(readable, { end: false })
const p = whichStream({
readable,
source,
writable,
destination,
})
await new Promise((r, j) => {
s.on('error', e => { LOG('Error in Read'); j(e) })
ts.on('error', e => { LOG('Error in Transform'); j(e) })
ps.on('error', e => { LOG('Error in RegexTransform'); j(e) })
xml.on('error', e => { LOG('Error in XML'); j(e) })
readable.on('error', e => { LOG('Error in Stream'); j(e) })
xml.on('end', r)
})
await new Promise(r => readable.end('</types>\n', r))
await p
} catch (err) {
catcher(err)
}
} | javascript | async function extractTypedef(config) {
const {
source,
destination,
writable,
} = config
try {
const s = createReadStream(source)
const ts = createRegexTransformStream(typedefRe)
const ps = new Properties()
const readable = new PassThrough()
const xml = new XML()
await writeOnce(readable, '<types>\n')
s.pipe(ts).pipe(ps).pipe(xml).pipe(readable, { end: false })
const p = whichStream({
readable,
source,
writable,
destination,
})
await new Promise((r, j) => {
s.on('error', e => { LOG('Error in Read'); j(e) })
ts.on('error', e => { LOG('Error in Transform'); j(e) })
ps.on('error', e => { LOG('Error in RegexTransform'); j(e) })
xml.on('error', e => { LOG('Error in XML'); j(e) })
readable.on('error', e => { LOG('Error in Stream'); j(e) })
xml.on('end', r)
})
await new Promise(r => readable.end('</types>\n', r))
await p
} catch (err) {
catcher(err)
}
} | [
"async",
"function",
"extractTypedef",
"(",
"config",
")",
"{",
"const",
"{",
"source",
",",
"destination",
",",
"writable",
",",
"}",
"=",
"config",
"try",
"{",
"const",
"s",
"=",
"createReadStream",
"(",
"source",
")",
"const",
"ts",
"=",
"createRegexTra... | Process a JavaScript file to extract typedefs and place them in an XML file.
@param {Config} config Configuration object.
@param {string} config.source Input file from which to extract typedefs.
@param {string} [config.destination="-"] Output file to where to write XML. `-` will write to `stdout`. Default `-`.
@param {string} [config.stream] An output stream to which to write instead of a location from `extractTo`. | [
"Process",
"a",
"JavaScript",
"file",
"to",
"extract",
"typedefs",
"and",
"place",
"them",
"in",
"an",
"XML",
"file",
"."
] | 5446d3df3ec76da65d671556ac25735be467e040 | https://github.com/artdecocode/documentary/blob/5446d3df3ec76da65d671556ac25735be467e040/build/bin/run/extract.js#L139-L177 |
28,874 | pangolinjs/core | lib/utils/resolve-bin.js | resolveBin | function resolveBin (moduleName) {
// Get the directory from the module's package.json path
const directory = path.dirname(require.resolve(`${moduleName}/package.json`))
// Get the relative bin path from the module's package.json bin key
let bin = require(`${moduleName}/package.json`).bin
// Sometimes the bin file isn't a string but an object
// This extracts the first bin from that object
if (typeof bin !== 'string') {
bin = Object.values(bin)[0]
}
return path.join(directory, bin)
} | javascript | function resolveBin (moduleName) {
// Get the directory from the module's package.json path
const directory = path.dirname(require.resolve(`${moduleName}/package.json`))
// Get the relative bin path from the module's package.json bin key
let bin = require(`${moduleName}/package.json`).bin
// Sometimes the bin file isn't a string but an object
// This extracts the first bin from that object
if (typeof bin !== 'string') {
bin = Object.values(bin)[0]
}
return path.join(directory, bin)
} | [
"function",
"resolveBin",
"(",
"moduleName",
")",
"{",
"// Get the directory from the module's package.json path",
"const",
"directory",
"=",
"path",
".",
"dirname",
"(",
"require",
".",
"resolve",
"(",
"`",
"${",
"moduleName",
"}",
"`",
")",
")",
"// Get the relati... | Get the corresponding bin path for a module
@param {String} moduleName Name of the module
@returns {String} Absolute path to bin file | [
"Get",
"the",
"corresponding",
"bin",
"path",
"for",
"a",
"module"
] | 83c735da9eb641cf538fb61dcefebc096b30c123 | https://github.com/pangolinjs/core/blob/83c735da9eb641cf538fb61dcefebc096b30c123/lib/utils/resolve-bin.js#L8-L22 |
28,875 | pangolinjs/core | ui/js/components/color-contrast.js | isDark | function isDark (r, g, b) {
/**
* W3C perceived brightness calculator
* @see {@link https://www.w3.org/TR/AERT/#color-contrast}
*/
const brightness = ((r * 299) + (g * 587) + (b * 114)) / 1000
if (brightness < 140) {
return true
}
return false
} | javascript | function isDark (r, g, b) {
/**
* W3C perceived brightness calculator
* @see {@link https://www.w3.org/TR/AERT/#color-contrast}
*/
const brightness = ((r * 299) + (g * 587) + (b * 114)) / 1000
if (brightness < 140) {
return true
}
return false
} | [
"function",
"isDark",
"(",
"r",
",",
"g",
",",
"b",
")",
"{",
"/**\n * W3C perceived brightness calculator\n * @see {@link https://www.w3.org/TR/AERT/#color-contrast}\n */",
"const",
"brightness",
"=",
"(",
"(",
"r",
"*",
"299",
")",
"+",
"(",
"g",
"*",
"587",
... | Color is dark
@param {Number} r Red
@param {Number} g Green
@param {Number} b Blue
@returns {Boolean} Is dark | [
"Color",
"is",
"dark"
] | 83c735da9eb641cf538fb61dcefebc096b30c123 | https://github.com/pangolinjs/core/blob/83c735da9eb641cf538fb61dcefebc096b30c123/ui/js/components/color-contrast.js#L10-L22 |
28,876 | primus/omega-supreme | omega.js | intercept | function intercept(req, res, next) {
if (
!route.test(req.url) // Incorrect URL.
|| !req.headers.authorization // Missing authorization.
|| options.method !== req.method // Invalid method.
) return next();
//
// Handle unauthorized requests.
//
if (authorization !== req.headers.authorization) {
res.statusCode = 401;
res.setHeader('Content-Type', 'application/json');
return res.end(JSON.stringify({
ok: false,
reason: [
'I am programmed to protect, and sacrifice if necessary.',
'Feel the power of my lazers! Pew pew!'
].join(' ')
}));
}
var primus = this
, buff = '';
if (typeof options.middleware === 'function') {
options.middleware(primus, parse, req, res, next);
} else {
//
// Receive the data from the socket. The `setEncoding` ensures that Unicode
// chars are correctly buffered and parsed before the `data` event is
// emitted.
//
req.setEncoding('utf8');
req.on('data', function data(chunk) {
buff += chunk;
}).once('end', function end() {
parse(primus, buff, res);
});
}
} | javascript | function intercept(req, res, next) {
if (
!route.test(req.url) // Incorrect URL.
|| !req.headers.authorization // Missing authorization.
|| options.method !== req.method // Invalid method.
) return next();
//
// Handle unauthorized requests.
//
if (authorization !== req.headers.authorization) {
res.statusCode = 401;
res.setHeader('Content-Type', 'application/json');
return res.end(JSON.stringify({
ok: false,
reason: [
'I am programmed to protect, and sacrifice if necessary.',
'Feel the power of my lazers! Pew pew!'
].join(' ')
}));
}
var primus = this
, buff = '';
if (typeof options.middleware === 'function') {
options.middleware(primus, parse, req, res, next);
} else {
//
// Receive the data from the socket. The `setEncoding` ensures that Unicode
// chars are correctly buffered and parsed before the `data` event is
// emitted.
//
req.setEncoding('utf8');
req.on('data', function data(chunk) {
buff += chunk;
}).once('end', function end() {
parse(primus, buff, res);
});
}
} | [
"function",
"intercept",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"!",
"route",
".",
"test",
"(",
"req",
".",
"url",
")",
"// Incorrect URL.",
"||",
"!",
"req",
".",
"headers",
".",
"authorization",
"// Missing authorization.",
"||",
"op... | The actual middleware layer.
@param {Request} req Incoming HTTP request.
@param {Response} res Outgoing HTTP response.
@param {Function} next Middleware continuation.
@api private | [
"The",
"actual",
"middleware",
"layer",
"."
] | 8f118d3f76c0b9187fb6e1cdc56d6691bf959aa0 | https://github.com/primus/omega-supreme/blob/8f118d3f76c0b9187fb6e1cdc56d6691bf959aa0/omega.js#L40-L81 |
28,877 | primus/omega-supreme | omega.js | parse | function parse(primus, raw, res) {
var called = 0
, data
, err;
try {
data = JSON.parse(raw);
} catch (e) {
err = e;
}
if (
err // No error..
|| 'object' !== typeof data // Should be an object.
|| Array.isArray(data) // A real object, not array.
|| !data.msg // The data we send should be defined.
) {
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
return res.end('{ "ok": false, "reason": "invalid data structure" }');
}
//
// Process the incoming messages in three different modes:
//
// Sparks: The data.sparks is an array with spark id's which we should write
// the data to.
// Spark: The data.sparks is the id of one single individual spark which
// should receive the data.
// All: Broadcast the message to every single connected spark if no
// `data.sparks` has been provided.
//
if (Array.isArray(data.sparks)) {
data.sparks.forEach(function each(id) {
var spark = primus.spark(id);
if (spark) {
spark.write(data.msg);
called++;
}
});
} else if ('string' === typeof data.sparks && data.sparks) {
var spark = primus.spark(data.sparks);
if (spark) {
spark.write(data.msg);
called++;
}
} else {
primus.forEach(function each(spark) {
spark.write(data.msg);
called++;
});
}
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end('{ "ok": true, "send":'+ called +' }');
} | javascript | function parse(primus, raw, res) {
var called = 0
, data
, err;
try {
data = JSON.parse(raw);
} catch (e) {
err = e;
}
if (
err // No error..
|| 'object' !== typeof data // Should be an object.
|| Array.isArray(data) // A real object, not array.
|| !data.msg // The data we send should be defined.
) {
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
return res.end('{ "ok": false, "reason": "invalid data structure" }');
}
//
// Process the incoming messages in three different modes:
//
// Sparks: The data.sparks is an array with spark id's which we should write
// the data to.
// Spark: The data.sparks is the id of one single individual spark which
// should receive the data.
// All: Broadcast the message to every single connected spark if no
// `data.sparks` has been provided.
//
if (Array.isArray(data.sparks)) {
data.sparks.forEach(function each(id) {
var spark = primus.spark(id);
if (spark) {
spark.write(data.msg);
called++;
}
});
} else if ('string' === typeof data.sparks && data.sparks) {
var spark = primus.spark(data.sparks);
if (spark) {
spark.write(data.msg);
called++;
}
} else {
primus.forEach(function each(spark) {
spark.write(data.msg);
called++;
});
}
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end('{ "ok": true, "send":'+ called +' }');
} | [
"function",
"parse",
"(",
"primus",
",",
"raw",
",",
"res",
")",
"{",
"var",
"called",
"=",
"0",
",",
"data",
",",
"err",
";",
"try",
"{",
"data",
"=",
"JSON",
".",
"parse",
"(",
"raw",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"err",
"=",
... | Parse the incoming so we can hand it off to the correct spark for further
processing.
@param {String} raw Raw text data.
@param {Response} res HTTP response.
@api private | [
"Parse",
"the",
"incoming",
"so",
"we",
"can",
"hand",
"it",
"off",
"to",
"the",
"correct",
"spark",
"for",
"further",
"processing",
"."
] | 8f118d3f76c0b9187fb6e1cdc56d6691bf959aa0 | https://github.com/primus/omega-supreme/blob/8f118d3f76c0b9187fb6e1cdc56d6691bf959aa0/omega.js#L99-L157 |
28,878 | pangolinjs/core | lib/utils/enhance-error-messages.js | enhanceErrorMessages | function enhanceErrorMessages (method, log) {
program.Command.prototype[method] = function (argument) {
if (method === 'unknownOption' && this._allowUnknownOption) {
return
}
this.outputHelp()
console.log(chalk`\n{red ${log(argument)}}`)
process.exit(1)
}
} | javascript | function enhanceErrorMessages (method, log) {
program.Command.prototype[method] = function (argument) {
if (method === 'unknownOption' && this._allowUnknownOption) {
return
}
this.outputHelp()
console.log(chalk`\n{red ${log(argument)}}`)
process.exit(1)
}
} | [
"function",
"enhanceErrorMessages",
"(",
"method",
",",
"log",
")",
"{",
"program",
".",
"Command",
".",
"prototype",
"[",
"method",
"]",
"=",
"function",
"(",
"argument",
")",
"{",
"if",
"(",
"method",
"===",
"'unknownOption'",
"&&",
"this",
".",
"_allowU... | Enhance Commander.js error message with more useful help
Inspired by Vue CLI
@see {@link https://github.com/vuejs/vue-cli/blob/dev/packages/%40vue/cli/lib/util/enhanceErrorMessages.js | Source on GitHub}
@param {string} method Commander.js method name
@param {Function} log Error message callback (returns a string) | [
"Enhance",
"Commander",
".",
"js",
"error",
"message",
"with",
"more",
"useful",
"help",
"Inspired",
"by",
"Vue",
"CLI"
] | 83c735da9eb641cf538fb61dcefebc096b30c123 | https://github.com/pangolinjs/core/blob/83c735da9eb641cf538fb61dcefebc096b30c123/lib/utils/enhance-error-messages.js#L11-L21 |
28,879 | artdecocode/documentary | build/bin/run/generate.js | generateTypedef | async function generateTypedef(config) {
const {
source,
destination = source,
writable,
} = config
try {
if (!source && !writable) {
console.log('Please specify a JavaScript file or a pass a stream.')
process.exit(1)
}
const s = createReadStream(source)
const readable = createJsReplaceStream()
s.pipe(readable)
const p = whichStream({
source,
readable,
destination: writable ? undefined : destination,
writable,
})
await new Promise((r, j) => {
readable.on('error', e => { LOG('Error in Replaceable'); j(e) })
s.on('error', e => { LOG('Error in Read'); j(e) })
readable.on('end', r)
})
await p
if (writable) {
LOG('%s written to stream', source)
} else if (source == destination) {
console.error('Updated %s to include types.', source)
} else if (destination == '-') {
console.error('Written %s to stdout.', source)
} else {
console.error('Saved output to %s', destination)
}
} catch (err) {
catcher(err)
}
} | javascript | async function generateTypedef(config) {
const {
source,
destination = source,
writable,
} = config
try {
if (!source && !writable) {
console.log('Please specify a JavaScript file or a pass a stream.')
process.exit(1)
}
const s = createReadStream(source)
const readable = createJsReplaceStream()
s.pipe(readable)
const p = whichStream({
source,
readable,
destination: writable ? undefined : destination,
writable,
})
await new Promise((r, j) => {
readable.on('error', e => { LOG('Error in Replaceable'); j(e) })
s.on('error', e => { LOG('Error in Read'); j(e) })
readable.on('end', r)
})
await p
if (writable) {
LOG('%s written to stream', source)
} else if (source == destination) {
console.error('Updated %s to include types.', source)
} else if (destination == '-') {
console.error('Written %s to stdout.', source)
} else {
console.error('Saved output to %s', destination)
}
} catch (err) {
catcher(err)
}
} | [
"async",
"function",
"generateTypedef",
"(",
"config",
")",
"{",
"const",
"{",
"source",
",",
"destination",
"=",
"source",
",",
"writable",
",",
"}",
"=",
"config",
"try",
"{",
"if",
"(",
"!",
"source",
"&&",
"!",
"writable",
")",
"{",
"console",
".",... | Process a JavaScript file to include `@typedef`s found with the `/* documentary types.xml *\/` marker.
@param {Config} config Configuration Object.
@param {string} config.source Path to the source JavaScript file.
@param {string} [config.destination] Path to the source JavaScript file. If not specified, source is assumed (overwriting the original file).
@param {import('stream').Writable} [config.writable] An output stream to which to write instead of a location from `generateTo`. | [
"Process",
"a",
"JavaScript",
"file",
"to",
"include"
] | 5446d3df3ec76da65d671556ac25735be467e040 | https://github.com/artdecocode/documentary/blob/5446d3df3ec76da65d671556ac25735be467e040/build/bin/run/generate.js#L16-L59 |
28,880 | artdecocode/documentary | build/bin/run.js | run | async function run(options) {
const {
source, output = '-', reverse, justToc, h1, noCache, rootNamespace,
} = options
const stream = getStream(source, reverse, false)
// todo: figure out why can't create a pass-through, pipe into it and pause it
const { types, locations } = await getTypedefs(stream, rootNamespace)
const stream3 = getStream(source, reverse, true)
const doc = new Documentary({ locations, types, noCache, objectMode: true })
stream3.pipe(doc)
const tocPromise = getToc(doc, h1, locations)
const c = new Catchment()
await whichStream({
readable: doc,
writable: c,
})
const toc = await tocPromise
const result = (await c.promise)
.replace('%%_DOCUMENTARY_TOC_CHANGE_LATER_%%', toc)
.replace(/%%DTOC_(.+?)_(\d+)%%/g, '')
if (justToc) {
console.log(toc)
process.exit()
}
if (output != '-') {
console.log('Saved documentation to %s', output)
await write(output, result)
} else {
console.log(result)
}
return [...Object.keys(locations), ...doc.assets]
} | javascript | async function run(options) {
const {
source, output = '-', reverse, justToc, h1, noCache, rootNamespace,
} = options
const stream = getStream(source, reverse, false)
// todo: figure out why can't create a pass-through, pipe into it and pause it
const { types, locations } = await getTypedefs(stream, rootNamespace)
const stream3 = getStream(source, reverse, true)
const doc = new Documentary({ locations, types, noCache, objectMode: true })
stream3.pipe(doc)
const tocPromise = getToc(doc, h1, locations)
const c = new Catchment()
await whichStream({
readable: doc,
writable: c,
})
const toc = await tocPromise
const result = (await c.promise)
.replace('%%_DOCUMENTARY_TOC_CHANGE_LATER_%%', toc)
.replace(/%%DTOC_(.+?)_(\d+)%%/g, '')
if (justToc) {
console.log(toc)
process.exit()
}
if (output != '-') {
console.log('Saved documentation to %s', output)
await write(output, result)
} else {
console.log(result)
}
return [...Object.keys(locations), ...doc.assets]
} | [
"async",
"function",
"run",
"(",
"options",
")",
"{",
"const",
"{",
"source",
",",
"output",
"=",
"'-'",
",",
"reverse",
",",
"justToc",
",",
"h1",
",",
"noCache",
",",
"rootNamespace",
",",
"}",
"=",
"options",
"const",
"stream",
"=",
"getStream",
"("... | Run the documentary and save the results.
@param {RunOptions} options Options for the run command.
@param {string} options.source The path to the source directory or file.
@param {string} [options.output="-"] The path where to save the output. When `-` is passed, prints to `stdout`. Default `-`.
@param {boolean} [options.reverse=false] Read files in directories in reverse order, such that `30.md` comes before `1.md`. Useful for blogs. Default `false`.
@param {boolean} [options.justToc=false] Only print the table of contents and exit. Default `false`.
@param {boolean} [options.h1=false] Include `H1` headers in the table of contents. Default `false`. | [
"Run",
"the",
"documentary",
"and",
"save",
"the",
"results",
"."
] | 5446d3df3ec76da65d671556ac25735be467e040 | https://github.com/artdecocode/documentary/blob/5446d3df3ec76da65d671556ac25735be467e040/build/bin/run.js#L18-L53 |
28,881 | pangolinjs/core | lib/utils/get-page-data.js | createTree | function createTree (context, folder) {
const tree = []
const files = []
let directoryContents = []
try {
directoryContents = fs.readdirSync(path.join(context, folder))
} catch (error) {
// Throw error if it’s not a permissions error
if (error.code !== 'EACCESS') {
throw error
}
}
// Folders first
directoryContents
.filter(item => {
return fs
.lstatSync(path.join(context, folder, item))
.isDirectory()
})
.forEach(item => {
const children = createTree(context, path.join(folder, item))
// Don’t add current directory to tree if it has no children
if (children.tree.length) {
tree.push({
name: formatName(item),
children: children.tree
})
}
files.push(...children.files)
})
// Files second
directoryContents
.filter(item => item.endsWith('.njk'))
.forEach(item => {
const basename = path.basename(item, '.njk')
const filePath = formatPath(folder, item)
const configPath = path.join(context, folder, basename + '.json')
let config
try {
config = JSON.parse(fs.readFileSync(configPath))
} catch (error) {
config = {}
}
// Don’t add current component to tree if it’s hidden
if (config.hidden) {
return
}
tree.push({
name: formatName(basename),
path: filePath.slice(0, -4),
config
})
files.push(filePath)
})
return { files, tree }
} | javascript | function createTree (context, folder) {
const tree = []
const files = []
let directoryContents = []
try {
directoryContents = fs.readdirSync(path.join(context, folder))
} catch (error) {
// Throw error if it’s not a permissions error
if (error.code !== 'EACCESS') {
throw error
}
}
// Folders first
directoryContents
.filter(item => {
return fs
.lstatSync(path.join(context, folder, item))
.isDirectory()
})
.forEach(item => {
const children = createTree(context, path.join(folder, item))
// Don’t add current directory to tree if it has no children
if (children.tree.length) {
tree.push({
name: formatName(item),
children: children.tree
})
}
files.push(...children.files)
})
// Files second
directoryContents
.filter(item => item.endsWith('.njk'))
.forEach(item => {
const basename = path.basename(item, '.njk')
const filePath = formatPath(folder, item)
const configPath = path.join(context, folder, basename + '.json')
let config
try {
config = JSON.parse(fs.readFileSync(configPath))
} catch (error) {
config = {}
}
// Don’t add current component to tree if it’s hidden
if (config.hidden) {
return
}
tree.push({
name: formatName(basename),
path: filePath.slice(0, -4),
config
})
files.push(filePath)
})
return { files, tree }
} | [
"function",
"createTree",
"(",
"context",
",",
"folder",
")",
"{",
"const",
"tree",
"=",
"[",
"]",
"const",
"files",
"=",
"[",
"]",
"let",
"directoryContents",
"=",
"[",
"]",
"try",
"{",
"directoryContents",
"=",
"fs",
".",
"readdirSync",
"(",
"path",
... | Recursively walk directory
@param {string} context Project directory
@param {string} folder Search in this folder
@returns {{ files: string[], tree: Object[] }} Flat file array and directory tree | [
"Recursively",
"walk",
"directory"
] | 83c735da9eb641cf538fb61dcefebc096b30c123 | https://github.com/pangolinjs/core/blob/83c735da9eb641cf538fb61dcefebc096b30c123/lib/utils/get-page-data.js#L12-L79 |
28,882 | canjs/can-dom-events | helpers/util.js | isDomEventTarget | function isDomEventTarget (obj) {
if (!(obj && obj.nodeName)) {
return obj === window;
}
var nodeType = obj.nodeType;
return (
nodeType === 1 || // Node.ELEMENT_NODE
nodeType === 9 || // Node.DOCUMENT_NODE
nodeType === 11 // Node.DOCUMENT_FRAGMENT_NODE
);
} | javascript | function isDomEventTarget (obj) {
if (!(obj && obj.nodeName)) {
return obj === window;
}
var nodeType = obj.nodeType;
return (
nodeType === 1 || // Node.ELEMENT_NODE
nodeType === 9 || // Node.DOCUMENT_NODE
nodeType === 11 // Node.DOCUMENT_FRAGMENT_NODE
);
} | [
"function",
"isDomEventTarget",
"(",
"obj",
")",
"{",
"if",
"(",
"!",
"(",
"obj",
"&&",
"obj",
".",
"nodeName",
")",
")",
"{",
"return",
"obj",
"===",
"window",
";",
"}",
"var",
"nodeType",
"=",
"obj",
".",
"nodeType",
";",
"return",
"(",
"nodeType",... | We do not account for all EventTarget classes, only EventTarget DOM nodes, fragments, and the window. | [
"We",
"do",
"not",
"account",
"for",
"all",
"EventTarget",
"classes",
"only",
"EventTarget",
"DOM",
"nodes",
"fragments",
"and",
"the",
"window",
"."
] | c5487a84a4724f69036757a476cda7efb6ecd345 | https://github.com/canjs/can-dom-events/blob/c5487a84a4724f69036757a476cda7efb6ecd345/helpers/util.js#L33-L43 |
28,883 | phovea/phovea_core | webpack.config.js | injectRegistry | function injectRegistry(entry) {
const extraFiles = [registryFile, actBuildInfoFile, actMetaData];
// build also the registry
if (typeof entry === 'string') {
return extraFiles.concat(entry);
}
const transformed = {};
Object.keys(entry).forEach((eentry) => {
transformed[eentry] = extraFiles.concat(entry[eentry]);
});
return transformed;
} | javascript | function injectRegistry(entry) {
const extraFiles = [registryFile, actBuildInfoFile, actMetaData];
// build also the registry
if (typeof entry === 'string') {
return extraFiles.concat(entry);
}
const transformed = {};
Object.keys(entry).forEach((eentry) => {
transformed[eentry] = extraFiles.concat(entry[eentry]);
});
return transformed;
} | [
"function",
"injectRegistry",
"(",
"entry",
")",
"{",
"const",
"extraFiles",
"=",
"[",
"registryFile",
",",
"actBuildInfoFile",
",",
"actMetaData",
"]",
";",
"// build also the registry",
"if",
"(",
"typeof",
"entry",
"===",
"'string'",
")",
"{",
"return",
"extr... | inject the registry to be included
@param entry
@returns {*} | [
"inject",
"the",
"registry",
"to",
"be",
"included"
] | 3fc964741dcf84628b26ac8da14af01ae789b40d | https://github.com/phovea/phovea_core/blob/3fc964741dcf84628b26ac8da14af01ae789b40d/webpack.config.js#L146-L157 |
28,884 | tyranid-org/tyranid | packages/tyranid/src/fake.js | fakeField | function fakeField(field) {
const def = _.get(field, 'is.def') || field.def;
if (!def)
throw new Error(
'No field.def property to fake on! ' + JSON.stringify(field)
);
switch (def.name) {
case 'integer':
case 'float':
case 'double':
case 'number':
return faker.random.number();
case 'email':
return faker.internet.email();
case 'url':
return faker.internet.url();
case 'date':
const date = faker.date.past();
date.setMilliseconds(0);
return date;
case 'image':
return faker.image.avatar();
case 'link':
case 'mongoid':
let i = 24,
s = '';
while (i--) s += faker.random.number(15).toString(16);
return ObjectId(s);
case 'boolean':
return faker.random.boolean();
case 'array':
return _.range(2).map(() => fakeField(field.of));
case 'object':
const key = def.name === 'link' ? 'link.def.fields' : 'fields';
return _.reduce(
_.get(field, key),
(out, value, key) => {
out[key] = fakeField(value);
return out;
},
{}
);
// default to string
default:
return faker.name.lastName();
}
} | javascript | function fakeField(field) {
const def = _.get(field, 'is.def') || field.def;
if (!def)
throw new Error(
'No field.def property to fake on! ' + JSON.stringify(field)
);
switch (def.name) {
case 'integer':
case 'float':
case 'double':
case 'number':
return faker.random.number();
case 'email':
return faker.internet.email();
case 'url':
return faker.internet.url();
case 'date':
const date = faker.date.past();
date.setMilliseconds(0);
return date;
case 'image':
return faker.image.avatar();
case 'link':
case 'mongoid':
let i = 24,
s = '';
while (i--) s += faker.random.number(15).toString(16);
return ObjectId(s);
case 'boolean':
return faker.random.boolean();
case 'array':
return _.range(2).map(() => fakeField(field.of));
case 'object':
const key = def.name === 'link' ? 'link.def.fields' : 'fields';
return _.reduce(
_.get(field, key),
(out, value, key) => {
out[key] = fakeField(value);
return out;
},
{}
);
// default to string
default:
return faker.name.lastName();
}
} | [
"function",
"fakeField",
"(",
"field",
")",
"{",
"const",
"def",
"=",
"_",
".",
"get",
"(",
"field",
",",
"'is.def'",
")",
"||",
"field",
".",
"def",
";",
"if",
"(",
"!",
"def",
")",
"throw",
"new",
"Error",
"(",
"'No field.def property to fake on! '",
... | Recurse into schema and populate fake document | [
"Recurse",
"into",
"schema",
"and",
"populate",
"fake",
"document"
] | 951ebc6efac2672479fbc1b47a9194b1e297bf8a | https://github.com/tyranid-org/tyranid/blob/951ebc6efac2672479fbc1b47a9194b1e297bf8a/packages/tyranid/src/fake.js#L9-L67 |
28,885 | tyranid-org/tyranid | packages/tyranid/src/express.js | es5Fn | function es5Fn(fn) {
let s = fn.toString();
//const name = fn.name;
//if (s.startsWith('function (')) {
//s = 'function ' + (name || '_fn' + nextFnName++) + ' (' + s.substring(10);
/*} else */
if (!s.startsWith('function')) {
s = 'function ' + s;
}
return s;
} | javascript | function es5Fn(fn) {
let s = fn.toString();
//const name = fn.name;
//if (s.startsWith('function (')) {
//s = 'function ' + (name || '_fn' + nextFnName++) + ' (' + s.substring(10);
/*} else */
if (!s.startsWith('function')) {
s = 'function ' + s;
}
return s;
} | [
"function",
"es5Fn",
"(",
"fn",
")",
"{",
"let",
"s",
"=",
"fn",
".",
"toString",
"(",
")",
";",
"//const name = fn.name;",
"//if (s.startsWith('function (')) {",
"//s = 'function ' + (name || '_fn' + nextFnName++) + ' (' + s.substring(10);",
"/*} else */",
"if",
"(",
"!",
... | let nextFnName = 1; | [
"let",
"nextFnName",
"=",
"1",
";"
] | 951ebc6efac2672479fbc1b47a9194b1e297bf8a | https://github.com/tyranid-org/tyranid/blob/951ebc6efac2672479fbc1b47a9194b1e297bf8a/packages/tyranid/src/express.js#L202-L215 |
28,886 | backand/vanilla-sdk | src/services/auth.js | useBasicAuth | function useBasicAuth() {
return new Promise((resolve, reject) => {
if (!defaults.userToken || !defaults.masterToken) {
reject(__generateFakeResponse__(0, '', {}, 'userToken or masterToken are missing for basic authentication'))
}
else {
let details = {
"token_type": "Basic",
"expires_in": 0,
"appName": defaults.appName,
"username": "",
"role": "",
"firstName": "",
"lastName": "",
"fullName": "",
"regId": 0,
"userId": null
};
let basicToken = 'Basic ' + createBasicToken(defaults.masterToken, defaults.userToken);
utils.storage.set('user', {
token: {
Authorization: basicToken
},
details: details
});
resolve(__generateFakeResponse__(200, 'OK', {}, details, {}));
}
});
} | javascript | function useBasicAuth() {
return new Promise((resolve, reject) => {
if (!defaults.userToken || !defaults.masterToken) {
reject(__generateFakeResponse__(0, '', {}, 'userToken or masterToken are missing for basic authentication'))
}
else {
let details = {
"token_type": "Basic",
"expires_in": 0,
"appName": defaults.appName,
"username": "",
"role": "",
"firstName": "",
"lastName": "",
"fullName": "",
"regId": 0,
"userId": null
};
let basicToken = 'Basic ' + createBasicToken(defaults.masterToken, defaults.userToken);
utils.storage.set('user', {
token: {
Authorization: basicToken
},
details: details
});
resolve(__generateFakeResponse__(200, 'OK', {}, details, {}));
}
});
} | [
"function",
"useBasicAuth",
"(",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"if",
"(",
"!",
"defaults",
".",
"userToken",
"||",
"!",
"defaults",
".",
"masterToken",
")",
"{",
"reject",
"(",
"__generateFakeRe... | A function that sets the authorization in the storage and therefore in the header as basic auth, the credentials are inserted in the init config. | [
"A",
"function",
"that",
"sets",
"the",
"authorization",
"in",
"the",
"storage",
"and",
"therefore",
"in",
"the",
"header",
"as",
"basic",
"auth",
"the",
"credentials",
"are",
"inserted",
"in",
"the",
"init",
"config",
"."
] | 9702f6715e46f10a19dd5644cfc12115e0a32892 | https://github.com/backand/vanilla-sdk/blob/9702f6715e46f10a19dd5644cfc12115e0a32892/src/services/auth.js#L55-L84 |
28,887 | backand/vanilla-sdk | src/services/auth.js | useAccessAuth | function useAccessAuth() {
return new Promise((resolve, reject) => {
if (!defaults.accessToken) {
reject(__generateFakeResponse__(0, '', {}, 'accessToken is missing for Access authentication'))
}
else {
let details = {
"token_type": "",
"expires_in": 0,
"appName": defaults.appName,
"username": "",
"role": "",
"firstName": "",
"lastName": "",
"fullName": "",
"regId": 0,
"userId": null
};
var aToken = defaults.accessToken.toLowerCase().startsWith('bearer') ? defaults.accessToken : 'Bearer ' + defaults.accessToken;
utils.storage.set('user', {
token: {
Authorization: aToken,
appName: defaults.appName
},
details: details
});
resolve(__generateFakeResponse__(200, 'OK', {}, details, {}));
}
});
} | javascript | function useAccessAuth() {
return new Promise((resolve, reject) => {
if (!defaults.accessToken) {
reject(__generateFakeResponse__(0, '', {}, 'accessToken is missing for Access authentication'))
}
else {
let details = {
"token_type": "",
"expires_in": 0,
"appName": defaults.appName,
"username": "",
"role": "",
"firstName": "",
"lastName": "",
"fullName": "",
"regId": 0,
"userId": null
};
var aToken = defaults.accessToken.toLowerCase().startsWith('bearer') ? defaults.accessToken : 'Bearer ' + defaults.accessToken;
utils.storage.set('user', {
token: {
Authorization: aToken,
appName: defaults.appName
},
details: details
});
resolve(__generateFakeResponse__(200, 'OK', {}, details, {}));
}
});
} | [
"function",
"useAccessAuth",
"(",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"if",
"(",
"!",
"defaults",
".",
"accessToken",
")",
"{",
"reject",
"(",
"__generateFakeResponse__",
"(",
"0",
",",
"''",
",",
"... | A function that sets the authorization in the storage and therefore in the header as Access Token auth, the credentials are inserted in the init config. | [
"A",
"function",
"that",
"sets",
"the",
"authorization",
"in",
"the",
"storage",
"and",
"therefore",
"in",
"the",
"header",
"as",
"Access",
"Token",
"auth",
"the",
"credentials",
"are",
"inserted",
"in",
"the",
"init",
"config",
"."
] | 9702f6715e46f10a19dd5644cfc12115e0a32892 | https://github.com/backand/vanilla-sdk/blob/9702f6715e46f10a19dd5644cfc12115e0a32892/src/services/auth.js#L88-L118 |
28,888 | skleeschulte/babel-plugin-transform-semantic-ui-react-imports | index.js | warn | function warn(msg) {
console.log(TAG + ' ' + colors.bold.black.bgYellow('WARNING') + ' ' + msg);
} | javascript | function warn(msg) {
console.log(TAG + ' ' + colors.bold.black.bgYellow('WARNING') + ' ' + msg);
} | [
"function",
"warn",
"(",
"msg",
")",
"{",
"console",
".",
"log",
"(",
"TAG",
"+",
"' '",
"+",
"colors",
".",
"bold",
".",
"black",
".",
"bgYellow",
"(",
"'WARNING'",
")",
"+",
"' '",
"+",
"msg",
")",
";",
"}"
] | Prints a tagged warning message.
@param msg The warning message | [
"Prints",
"a",
"tagged",
"warning",
"message",
"."
] | fac4d47e017c47cbb0491c958b42bab7fdb2379c | https://github.com/skleeschulte/babel-plugin-transform-semantic-ui-react-imports/blob/fac4d47e017c47cbb0491c958b42bab7fdb2379c/index.js#L18-L20 |
28,889 | skleeschulte/babel-plugin-transform-semantic-ui-react-imports | index.js | getJsImports | function getJsImports(importType) {
if (cache.jsImports[importType]) {
return cache.jsImports[importType];
}
var unprefixedImports = {};
if (cache.jsImports._unprefixedImports) {
unprefixedImports = cache.jsImports._unprefixedImports;
} else {
var semanticUiReactPath = getPackagePath('semantic-ui-react');
if (!semanticUiReactPath) {
error('Package semantic-ui-react could not be found. Install semantic-ui-react or set convertMemberImports ' +
'to false.');
}
var srcDirPath = path.resolve(semanticUiReactPath, 'src');
var searchFolders = [
'addons',
'behaviors',
'collections',
'elements',
'modules',
'views'
];
searchFolders.forEach(function (searchFolder) {
var searchRoot = path.resolve(srcDirPath, searchFolder);
dirTree(searchRoot, {extensions: /\.js$/}, function (item) {
var basename = path.basename(item.path, '.js');
// skip files that do not start with an uppercase letter
if (/[^A-Z]/.test(basename[0])) {
return;
}
if (unprefixedImports[basename]) {
error('duplicate react component name \'' + basename + '\' - probably the plugin needs an update');
}
unprefixedImports[basename] = item.path.substring(srcDirPath.length).replace(/\\/g, '/');
});
});
cache.jsImports._unprefixedImports = unprefixedImports;
}
var prefix;
if (importType === 'src') {
prefix = '/src';
} else {
prefix = '/dist/' + importType;
}
cache.jsImports[importType] = {};
for(var key in unprefixedImports) {
if (unprefixedImports.hasOwnProperty(key)) {
cache.jsImports[importType][key] = prefix + unprefixedImports[key];
}
}
return cache.jsImports[importType];
} | javascript | function getJsImports(importType) {
if (cache.jsImports[importType]) {
return cache.jsImports[importType];
}
var unprefixedImports = {};
if (cache.jsImports._unprefixedImports) {
unprefixedImports = cache.jsImports._unprefixedImports;
} else {
var semanticUiReactPath = getPackagePath('semantic-ui-react');
if (!semanticUiReactPath) {
error('Package semantic-ui-react could not be found. Install semantic-ui-react or set convertMemberImports ' +
'to false.');
}
var srcDirPath = path.resolve(semanticUiReactPath, 'src');
var searchFolders = [
'addons',
'behaviors',
'collections',
'elements',
'modules',
'views'
];
searchFolders.forEach(function (searchFolder) {
var searchRoot = path.resolve(srcDirPath, searchFolder);
dirTree(searchRoot, {extensions: /\.js$/}, function (item) {
var basename = path.basename(item.path, '.js');
// skip files that do not start with an uppercase letter
if (/[^A-Z]/.test(basename[0])) {
return;
}
if (unprefixedImports[basename]) {
error('duplicate react component name \'' + basename + '\' - probably the plugin needs an update');
}
unprefixedImports[basename] = item.path.substring(srcDirPath.length).replace(/\\/g, '/');
});
});
cache.jsImports._unprefixedImports = unprefixedImports;
}
var prefix;
if (importType === 'src') {
prefix = '/src';
} else {
prefix = '/dist/' + importType;
}
cache.jsImports[importType] = {};
for(var key in unprefixedImports) {
if (unprefixedImports.hasOwnProperty(key)) {
cache.jsImports[importType][key] = prefix + unprefixedImports[key];
}
}
return cache.jsImports[importType];
} | [
"function",
"getJsImports",
"(",
"importType",
")",
"{",
"if",
"(",
"cache",
".",
"jsImports",
"[",
"importType",
"]",
")",
"{",
"return",
"cache",
".",
"jsImports",
"[",
"importType",
"]",
";",
"}",
"var",
"unprefixedImports",
"=",
"{",
"}",
";",
"if",
... | Gathers import paths of Semantic UI React components from semantic-ui-react package folder.
@param importType Type of the import (es, commonjs, umd or src).
@returns {*} An object where the keys are Semantic UI React component names and the values are the corresponding
import paths (relative to semantic-ui-react/dist/[import type]/ or semantic-ui-react/src/ (for importType='src'). | [
"Gathers",
"import",
"paths",
"of",
"Semantic",
"UI",
"React",
"components",
"from",
"semantic",
"-",
"ui",
"-",
"react",
"package",
"folder",
"."
] | fac4d47e017c47cbb0491c958b42bab7fdb2379c | https://github.com/skleeschulte/babel-plugin-transform-semantic-ui-react-imports/blob/fac4d47e017c47cbb0491c958b42bab7fdb2379c/index.js#L49-L112 |
28,890 | skleeschulte/babel-plugin-transform-semantic-ui-react-imports | index.js | isLodashPluginWithSemanticUiReact | function isLodashPluginWithSemanticUiReact(plugin) {
if (Array.isArray(plugin)) {
// Babel 6 plugin is a tuple as an array [id, options]
return (
["lodash", "babel-plugin-lodash"].includes(plugin[0].key) &&
[].concat(plugin[1].id).includes("semantic-ui-react")
);
} else if (plugin != null && typeof plugin === "object") {
// Babel 7 plugin is an object { key, options, ... }
return (
/[/\\]node_modules([/\\].*)?[/\\]babel-plugin-lodash([/\\].*)?$/.test(plugin.key) &&
plugin.options &&
plugin.options.id &&
[].concat(plugin.options.id).includes("semantic-ui-react")
);
} else {
return false;
}
} | javascript | function isLodashPluginWithSemanticUiReact(plugin) {
if (Array.isArray(plugin)) {
// Babel 6 plugin is a tuple as an array [id, options]
return (
["lodash", "babel-plugin-lodash"].includes(plugin[0].key) &&
[].concat(plugin[1].id).includes("semantic-ui-react")
);
} else if (plugin != null && typeof plugin === "object") {
// Babel 7 plugin is an object { key, options, ... }
return (
/[/\\]node_modules([/\\].*)?[/\\]babel-plugin-lodash([/\\].*)?$/.test(plugin.key) &&
plugin.options &&
plugin.options.id &&
[].concat(plugin.options.id).includes("semantic-ui-react")
);
} else {
return false;
}
} | [
"function",
"isLodashPluginWithSemanticUiReact",
"(",
"plugin",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"plugin",
")",
")",
"{",
"// Babel 6 plugin is a tuple as an array [id, options]",
"return",
"(",
"[",
"\"lodash\"",
",",
"\"babel-plugin-lodash\"",
"]",
... | Checks if a babel configuration object matches a lodash plugin with semantic-ui-react in its id option.
@param plugin A plugin config obtained from babel's state | [
"Checks",
"if",
"a",
"babel",
"configuration",
"object",
"matches",
"a",
"lodash",
"plugin",
"with",
"semantic",
"-",
"ui",
"-",
"react",
"in",
"its",
"id",
"option",
"."
] | fac4d47e017c47cbb0491c958b42bab7fdb2379c | https://github.com/skleeschulte/babel-plugin-transform-semantic-ui-react-imports/blob/fac4d47e017c47cbb0491c958b42bab7fdb2379c/index.js#L207-L225 |
28,891 | jasonrojas/node-captions | lib/time.js | function(adjustment, precision, captions, callback) {
//precision should be one of: seconds, milliseconds, microseconds
var precisionMultipliers = {
"seconds": 1000000, //seconds to microseconds
"milliseconds": 1000, //milliseconds to microseconds
"microseconds": 1 //microseconds to microseconds
},
newStartTime,
newEndTime,
adjuster = adjustment * precisionMultipliers[precision];
if (precisionMultipliers[precision] && captions[0].startTimeMicro !== undefined) {
//quick check to see if it will zero out the 2nd or 3rd caption
// there are cases where the first caption can be 00:00:00:000 and have no text.
if ((captions[1].startTimeMicro + adjuster) <= 0 || (captions[2].startTimeMicro + adjuster) <= 0) {
return callback("ERROR_ADJUSTMENT_ZEROS_CAPTIONS");
}
captions.forEach(function(caption) {
//calculate new start times...
newStartTime = caption.startTimeMicro + adjuster;
newEndTime = caption.endTimeMicro + adjuster;
if (adjuster > 0) {
caption.startTimeMicro = newStartTime;
caption.endTimeMicro = newEndTime;
} else if (newStartTime >= 0 && newEndTime >= 0) {
caption.startTimeMicro = newStartTime;
caption.endTimeMicro = newEndTime;
}
});
callback(undefined, captions);
} else {
callback('NO_CAPTIONS_OR_PRECISION_PASSED_TO_FUNCTION');
}
} | javascript | function(adjustment, precision, captions, callback) {
//precision should be one of: seconds, milliseconds, microseconds
var precisionMultipliers = {
"seconds": 1000000, //seconds to microseconds
"milliseconds": 1000, //milliseconds to microseconds
"microseconds": 1 //microseconds to microseconds
},
newStartTime,
newEndTime,
adjuster = adjustment * precisionMultipliers[precision];
if (precisionMultipliers[precision] && captions[0].startTimeMicro !== undefined) {
//quick check to see if it will zero out the 2nd or 3rd caption
// there are cases where the first caption can be 00:00:00:000 and have no text.
if ((captions[1].startTimeMicro + adjuster) <= 0 || (captions[2].startTimeMicro + adjuster) <= 0) {
return callback("ERROR_ADJUSTMENT_ZEROS_CAPTIONS");
}
captions.forEach(function(caption) {
//calculate new start times...
newStartTime = caption.startTimeMicro + adjuster;
newEndTime = caption.endTimeMicro + adjuster;
if (adjuster > 0) {
caption.startTimeMicro = newStartTime;
caption.endTimeMicro = newEndTime;
} else if (newStartTime >= 0 && newEndTime >= 0) {
caption.startTimeMicro = newStartTime;
caption.endTimeMicro = newEndTime;
}
});
callback(undefined, captions);
} else {
callback('NO_CAPTIONS_OR_PRECISION_PASSED_TO_FUNCTION');
}
} | [
"function",
"(",
"adjustment",
",",
"precision",
",",
"captions",
",",
"callback",
")",
"{",
"//precision should be one of: seconds, milliseconds, microseconds",
"var",
"precisionMultipliers",
"=",
"{",
"\"seconds\"",
":",
"1000000",
",",
"//seconds to microseconds",
"\"mil... | adjust timestamp by X, precision
@function
@param {integer} adjustment - negative or positive integer amount to adjust the captions by
@param {string} precision - precision to adjust captions by
@param {array} captions - json array of captions to perform adjustment on created by toJSON
@public | [
"adjust",
"timestamp",
"by",
"X",
"precision"
] | 4b7fd97dd36ea14bff393781f1d609644bcd61a3 | https://github.com/jasonrojas/node-captions/blob/4b7fd97dd36ea14bff393781f1d609644bcd61a3/lib/time.js#L20-L52 | |
28,892 | jasonrojas/node-captions | lib/vtt.js | function(captions) {
var VTT_BODY = ['WEBVTT\n']; //header
captions.forEach(function(caption) {
if (caption.text.length > 0 && validateText(caption.text)) {
VTT_BODY.push(module.exports.formatTime(caption.startTimeMicro) + ' --> ' + module.exports.formatTime(caption.endTimeMicro));
VTT_BODY.push(module.exports.renderMacros(caption.text) + '\n');
}
});
return VTT_BODY.join('\n');
} | javascript | function(captions) {
var VTT_BODY = ['WEBVTT\n']; //header
captions.forEach(function(caption) {
if (caption.text.length > 0 && validateText(caption.text)) {
VTT_BODY.push(module.exports.formatTime(caption.startTimeMicro) + ' --> ' + module.exports.formatTime(caption.endTimeMicro));
VTT_BODY.push(module.exports.renderMacros(caption.text) + '\n');
}
});
return VTT_BODY.join('\n');
} | [
"function",
"(",
"captions",
")",
"{",
"var",
"VTT_BODY",
"=",
"[",
"'WEBVTT\\n'",
"]",
";",
"//header",
"captions",
".",
"forEach",
"(",
"function",
"(",
"caption",
")",
"{",
"if",
"(",
"caption",
".",
"text",
".",
"length",
">",
"0",
"&&",
"validateT... | Generates VTT from JSON
@function
@param {array} captions - array of json captions
@public | [
"Generates",
"VTT",
"from",
"JSON"
] | 4b7fd97dd36ea14bff393781f1d609644bcd61a3 | https://github.com/jasonrojas/node-captions/blob/4b7fd97dd36ea14bff393781f1d609644bcd61a3/lib/vtt.js#L28-L37 | |
28,893 | jasonrojas/node-captions | lib/vtt.js | function(microseconds) {
var milliseconds = microseconds / 1000;
if (moment.utc(milliseconds).format("HH") > 0) {
return moment.utc(milliseconds).format("HH:mm:ss.SSS");
}
return moment.utc(milliseconds).format("mm:ss.SSS");
} | javascript | function(microseconds) {
var milliseconds = microseconds / 1000;
if (moment.utc(milliseconds).format("HH") > 0) {
return moment.utc(milliseconds).format("HH:mm:ss.SSS");
}
return moment.utc(milliseconds).format("mm:ss.SSS");
} | [
"function",
"(",
"microseconds",
")",
"{",
"var",
"milliseconds",
"=",
"microseconds",
"/",
"1000",
";",
"if",
"(",
"moment",
".",
"utc",
"(",
"milliseconds",
")",
".",
"format",
"(",
"\"HH\"",
")",
">",
"0",
")",
"{",
"return",
"moment",
".",
"utc",
... | formats microseconds into VTT timestamps
@function
@param {string} microseconds - microseocnds to convert to VTT timestamp
@public | [
"formats",
"microseconds",
"into",
"VTT",
"timestamps"
] | 4b7fd97dd36ea14bff393781f1d609644bcd61a3 | https://github.com/jasonrojas/node-captions/blob/4b7fd97dd36ea14bff393781f1d609644bcd61a3/lib/vtt.js#L53-L59 | |
28,894 | t2t2/vue-syncers-feathers | src/mixin.js | loadingStateGetter | function loadingStateGetter() {
if (Object.keys(this._syncers).length > 0) {
return some(this._syncers, syncer => {
return syncer.loading
})
}
return false
} | javascript | function loadingStateGetter() {
if (Object.keys(this._syncers).length > 0) {
return some(this._syncers, syncer => {
return syncer.loading
})
}
return false
} | [
"function",
"loadingStateGetter",
"(",
")",
"{",
"if",
"(",
"Object",
".",
"keys",
"(",
"this",
".",
"_syncers",
")",
".",
"length",
">",
"0",
")",
"{",
"return",
"some",
"(",
"this",
".",
"_syncers",
",",
"syncer",
"=>",
"{",
"return",
"syncer",
"."... | Get loading state of the syncers
@returns {boolean} | [
"Get",
"loading",
"state",
"of",
"the",
"syncers"
] | 9a5c45d803d51d6c941dfdf2a729dc2908b53dc7 | https://github.com/t2t2/vue-syncers-feathers/blob/9a5c45d803d51d6c941dfdf2a729dc2908b53dc7/src/mixin.js#L83-L90 |
28,895 | t2t2/vue-syncers-feathers | src/mixin.js | refreshSyncers | function refreshSyncers(keys) {
if (typeof keys === 'string') {
keys = [keys]
}
if (!keys) {
keys = Object.keys(this._syncers)
}
return Promise.all(keys.map(key => {
return this._syncers[key].refresh()
}))
} | javascript | function refreshSyncers(keys) {
if (typeof keys === 'string') {
keys = [keys]
}
if (!keys) {
keys = Object.keys(this._syncers)
}
return Promise.all(keys.map(key => {
return this._syncers[key].refresh()
}))
} | [
"function",
"refreshSyncers",
"(",
"keys",
")",
"{",
"if",
"(",
"typeof",
"keys",
"===",
"'string'",
")",
"{",
"keys",
"=",
"[",
"keys",
"]",
"}",
"if",
"(",
"!",
"keys",
")",
"{",
"keys",
"=",
"Object",
".",
"keys",
"(",
"this",
".",
"_syncers",
... | Refresh syncers state
@param {string|string[]} [keys] - Syncers to refresh | [
"Refresh",
"syncers",
"state"
] | 9a5c45d803d51d6c941dfdf2a729dc2908b53dc7 | https://github.com/t2t2/vue-syncers-feathers/blob/9a5c45d803d51d6c941dfdf2a729dc2908b53dc7/src/mixin.js#L97-L107 |
28,896 | jasonrojas/node-captions | lib/ttml.js | function(data) {
var TTML_BODY = '',
index = 0,
splitText,
captions = data;
TTML_BODY += TTML.header.join('\n') + '\n';
captions.forEach(function(caption) {
if (caption.text.length > 0 && validateText(caption.text)) {
if ((/&/.test(caption.text)) && !(/&/.test(caption.text))) {
caption.text = caption.text.replace(/&/g, '&');
}
if ((/</.test(caption.text)) && !(/</.test(caption.text))) {
caption.text = caption.text.replace(/</g, '<');
}
if ((/>/.test(caption.text)) && !(/>/.test(caption.text))) {
caption.text = caption.text.replace(/>/g, '>');
}
if (/\{break\}/.test(caption.text)) {
splitText = caption.text.split('{break}');
//TODO this should count for number of breaks and add the appropriate pops where needed.
for (index = 0; index < splitText.length; index++) {
TTML_BODY += TTML.lineTemplate.replace('{region}', 'pop' + (index + 1))
.replace('{startTime}', module.exports.formatTime(caption.startTimeMicro))
.replace('{endTime}', module.exports.formatTime(caption.endTimeMicro))
.replace('{text}', module.exports.renderMacros(macros.fixItalics(macros.cleanMacros(splitText[index])))) + '\n';
}
} else {
TTML_BODY += TTML.lineTemplate.replace('{region}', 'pop1')
.replace('{startTime}', module.exports.formatTime(caption.startTimeMicro))
.replace('{endTime}', module.exports.formatTime(caption.endTimeMicro))
.replace('{text}', module.exports.renderMacros(macros.fixItalics(macros.cleanMacros(caption.text)))) + '\n';
}
}
});
return TTML_BODY + TTML.footer.join('\n') + '\n';
} | javascript | function(data) {
var TTML_BODY = '',
index = 0,
splitText,
captions = data;
TTML_BODY += TTML.header.join('\n') + '\n';
captions.forEach(function(caption) {
if (caption.text.length > 0 && validateText(caption.text)) {
if ((/&/.test(caption.text)) && !(/&/.test(caption.text))) {
caption.text = caption.text.replace(/&/g, '&');
}
if ((/</.test(caption.text)) && !(/</.test(caption.text))) {
caption.text = caption.text.replace(/</g, '<');
}
if ((/>/.test(caption.text)) && !(/>/.test(caption.text))) {
caption.text = caption.text.replace(/>/g, '>');
}
if (/\{break\}/.test(caption.text)) {
splitText = caption.text.split('{break}');
//TODO this should count for number of breaks and add the appropriate pops where needed.
for (index = 0; index < splitText.length; index++) {
TTML_BODY += TTML.lineTemplate.replace('{region}', 'pop' + (index + 1))
.replace('{startTime}', module.exports.formatTime(caption.startTimeMicro))
.replace('{endTime}', module.exports.formatTime(caption.endTimeMicro))
.replace('{text}', module.exports.renderMacros(macros.fixItalics(macros.cleanMacros(splitText[index])))) + '\n';
}
} else {
TTML_BODY += TTML.lineTemplate.replace('{region}', 'pop1')
.replace('{startTime}', module.exports.formatTime(caption.startTimeMicro))
.replace('{endTime}', module.exports.formatTime(caption.endTimeMicro))
.replace('{text}', module.exports.renderMacros(macros.fixItalics(macros.cleanMacros(caption.text)))) + '\n';
}
}
});
return TTML_BODY + TTML.footer.join('\n') + '\n';
} | [
"function",
"(",
"data",
")",
"{",
"var",
"TTML_BODY",
"=",
"''",
",",
"index",
"=",
"0",
",",
"splitText",
",",
"captions",
"=",
"data",
";",
"TTML_BODY",
"+=",
"TTML",
".",
"header",
".",
"join",
"(",
"'\\n'",
")",
"+",
"'\\n'",
";",
"captions",
... | generates TTML from JSON
@function
@param {array} data - JSON array of captions
@public | [
"generates",
"TTML",
"from",
"JSON"
] | 4b7fd97dd36ea14bff393781f1d609644bcd61a3 | https://github.com/jasonrojas/node-captions/blob/4b7fd97dd36ea14bff393781f1d609644bcd61a3/lib/ttml.js#L29-L66 | |
28,897 | mportuga/eslint-detailed-reporter | lib/template-generator.js | getRuleLink | function getRuleLink(ruleId) {
let ruleLink = `http://eslint.org/docs/rules/${ruleId}`;
if (_.startsWith(ruleId, 'angular')) {
ruleId = ruleId.replace('angular/', '');
ruleLink = `https://github.com/Gillespie59/eslint-plugin-angular/blob/master/docs/${ruleId}.md`;
} else if (_.startsWith(ruleId, 'lodash')) {
ruleId = ruleId.replace('lodash/', '');
ruleLink = `https://github.com/wix/eslint-plugin-lodash/blob/master/docs/rules/${ruleId}.md`;
}
return ruleLink;
} | javascript | function getRuleLink(ruleId) {
let ruleLink = `http://eslint.org/docs/rules/${ruleId}`;
if (_.startsWith(ruleId, 'angular')) {
ruleId = ruleId.replace('angular/', '');
ruleLink = `https://github.com/Gillespie59/eslint-plugin-angular/blob/master/docs/${ruleId}.md`;
} else if (_.startsWith(ruleId, 'lodash')) {
ruleId = ruleId.replace('lodash/', '');
ruleLink = `https://github.com/wix/eslint-plugin-lodash/blob/master/docs/rules/${ruleId}.md`;
}
return ruleLink;
} | [
"function",
"getRuleLink",
"(",
"ruleId",
")",
"{",
"let",
"ruleLink",
"=",
"`",
"${",
"ruleId",
"}",
"`",
";",
"if",
"(",
"_",
".",
"startsWith",
"(",
"ruleId",
",",
"'angular'",
")",
")",
"{",
"ruleId",
"=",
"ruleId",
".",
"replace",
"(",
"'angular... | Takes in a rule Id and returns the correct link for the description
@param {string} ruleId A eslint rule Id
@return {string} The link to the rules description | [
"Takes",
"in",
"a",
"rule",
"Id",
"and",
"returns",
"the",
"correct",
"link",
"for",
"the",
"description"
] | 731af360846962e6bf7d9a92a6e8f96ef2710fb0 | https://github.com/mportuga/eslint-detailed-reporter/blob/731af360846962e6bf7d9a92a6e8f96ef2710fb0/lib/template-generator.js#L62-L73 |
28,898 | mportuga/eslint-detailed-reporter | lib/template-generator.js | renderSummaryDetails | function renderSummaryDetails(rules, problemFiles, currDir) {
let summaryDetails = '<div class="row">';
// errors exist
if (rules['2']) {
summaryDetails += summaryDetailsTemplate({
ruleType: 'error',
topRules: renderRules(rules['2'])
});
}
// warnings exist
if (rules['1']) {
summaryDetails += summaryDetailsTemplate({
ruleType: 'warning',
topRules: renderRules(rules['1'])
});
}
summaryDetails += '</div>';
// files with problems exist
if (!_.isEmpty(problemFiles)) {
summaryDetails += mostProblemsTemplate({
files: renderProblemFiles(problemFiles, currDir)
});
}
return summaryDetails;
} | javascript | function renderSummaryDetails(rules, problemFiles, currDir) {
let summaryDetails = '<div class="row">';
// errors exist
if (rules['2']) {
summaryDetails += summaryDetailsTemplate({
ruleType: 'error',
topRules: renderRules(rules['2'])
});
}
// warnings exist
if (rules['1']) {
summaryDetails += summaryDetailsTemplate({
ruleType: 'warning',
topRules: renderRules(rules['1'])
});
}
summaryDetails += '</div>';
// files with problems exist
if (!_.isEmpty(problemFiles)) {
summaryDetails += mostProblemsTemplate({
files: renderProblemFiles(problemFiles, currDir)
});
}
return summaryDetails;
} | [
"function",
"renderSummaryDetails",
"(",
"rules",
",",
"problemFiles",
",",
"currDir",
")",
"{",
"let",
"summaryDetails",
"=",
"'<div class=\"row\">'",
";",
"// errors exist",
"if",
"(",
"rules",
"[",
"'2'",
"]",
")",
"{",
"summaryDetails",
"+=",
"summaryDetailsTe... | Generates the summary details section by only including the necessary tables.
@param {object} rules An object with all of the rules sorted by type
@param {array} [problemFiles] An optional object with the top 5 worst files being linted
@param {String} currDir Current working directory
@return {string} HTML string of all the summary detail tables that are needed | [
"Generates",
"the",
"summary",
"details",
"section",
"by",
"only",
"including",
"the",
"necessary",
"tables",
"."
] | 731af360846962e6bf7d9a92a6e8f96ef2710fb0 | https://github.com/mportuga/eslint-detailed-reporter/blob/731af360846962e6bf7d9a92a6e8f96ef2710fb0/lib/template-generator.js#L82-L111 |
28,899 | mportuga/eslint-detailed-reporter | lib/template-generator.js | renderIssue | function renderIssue(message) {
return issueTemplate({
severity: severityString(message.severity),
severityName: message.severity === 1 ? 'Warning' : 'Error',
lineNumber: message.line,
column: message.column,
message: message.message,
ruleId: message.ruleId,
ruleLink: getRuleLink(message.ruleId)
});
} | javascript | function renderIssue(message) {
return issueTemplate({
severity: severityString(message.severity),
severityName: message.severity === 1 ? 'Warning' : 'Error',
lineNumber: message.line,
column: message.column,
message: message.message,
ruleId: message.ruleId,
ruleLink: getRuleLink(message.ruleId)
});
} | [
"function",
"renderIssue",
"(",
"message",
")",
"{",
"return",
"issueTemplate",
"(",
"{",
"severity",
":",
"severityString",
"(",
"message",
".",
"severity",
")",
",",
"severityName",
":",
"message",
".",
"severity",
"===",
"1",
"?",
"'Warning'",
":",
"'Erro... | Renders an issue
@param {object} message a message object with an issue
@returns {string} HTML string of an issue | [
"Renders",
"an",
"issue"
] | 731af360846962e6bf7d9a92a6e8f96ef2710fb0 | https://github.com/mportuga/eslint-detailed-reporter/blob/731af360846962e6bf7d9a92a6e8f96ef2710fb0/lib/template-generator.js#L144-L154 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.