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
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
rung-tools/rung-cli | src/build.js | resolveOutputTarget | function resolveOutputTarget(customPath, filename) {
const realPath = path.resolve('.', customPath);
const getPath = tryCatch(
realPath => fs.lstatSync(realPath).isDirectory()
? path.join(realPath, filename)
: realPath,
identity);
return getPath(realPath);
} | javascript | function resolveOutputTarget(customPath, filename) {
const realPath = path.resolve('.', customPath);
const getPath = tryCatch(
realPath => fs.lstatSync(realPath).isDirectory()
? path.join(realPath, filename)
: realPath,
identity);
return getPath(realPath);
} | [
"function",
"resolveOutputTarget",
"(",
"customPath",
",",
"filename",
")",
"{",
"const",
"realPath",
"=",
"path",
".",
"resolve",
"(",
"'.'",
",",
"customPath",
")",
";",
"const",
"getPath",
"=",
"tryCatch",
"(",
"realPath",
"=>",
"fs",
".",
"lstatSync",
"(",
"realPath",
")",
".",
"isDirectory",
"(",
")",
"?",
"path",
".",
"join",
"(",
"realPath",
",",
"filename",
")",
":",
"realPath",
",",
"identity",
")",
";",
"return",
"getPath",
"(",
"realPath",
")",
";",
"}"
] | Taking account the -o parameter can be used to specify the output directory,
let's deal with it
@param {String} customPath
@param {String} filename
@return {String} | [
"Taking",
"account",
"the",
"-",
"o",
"parameter",
"can",
"be",
"used",
"to",
"specify",
"the",
"output",
"directory",
"let",
"s",
"deal",
"with",
"it"
] | c8906bb6733bdd5bcea2e9b54ed48f26ae1526d5 | https://github.com/rung-tools/rung-cli/blob/c8906bb6733bdd5bcea2e9b54ed48f26ae1526d5/src/build.js#L238-L248 | train |
iuap-design/tinper-neoui-grid | dist/tinper-neoui-grid.js | objCompare | function objCompare(rootObj, objAry) {
var aryLen = objAry.length;
// var rootStr = JSON.stringify(rootObj);
var matchNum = 0;
for (var i = 0; i < aryLen; i++) {
// var compareStr = JSON.stringify(objAry[i]);
var compareObj = objAry[i];
matchNum += rootObj == compareObj ? 1 : 0;
}
return matchNum > 0 ? true : false;
} | javascript | function objCompare(rootObj, objAry) {
var aryLen = objAry.length;
// var rootStr = JSON.stringify(rootObj);
var matchNum = 0;
for (var i = 0; i < aryLen; i++) {
// var compareStr = JSON.stringify(objAry[i]);
var compareObj = objAry[i];
matchNum += rootObj == compareObj ? 1 : 0;
}
return matchNum > 0 ? true : false;
} | [
"function",
"objCompare",
"(",
"rootObj",
",",
"objAry",
")",
"{",
"var",
"aryLen",
"=",
"objAry",
".",
"length",
";",
"var",
"matchNum",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"aryLen",
";",
"i",
"++",
")",
"{",
"var",
"compareObj",
"=",
"objAry",
"[",
"i",
"]",
";",
"matchNum",
"+=",
"rootObj",
"==",
"compareObj",
"?",
"1",
":",
"0",
";",
"}",
"return",
"matchNum",
">",
"0",
"?",
"true",
":",
"false",
";",
"}"
] | Object Compare with Array Object | [
"Object",
"Compare",
"with",
"Array",
"Object"
] | 24d392eb460beede997187593982952a1af2cfcc | https://github.com/iuap-design/tinper-neoui-grid/blob/24d392eb460beede997187593982952a1af2cfcc/dist/tinper-neoui-grid.js#L1989-L1999 | train |
rung-tools/rung-cli | src/db.js | serialize | function serialize(input) {
const value = JSON.stringify(input);
return value === undefined
? reject(new Error(`Unsupported type ${type(input)}`))
: resolve(value);
} | javascript | function serialize(input) {
const value = JSON.stringify(input);
return value === undefined
? reject(new Error(`Unsupported type ${type(input)}`))
: resolve(value);
} | [
"function",
"serialize",
"(",
"input",
")",
"{",
"const",
"value",
"=",
"JSON",
".",
"stringify",
"(",
"input",
")",
";",
"return",
"value",
"===",
"undefined",
"?",
"reject",
"(",
"new",
"Error",
"(",
"`",
"${",
"type",
"(",
"input",
")",
"}",
"`",
")",
")",
":",
"resolve",
"(",
"value",
")",
";",
"}"
] | Marshalls the JS input
@param {Mixed} input
@return {Promise} | [
"Marshalls",
"the",
"JS",
"input"
] | c8906bb6733bdd5bcea2e9b54ed48f26ae1526d5 | https://github.com/rung-tools/rung-cli/blob/c8906bb6733bdd5bcea2e9b54ed48f26ae1526d5/src/db.js#L26-L31 | train |
rung-tools/rung-cli | src/db.js | resolveRungFolder | function resolveRungFolder() {
const folder = path.join(os.homedir(), '.rung');
const createIfNotExists = tryCatch(
~(fs.lstatSync(folder).isDirectory()
? resolve()
: reject(new Error('~/.rung is not a directory'))),
~createFolder(folder)
);
return createIfNotExists();
} | javascript | function resolveRungFolder() {
const folder = path.join(os.homedir(), '.rung');
const createIfNotExists = tryCatch(
~(fs.lstatSync(folder).isDirectory()
? resolve()
: reject(new Error('~/.rung is not a directory'))),
~createFolder(folder)
);
return createIfNotExists();
} | [
"function",
"resolveRungFolder",
"(",
")",
"{",
"const",
"folder",
"=",
"path",
".",
"join",
"(",
"os",
".",
"homedir",
"(",
")",
",",
"'.rung'",
")",
";",
"const",
"createIfNotExists",
"=",
"tryCatch",
"(",
"~",
"(",
"fs",
".",
"lstatSync",
"(",
"folder",
")",
".",
"isDirectory",
"(",
")",
"?",
"resolve",
"(",
")",
":",
"reject",
"(",
"new",
"Error",
"(",
"'~/.rung is not a directory'",
")",
")",
")",
",",
"~",
"createFolder",
"(",
"folder",
")",
")",
";",
"return",
"createIfNotExists",
"(",
")",
";",
"}"
] | Creates the .rung folder when it doesn't exist
@return {Promise} | [
"Creates",
"the",
".",
"rung",
"folder",
"when",
"it",
"doesn",
"t",
"exist"
] | c8906bb6733bdd5bcea2e9b54ed48f26ae1526d5 | https://github.com/rung-tools/rung-cli/blob/c8906bb6733bdd5bcea2e9b54ed48f26ae1526d5/src/db.js#L87-L97 | train |
rung-tools/rung-cli | src/live.js | watchChanges | function watchChanges(io, params) {
const folder = process.cwd();
return watch(folder, { recursive: true }, () => {
emitInfo('changes detected. Recompiling...');
io.sockets.emit('load');
const start = new Date().getTime();
executeWithParams(params)
.tap(alerts => {
const ellapsed = new Date().getTime() - start;
emitSuccess(`wow! recompiled and executed in ${ellapsed}ms!`);
io.sockets.emit('update', compileMarkdown(alerts));
})
.catch(err => {
emitError(`hot compilation error, baby: ${err.message}`);
io.sockets.emit('failure', err.stack);
});
});
} | javascript | function watchChanges(io, params) {
const folder = process.cwd();
return watch(folder, { recursive: true }, () => {
emitInfo('changes detected. Recompiling...');
io.sockets.emit('load');
const start = new Date().getTime();
executeWithParams(params)
.tap(alerts => {
const ellapsed = new Date().getTime() - start;
emitSuccess(`wow! recompiled and executed in ${ellapsed}ms!`);
io.sockets.emit('update', compileMarkdown(alerts));
})
.catch(err => {
emitError(`hot compilation error, baby: ${err.message}`);
io.sockets.emit('failure', err.stack);
});
});
} | [
"function",
"watchChanges",
"(",
"io",
",",
"params",
")",
"{",
"const",
"folder",
"=",
"process",
".",
"cwd",
"(",
")",
";",
"return",
"watch",
"(",
"folder",
",",
"{",
"recursive",
":",
"true",
"}",
",",
"(",
")",
"=>",
"{",
"emitInfo",
"(",
"'changes detected. Recompiling...'",
")",
";",
"io",
".",
"sockets",
".",
"emit",
"(",
"'load'",
")",
";",
"const",
"start",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
";",
"executeWithParams",
"(",
"params",
")",
".",
"tap",
"(",
"alerts",
"=>",
"{",
"const",
"ellapsed",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"-",
"start",
";",
"emitSuccess",
"(",
"`",
"${",
"ellapsed",
"}",
"`",
")",
";",
"io",
".",
"sockets",
".",
"emit",
"(",
"'update'",
",",
"compileMarkdown",
"(",
"alerts",
")",
")",
";",
"}",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"emitError",
"(",
"`",
"${",
"err",
".",
"message",
"}",
"`",
")",
";",
"io",
".",
"sockets",
".",
"emit",
"(",
"'failure'",
",",
"err",
".",
"stack",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Watches folder for file changes, hot recompiling everything and notifying
the clients
@param {SocketIO} io
@param {Object} params
@return {Object} | [
"Watches",
"folder",
"for",
"file",
"changes",
"hot",
"recompiling",
"everything",
"and",
"notifying",
"the",
"clients"
] | c8906bb6733bdd5bcea2e9b54ed48f26ae1526d5 | https://github.com/rung-tools/rung-cli/blob/c8906bb6733bdd5bcea2e9b54ed48f26ae1526d5/src/live.js#L76-L93 | train |
rung-tools/rung-cli | src/live.js | startServer | function startServer(alerts, params, port, resources) {
const compiledAlerts = compileMarkdown(alerts);
const app = http.createServer((req, res) =>
res.end(resources[req.url] || resources['/index.html']));
const io = listen(app);
io.on('connection', socket => {
emitInfo(`new session for ${socket.handshake.address}`);
socket.emit('update', compiledAlerts);
socket.on('disconnect', () => {
emitInfo(`disconnected session ${socket.handshake.address}`);
});
});
return new Promise(resolve => app.listen(port, emitRungEmoji & resolve))
.then(~watchChanges(io, params));
} | javascript | function startServer(alerts, params, port, resources) {
const compiledAlerts = compileMarkdown(alerts);
const app = http.createServer((req, res) =>
res.end(resources[req.url] || resources['/index.html']));
const io = listen(app);
io.on('connection', socket => {
emitInfo(`new session for ${socket.handshake.address}`);
socket.emit('update', compiledAlerts);
socket.on('disconnect', () => {
emitInfo(`disconnected session ${socket.handshake.address}`);
});
});
return new Promise(resolve => app.listen(port, emitRungEmoji & resolve))
.then(~watchChanges(io, params));
} | [
"function",
"startServer",
"(",
"alerts",
",",
"params",
",",
"port",
",",
"resources",
")",
"{",
"const",
"compiledAlerts",
"=",
"compileMarkdown",
"(",
"alerts",
")",
";",
"const",
"app",
"=",
"http",
".",
"createServer",
"(",
"(",
"req",
",",
"res",
")",
"=>",
"res",
".",
"end",
"(",
"resources",
"[",
"req",
".",
"url",
"]",
"||",
"resources",
"[",
"'/index.html'",
"]",
")",
")",
";",
"const",
"io",
"=",
"listen",
"(",
"app",
")",
";",
"io",
".",
"on",
"(",
"'connection'",
",",
"socket",
"=>",
"{",
"emitInfo",
"(",
"`",
"${",
"socket",
".",
"handshake",
".",
"address",
"}",
"`",
")",
";",
"socket",
".",
"emit",
"(",
"'update'",
",",
"compiledAlerts",
")",
";",
"socket",
".",
"on",
"(",
"'disconnect'",
",",
"(",
")",
"=>",
"{",
"emitInfo",
"(",
"`",
"${",
"socket",
".",
"handshake",
".",
"address",
"}",
"`",
")",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"new",
"Promise",
"(",
"resolve",
"=>",
"app",
".",
"listen",
"(",
"port",
",",
"emitRungEmoji",
"&",
"resolve",
")",
")",
".",
"then",
"(",
"~",
"watchChanges",
"(",
"io",
",",
"params",
")",
")",
";",
"}"
] | Starts the stream server using sockets
@param {Object} alerts
@param {Object} params
@param {Number} port
@param {Object} resources
@return {Promise} | [
"Starts",
"the",
"stream",
"server",
"using",
"sockets"
] | c8906bb6733bdd5bcea2e9b54ed48f26ae1526d5 | https://github.com/rung-tools/rung-cli/blob/c8906bb6733bdd5bcea2e9b54ed48f26ae1526d5/src/live.js#L104-L119 | train |
rung-tools/rung-cli | src/cli.js | cli | function cli(args) {
const { _: [command] } = args;
return getModule(command).default(args)
.catch(err => {
getModule('input').emitError(err.message);
process.exit(1);
});
} | javascript | function cli(args) {
const { _: [command] } = args;
return getModule(command).default(args)
.catch(err => {
getModule('input').emitError(err.message);
process.exit(1);
});
} | [
"function",
"cli",
"(",
"args",
")",
"{",
"const",
"{",
"_",
":",
"[",
"command",
"]",
"}",
"=",
"args",
";",
"return",
"getModule",
"(",
"command",
")",
".",
"default",
"(",
"args",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"getModule",
"(",
"'input'",
")",
".",
"emitError",
"(",
"err",
".",
"message",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
")",
";",
"}"
] | Entry point of Rung CLI
@param {Object} args | [
"Entry",
"point",
"of",
"Rung",
"CLI"
] | c8906bb6733bdd5bcea2e9b54ed48f26ae1526d5 | https://github.com/rung-tools/rung-cli/blob/c8906bb6733bdd5bcea2e9b54ed48f26ae1526d5/src/cli.js#L18-L25 | train |
drkibitz/node-pixi | src/pixi/InteractionManager.js | InteractionManager | function InteractionManager(stage)
{
/**
* a refference to the stage
*
* @property stage
* @type Stage
*/
this.stage = stage;
/**
* the mouse data
*
* @property mouse
* @type InteractionData
*/
this.mouse = new InteractionData();
/**
* an object that stores current touches (InteractionData) by id reference
*
* @property touchs
* @type Object
*/
this.touchs = {};
// helpers
this.tempPoint = new Point();
//this.tempMatrix = mat3.create();
this.mouseoverEnabled = true;
//tiny little interactiveData pool!
this.pool = [];
this.interactiveItems = [];
this.interactionDOMElement = null;
this.last = 0;
} | javascript | function InteractionManager(stage)
{
/**
* a refference to the stage
*
* @property stage
* @type Stage
*/
this.stage = stage;
/**
* the mouse data
*
* @property mouse
* @type InteractionData
*/
this.mouse = new InteractionData();
/**
* an object that stores current touches (InteractionData) by id reference
*
* @property touchs
* @type Object
*/
this.touchs = {};
// helpers
this.tempPoint = new Point();
//this.tempMatrix = mat3.create();
this.mouseoverEnabled = true;
//tiny little interactiveData pool!
this.pool = [];
this.interactiveItems = [];
this.interactionDOMElement = null;
this.last = 0;
} | [
"function",
"InteractionManager",
"(",
"stage",
")",
"{",
"this",
".",
"stage",
"=",
"stage",
";",
"this",
".",
"mouse",
"=",
"new",
"InteractionData",
"(",
")",
";",
"this",
".",
"touchs",
"=",
"{",
"}",
";",
"this",
".",
"tempPoint",
"=",
"new",
"Point",
"(",
")",
";",
"this",
".",
"mouseoverEnabled",
"=",
"true",
";",
"this",
".",
"pool",
"=",
"[",
"]",
";",
"this",
".",
"interactiveItems",
"=",
"[",
"]",
";",
"this",
".",
"interactionDOMElement",
"=",
"null",
";",
"this",
".",
"last",
"=",
"0",
";",
"}"
] | The interaction manager deals with mouse and touch events. Any DisplayObject can be interactive
This manager also supports multitouch.
@class InteractionManager
@constructor
@param stage {Stage} The stage to handle interactions | [
"The",
"interaction",
"manager",
"deals",
"with",
"mouse",
"and",
"touch",
"events",
".",
"Any",
"DisplayObject",
"can",
"be",
"interactive",
"This",
"manager",
"also",
"supports",
"multitouch",
"."
] | 2ddb5361c50293419a46a76bf4771cecd6d9aef4 | https://github.com/drkibitz/node-pixi/blob/2ddb5361c50293419a46a76bf4771cecd6d9aef4/src/pixi/InteractionManager.js#L76-L115 | train |
drkibitz/node-pixi | src/pixi/textures/RenderTexture.js | RenderTexture | function RenderTexture(width, height)
{
EventTarget.call( this );
this.width = width || 100;
this.height = height || 100;
this.identityMatrix = mat3.create();
this.frame = new Rectangle(0, 0, this.width, this.height);
if(globals.gl)
{
this.initWebGL();
}
else
{
this.initCanvas();
}
} | javascript | function RenderTexture(width, height)
{
EventTarget.call( this );
this.width = width || 100;
this.height = height || 100;
this.identityMatrix = mat3.create();
this.frame = new Rectangle(0, 0, this.width, this.height);
if(globals.gl)
{
this.initWebGL();
}
else
{
this.initCanvas();
}
} | [
"function",
"RenderTexture",
"(",
"width",
",",
"height",
")",
"{",
"EventTarget",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"width",
"=",
"width",
"||",
"100",
";",
"this",
".",
"height",
"=",
"height",
"||",
"100",
";",
"this",
".",
"identityMatrix",
"=",
"mat3",
".",
"create",
"(",
")",
";",
"this",
".",
"frame",
"=",
"new",
"Rectangle",
"(",
"0",
",",
"0",
",",
"this",
".",
"width",
",",
"this",
".",
"height",
")",
";",
"if",
"(",
"globals",
".",
"gl",
")",
"{",
"this",
".",
"initWebGL",
"(",
")",
";",
"}",
"else",
"{",
"this",
".",
"initCanvas",
"(",
")",
";",
"}",
"}"
] | A RenderTexture is a special texture that allows any pixi displayObject to be rendered to it.
__Hint__: All DisplayObjects (exmpl. Sprites) that renders on RenderTexture should be preloaded.
Otherwise black rectangles will be drawn instead.
RenderTexture takes snapshot of DisplayObject passed to render method. If DisplayObject is passed to render method, position and rotation of it will be ignored. For example:
var renderTexture = new RenderTexture(800, 600);
var sprite = Sprite.fromImage("spinObj_01.png");
sprite.position.x = 800/2;
sprite.position.y = 600/2;
sprite.anchor.x = 0.5;
sprite.anchor.y = 0.5;
renderTexture.render(sprite);
Sprite in this case will be rendered to 0,0 position. To render this sprite at center DisplayObjectContainer should be used:
var doc = new DisplayObjectContainer();
doc.addChild(sprite);
renderTexture.render(doc); // Renders to center of renderTexture
@class RenderTexture
@extends Texture
@constructor
@param width {Number} The width of the render texture
@param height {Number} The height of the render texture | [
"A",
"RenderTexture",
"is",
"a",
"special",
"texture",
"that",
"allows",
"any",
"pixi",
"displayObject",
"to",
"be",
"rendered",
"to",
"it",
"."
] | 2ddb5361c50293419a46a76bf4771cecd6d9aef4 | https://github.com/drkibitz/node-pixi/blob/2ddb5361c50293419a46a76bf4771cecd6d9aef4/src/pixi/textures/RenderTexture.js#L45-L64 | train |
drkibitz/node-pixi | src/pixi/display/MovieClip.js | MovieClip | function MovieClip(textures)
{
Sprite.call(this, textures[0]);
/**
* The array of textures that make up the animation
*
* @property textures
* @type Array
*/
this.textures = textures;
/**
* The speed that the MovieClip will play at. Higher is faster, lower is slower
*
* @property animationSpeed
* @type Number
* @default 1
*/
this.animationSpeed = 1;
/**
* Whether or not the movie clip repeats after playing.
*
* @property loop
* @type Boolean
* @default true
*/
this.loop = true;
/**
* Function to call when a MovieClip finishes playing
*
* @property onComplete
* @type Function
*/
this.onComplete = null;
/**
* [read-only] The index MovieClips current frame (this may not have to be a whole number)
*
* @property currentFrame
* @type Number
* @default 0
* @readOnly
*/
this.currentFrame = 0;
/**
* [read-only] Indicates if the MovieClip is currently playing
*
* @property playing
* @type Boolean
* @readOnly
*/
this.playing = false;
} | javascript | function MovieClip(textures)
{
Sprite.call(this, textures[0]);
/**
* The array of textures that make up the animation
*
* @property textures
* @type Array
*/
this.textures = textures;
/**
* The speed that the MovieClip will play at. Higher is faster, lower is slower
*
* @property animationSpeed
* @type Number
* @default 1
*/
this.animationSpeed = 1;
/**
* Whether or not the movie clip repeats after playing.
*
* @property loop
* @type Boolean
* @default true
*/
this.loop = true;
/**
* Function to call when a MovieClip finishes playing
*
* @property onComplete
* @type Function
*/
this.onComplete = null;
/**
* [read-only] The index MovieClips current frame (this may not have to be a whole number)
*
* @property currentFrame
* @type Number
* @default 0
* @readOnly
*/
this.currentFrame = 0;
/**
* [read-only] Indicates if the MovieClip is currently playing
*
* @property playing
* @type Boolean
* @readOnly
*/
this.playing = false;
} | [
"function",
"MovieClip",
"(",
"textures",
")",
"{",
"Sprite",
".",
"call",
"(",
"this",
",",
"textures",
"[",
"0",
"]",
")",
";",
"this",
".",
"textures",
"=",
"textures",
";",
"this",
".",
"animationSpeed",
"=",
"1",
";",
"this",
".",
"loop",
"=",
"true",
";",
"this",
".",
"onComplete",
"=",
"null",
";",
"this",
".",
"currentFrame",
"=",
"0",
";",
"this",
".",
"playing",
"=",
"false",
";",
"}"
] | A MovieClip is a simple way to display an animation depicted by a list of textures.
@class MovieClip
@extends Sprite
@constructor
@param textures {Array<Texture>} an array of {Texture} objects that make up the animation | [
"A",
"MovieClip",
"is",
"a",
"simple",
"way",
"to",
"display",
"an",
"animation",
"depicted",
"by",
"a",
"list",
"of",
"textures",
"."
] | 2ddb5361c50293419a46a76bf4771cecd6d9aef4 | https://github.com/drkibitz/node-pixi/blob/2ddb5361c50293419a46a76bf4771cecd6d9aef4/src/pixi/display/MovieClip.js#L16-L72 | train |
drkibitz/node-pixi | src/pixi/filters/AbstractFilter.js | AbstractFilter | function AbstractFilter(fragmentSrc, uniforms)
{
/**
* An array of passes - some filters contain a few steps this array simply stores the steps in a liniear fashion.
* For example the blur filter has two passes blurX and blurY.
* @property passes
* @type Array an array of filter objects
* @private
*/
this.passes = [this];
this.dirty = true;
this.padding = 0;
/**
@property uniforms
@private
*/
this.uniforms = uniforms || {};
this.fragmentSrc = fragmentSrc || [];
} | javascript | function AbstractFilter(fragmentSrc, uniforms)
{
/**
* An array of passes - some filters contain a few steps this array simply stores the steps in a liniear fashion.
* For example the blur filter has two passes blurX and blurY.
* @property passes
* @type Array an array of filter objects
* @private
*/
this.passes = [this];
this.dirty = true;
this.padding = 0;
/**
@property uniforms
@private
*/
this.uniforms = uniforms || {};
this.fragmentSrc = fragmentSrc || [];
} | [
"function",
"AbstractFilter",
"(",
"fragmentSrc",
",",
"uniforms",
")",
"{",
"this",
".",
"passes",
"=",
"[",
"this",
"]",
";",
"this",
".",
"dirty",
"=",
"true",
";",
"this",
".",
"padding",
"=",
"0",
";",
"this",
".",
"uniforms",
"=",
"uniforms",
"||",
"{",
"}",
";",
"this",
".",
"fragmentSrc",
"=",
"fragmentSrc",
"||",
"[",
"]",
";",
"}"
] | This is the base class for creating a pixi.js filter. Currently only webGL supports filters.
If you want to make a custom filter this should be your base class.
@class AbstractFilter
@constructor
@param fragmentSrc
@param uniforms | [
"This",
"is",
"the",
"base",
"class",
"for",
"creating",
"a",
"pixi",
".",
"js",
"filter",
".",
"Currently",
"only",
"webGL",
"supports",
"filters",
".",
"If",
"you",
"want",
"to",
"make",
"a",
"custom",
"filter",
"this",
"should",
"be",
"your",
"base",
"class",
"."
] | 2ddb5361c50293419a46a76bf4771cecd6d9aef4 | https://github.com/drkibitz/node-pixi/blob/2ddb5361c50293419a46a76bf4771cecd6d9aef4/src/pixi/filters/AbstractFilter.js#L14-L36 | train |
drkibitz/node-pixi | src/pixi/display/DisplayObject.js | DisplayObject | function DisplayObject()
{
this.last = this;
this.first = this;
/**
* The coordinate of the object relative to the local coordinates of the parent.
*
* @property position
* @type Point
*/
this.position = new Point();
/**
* The scale factor of the object.
*
* @property scale
* @type Point
*/
this.scale = new Point(1,1);//{x:1, y:1};
/**
* The pivot point of the displayObject that it rotates around
*
* @property pivot
* @type Point
*/
this.pivot = new Point(0,0);
/**
* The rotation of the object in radians.
*
* @property rotation
* @type Number
*/
this.rotation = 0;
/**
* The opacity of the object.
*
* @property alpha
* @type Number
*/
this.alpha = 1;
/**
* The visibility of the object.
*
* @property visible
* @type Boolean
*/
this.visible = true;
/**
* This is the defined area that will pick up mouse / touch events. It is null by default.
* Setting it is a neat way of optimising the hitTest function that the interactionManager will use (as it will not need to hit test all the children)
*
* @property hitArea
* @type Rectangle|Circle|Ellipse|Polygon
*/
this.hitArea = null;
/**
* This is used to indicate if the displayObject should display a mouse hand cursor on rollover
*
* @property buttonMode
* @type Boolean
*/
this.buttonMode = false;
/**
* Can this object be rendered
*
* @property renderable
* @type Boolean
*/
this.renderable = false;
/**
* [read-only] The display object container that contains this display object.
*
* @property parent
* @type DisplayObjectContainer
* @readOnly
*/
this.parent = null;
/**
* [read-only] The stage the display object is connected to, or undefined if it is not connected to the stage.
*
* @property stage
* @type Stage
* @readOnly
*/
this.stage = null;
/**
* [read-only] The multiplied alpha of the displayobject
*
* @property worldAlpha
* @type Number
* @readOnly
*/
this.worldAlpha = 1;
/**
* [read-only] Whether or not the object is interactive, do not toggle directly! use the `interactive` property
*
* @property _interactive
* @type Boolean
* @readOnly
* @private
*/
this._interactive = false;
this.defaultCursor = 'pointer';
/**
* [read-only] Current transform of the object based on world (parent) factors
*
* @property worldTransform
* @type Mat3
* @readOnly
* @private
*/
this.worldTransform = mat3.create();//mat3.identity();
/**
* [read-only] Current transform of the object locally
*
* @property localTransform
* @type Mat3
* @readOnly
* @private
*/
this.localTransform = mat3.create();//mat3.identity();
/**
* [NYI] Unkown
*
* @property color
* @type Array<>
* @private
*/
this.color = [];
/**
* [NYI] Holds whether or not this object is dynamic, for rendering optimization
*
* @property dynamic
* @type Boolean
* @private
*/
this.dynamic = true;
// chach that puppy!
this._sr = 0;
this._cr = 1;
this.filterArea = new Rectangle(0,0,1,1);
/*
* MOUSE Callbacks
*/
/**
* A callback that is used when the users clicks on the displayObject with their mouse
* @method click
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user clicks the mouse down over the sprite
* @method mousedown
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user releases the mouse that was over the displayObject
* for this callback to be fired the mouse must have been pressed down over the displayObject
* @method mouseup
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user releases the mouse that was over the displayObject but is no longer over the displayObject
* for this callback to be fired, The touch must have started over the displayObject
* @method mouseupoutside
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the users mouse rolls over the displayObject
* @method mouseover
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the users mouse leaves the displayObject
* @method mouseout
* @param interactionData {InteractionData}
*/
/*
* TOUCH Callbacks
*/
/**
* A callback that is used when the users taps on the sprite with their finger
* basically a touch version of click
* @method tap
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user touch's over the displayObject
* @method touchstart
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user releases a touch over the displayObject
* @method touchend
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user releases the touch that was over the displayObject
* for this callback to be fired, The touch must have started over the sprite
* @method touchendoutside
* @param interactionData {InteractionData}
*/
} | javascript | function DisplayObject()
{
this.last = this;
this.first = this;
/**
* The coordinate of the object relative to the local coordinates of the parent.
*
* @property position
* @type Point
*/
this.position = new Point();
/**
* The scale factor of the object.
*
* @property scale
* @type Point
*/
this.scale = new Point(1,1);//{x:1, y:1};
/**
* The pivot point of the displayObject that it rotates around
*
* @property pivot
* @type Point
*/
this.pivot = new Point(0,0);
/**
* The rotation of the object in radians.
*
* @property rotation
* @type Number
*/
this.rotation = 0;
/**
* The opacity of the object.
*
* @property alpha
* @type Number
*/
this.alpha = 1;
/**
* The visibility of the object.
*
* @property visible
* @type Boolean
*/
this.visible = true;
/**
* This is the defined area that will pick up mouse / touch events. It is null by default.
* Setting it is a neat way of optimising the hitTest function that the interactionManager will use (as it will not need to hit test all the children)
*
* @property hitArea
* @type Rectangle|Circle|Ellipse|Polygon
*/
this.hitArea = null;
/**
* This is used to indicate if the displayObject should display a mouse hand cursor on rollover
*
* @property buttonMode
* @type Boolean
*/
this.buttonMode = false;
/**
* Can this object be rendered
*
* @property renderable
* @type Boolean
*/
this.renderable = false;
/**
* [read-only] The display object container that contains this display object.
*
* @property parent
* @type DisplayObjectContainer
* @readOnly
*/
this.parent = null;
/**
* [read-only] The stage the display object is connected to, or undefined if it is not connected to the stage.
*
* @property stage
* @type Stage
* @readOnly
*/
this.stage = null;
/**
* [read-only] The multiplied alpha of the displayobject
*
* @property worldAlpha
* @type Number
* @readOnly
*/
this.worldAlpha = 1;
/**
* [read-only] Whether or not the object is interactive, do not toggle directly! use the `interactive` property
*
* @property _interactive
* @type Boolean
* @readOnly
* @private
*/
this._interactive = false;
this.defaultCursor = 'pointer';
/**
* [read-only] Current transform of the object based on world (parent) factors
*
* @property worldTransform
* @type Mat3
* @readOnly
* @private
*/
this.worldTransform = mat3.create();//mat3.identity();
/**
* [read-only] Current transform of the object locally
*
* @property localTransform
* @type Mat3
* @readOnly
* @private
*/
this.localTransform = mat3.create();//mat3.identity();
/**
* [NYI] Unkown
*
* @property color
* @type Array<>
* @private
*/
this.color = [];
/**
* [NYI] Holds whether or not this object is dynamic, for rendering optimization
*
* @property dynamic
* @type Boolean
* @private
*/
this.dynamic = true;
// chach that puppy!
this._sr = 0;
this._cr = 1;
this.filterArea = new Rectangle(0,0,1,1);
/*
* MOUSE Callbacks
*/
/**
* A callback that is used when the users clicks on the displayObject with their mouse
* @method click
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user clicks the mouse down over the sprite
* @method mousedown
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user releases the mouse that was over the displayObject
* for this callback to be fired the mouse must have been pressed down over the displayObject
* @method mouseup
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user releases the mouse that was over the displayObject but is no longer over the displayObject
* for this callback to be fired, The touch must have started over the displayObject
* @method mouseupoutside
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the users mouse rolls over the displayObject
* @method mouseover
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the users mouse leaves the displayObject
* @method mouseout
* @param interactionData {InteractionData}
*/
/*
* TOUCH Callbacks
*/
/**
* A callback that is used when the users taps on the sprite with their finger
* basically a touch version of click
* @method tap
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user touch's over the displayObject
* @method touchstart
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user releases a touch over the displayObject
* @method touchend
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user releases the touch that was over the displayObject
* for this callback to be fired, The touch must have started over the sprite
* @method touchendoutside
* @param interactionData {InteractionData}
*/
} | [
"function",
"DisplayObject",
"(",
")",
"{",
"this",
".",
"last",
"=",
"this",
";",
"this",
".",
"first",
"=",
"this",
";",
"this",
".",
"position",
"=",
"new",
"Point",
"(",
")",
";",
"this",
".",
"scale",
"=",
"new",
"Point",
"(",
"1",
",",
"1",
")",
";",
"this",
".",
"pivot",
"=",
"new",
"Point",
"(",
"0",
",",
"0",
")",
";",
"this",
".",
"rotation",
"=",
"0",
";",
"this",
".",
"alpha",
"=",
"1",
";",
"this",
".",
"visible",
"=",
"true",
";",
"this",
".",
"hitArea",
"=",
"null",
";",
"this",
".",
"buttonMode",
"=",
"false",
";",
"this",
".",
"renderable",
"=",
"false",
";",
"this",
".",
"parent",
"=",
"null",
";",
"this",
".",
"stage",
"=",
"null",
";",
"this",
".",
"worldAlpha",
"=",
"1",
";",
"this",
".",
"_interactive",
"=",
"false",
";",
"this",
".",
"defaultCursor",
"=",
"'pointer'",
";",
"this",
".",
"worldTransform",
"=",
"mat3",
".",
"create",
"(",
")",
";",
"this",
".",
"localTransform",
"=",
"mat3",
".",
"create",
"(",
")",
";",
"this",
".",
"color",
"=",
"[",
"]",
";",
"this",
".",
"dynamic",
"=",
"true",
";",
"this",
".",
"_sr",
"=",
"0",
";",
"this",
".",
"_cr",
"=",
"1",
";",
"this",
".",
"filterArea",
"=",
"new",
"Rectangle",
"(",
"0",
",",
"0",
",",
"1",
",",
"1",
")",
";",
"}"
] | The base class for all objects that are rendered on the screen.
@class DisplayObject
@constructor | [
"The",
"base",
"class",
"for",
"all",
"objects",
"that",
"are",
"rendered",
"on",
"the",
"screen",
"."
] | 2ddb5361c50293419a46a76bf4771cecd6d9aef4 | https://github.com/drkibitz/node-pixi/blob/2ddb5361c50293419a46a76bf4771cecd6d9aef4/src/pixi/display/DisplayObject.js#L18-L251 | train |
stampit-org/stamp | packages/privatize/index.js | function (fn, name) {
function proxiedFn() {
'use strict';
var fields = privates.get(this); // jshint ignore:line
return fn.apply(fields, arguments);
}
Object.defineProperty(proxiedFn, 'name', {
value: name,
configurable: true
});
return proxiedFn;
} | javascript | function (fn, name) {
function proxiedFn() {
'use strict';
var fields = privates.get(this); // jshint ignore:line
return fn.apply(fields, arguments);
}
Object.defineProperty(proxiedFn, 'name', {
value: name,
configurable: true
});
return proxiedFn;
} | [
"function",
"(",
"fn",
",",
"name",
")",
"{",
"function",
"proxiedFn",
"(",
")",
"{",
"'use strict'",
";",
"var",
"fields",
"=",
"privates",
".",
"get",
"(",
"this",
")",
";",
"return",
"fn",
".",
"apply",
"(",
"fields",
",",
"arguments",
")",
";",
"}",
"Object",
".",
"defineProperty",
"(",
"proxiedFn",
",",
"'name'",
",",
"{",
"value",
":",
"name",
",",
"configurable",
":",
"true",
"}",
")",
";",
"return",
"proxiedFn",
";",
"}"
] | WeakMap works in IE11, node 0.12 | [
"WeakMap",
"works",
"in",
"IE11",
"node",
"0",
".",
"12"
] | 7eb5ec0576e90ca17e5777a4ab9677d3478aa583 | https://github.com/stampit-org/stamp/blob/7eb5ec0576e90ca17e5777a4ab9677d3478aa583/packages/privatize/index.js#L4-L17 | train |
|
PepsRyuu/virtual-scrolling-tree | src/virtual-scrolling-tree/VirtualScrollingTree.js | prepareView | function prepareView() {
_(this).el = document.createElement('div');
_(this).el.setAttribute('class', 'VirtualScrollingTree');
let contentDiv = `<div class="VirtualScrollingTree-content"></div>`;
_(this).el.innerHTML = `
${_(this).smoothScrolling? '' : contentDiv}
<div class="VirtualScrollingTree-scrollbar ${_(this).scrollbarClass}">
${_(this).smoothScrolling? contentDiv : ''}
<div class="VirtualScrollingTree-scrollbarContent"></div>
</div>
`.replace(/\n\s+/g, '');
_(this).view = {
content: _(this).el.querySelector('.VirtualScrollingTree-content'),
scrollbar: _(this).el.querySelector('.VirtualScrollingTree-scrollbar'),
scrollbarContent: _(this).el.querySelector('.VirtualScrollingTree-scrollbarContent')
};
if (!_(this).smoothScrolling) {
_(this).view.content.addEventListener('wheel', e => {
_(this).view.scrollbar.scrollTop += e.deltaY;
}, true);
}
// Scrolling either the content with the middle mouse wheel, or manually
// scrolling the scrollbar directly should accomplish the same thing.
// Note it's important for this to come after the transform above.
// If it's not, when the DOM is being manipulated the scrollbar will jump.
let lastScrollTop = 0;
_(this).view.scrollbar.addEventListener('scroll', (e) => {
if (_(this).scrollLocked) {
return;
}
let newScrollTop = parseInt(_(this).view.scrollbar.scrollTop / _(this).itemHeight);
if (lastScrollTop !== newScrollTop) {
lastScrollTop = newScrollTop;
if (_(this).smoothScrolling) {
_(this).view.content.style.transform = `translateY(${newScrollTop * _(this).itemHeight}px)`;
}
requestData.call(this);
}
}, true);
_(this).parent.appendChild(_(this).el);
} | javascript | function prepareView() {
_(this).el = document.createElement('div');
_(this).el.setAttribute('class', 'VirtualScrollingTree');
let contentDiv = `<div class="VirtualScrollingTree-content"></div>`;
_(this).el.innerHTML = `
${_(this).smoothScrolling? '' : contentDiv}
<div class="VirtualScrollingTree-scrollbar ${_(this).scrollbarClass}">
${_(this).smoothScrolling? contentDiv : ''}
<div class="VirtualScrollingTree-scrollbarContent"></div>
</div>
`.replace(/\n\s+/g, '');
_(this).view = {
content: _(this).el.querySelector('.VirtualScrollingTree-content'),
scrollbar: _(this).el.querySelector('.VirtualScrollingTree-scrollbar'),
scrollbarContent: _(this).el.querySelector('.VirtualScrollingTree-scrollbarContent')
};
if (!_(this).smoothScrolling) {
_(this).view.content.addEventListener('wheel', e => {
_(this).view.scrollbar.scrollTop += e.deltaY;
}, true);
}
// Scrolling either the content with the middle mouse wheel, or manually
// scrolling the scrollbar directly should accomplish the same thing.
// Note it's important for this to come after the transform above.
// If it's not, when the DOM is being manipulated the scrollbar will jump.
let lastScrollTop = 0;
_(this).view.scrollbar.addEventListener('scroll', (e) => {
if (_(this).scrollLocked) {
return;
}
let newScrollTop = parseInt(_(this).view.scrollbar.scrollTop / _(this).itemHeight);
if (lastScrollTop !== newScrollTop) {
lastScrollTop = newScrollTop;
if (_(this).smoothScrolling) {
_(this).view.content.style.transform = `translateY(${newScrollTop * _(this).itemHeight}px)`;
}
requestData.call(this);
}
}, true);
_(this).parent.appendChild(_(this).el);
} | [
"function",
"prepareView",
"(",
")",
"{",
"_",
"(",
"this",
")",
".",
"el",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"_",
"(",
"this",
")",
".",
"el",
".",
"setAttribute",
"(",
"'class'",
",",
"'VirtualScrollingTree'",
")",
";",
"let",
"contentDiv",
"=",
"`",
"`",
";",
"_",
"(",
"this",
")",
".",
"el",
".",
"innerHTML",
"=",
"`",
"${",
"_",
"(",
"this",
")",
".",
"smoothScrolling",
"?",
"''",
":",
"contentDiv",
"}",
"${",
"_",
"(",
"this",
")",
".",
"scrollbarClass",
"}",
"${",
"_",
"(",
"this",
")",
".",
"smoothScrolling",
"?",
"contentDiv",
":",
"''",
"}",
"`",
".",
"replace",
"(",
"/",
"\\n\\s+",
"/",
"g",
",",
"''",
")",
";",
"_",
"(",
"this",
")",
".",
"view",
"=",
"{",
"content",
":",
"_",
"(",
"this",
")",
".",
"el",
".",
"querySelector",
"(",
"'.VirtualScrollingTree-content'",
")",
",",
"scrollbar",
":",
"_",
"(",
"this",
")",
".",
"el",
".",
"querySelector",
"(",
"'.VirtualScrollingTree-scrollbar'",
")",
",",
"scrollbarContent",
":",
"_",
"(",
"this",
")",
".",
"el",
".",
"querySelector",
"(",
"'.VirtualScrollingTree-scrollbarContent'",
")",
"}",
";",
"if",
"(",
"!",
"_",
"(",
"this",
")",
".",
"smoothScrolling",
")",
"{",
"_",
"(",
"this",
")",
".",
"view",
".",
"content",
".",
"addEventListener",
"(",
"'wheel'",
",",
"e",
"=>",
"{",
"_",
"(",
"this",
")",
".",
"view",
".",
"scrollbar",
".",
"scrollTop",
"+=",
"e",
".",
"deltaY",
";",
"}",
",",
"true",
")",
";",
"}",
"let",
"lastScrollTop",
"=",
"0",
";",
"_",
"(",
"this",
")",
".",
"view",
".",
"scrollbar",
".",
"addEventListener",
"(",
"'scroll'",
",",
"(",
"e",
")",
"=>",
"{",
"if",
"(",
"_",
"(",
"this",
")",
".",
"scrollLocked",
")",
"{",
"return",
";",
"}",
"let",
"newScrollTop",
"=",
"parseInt",
"(",
"_",
"(",
"this",
")",
".",
"view",
".",
"scrollbar",
".",
"scrollTop",
"/",
"_",
"(",
"this",
")",
".",
"itemHeight",
")",
";",
"if",
"(",
"lastScrollTop",
"!==",
"newScrollTop",
")",
"{",
"lastScrollTop",
"=",
"newScrollTop",
";",
"if",
"(",
"_",
"(",
"this",
")",
".",
"smoothScrolling",
")",
"{",
"_",
"(",
"this",
")",
".",
"view",
".",
"content",
".",
"style",
".",
"transform",
"=",
"`",
"${",
"newScrollTop",
"*",
"_",
"(",
"this",
")",
".",
"itemHeight",
"}",
"`",
";",
"}",
"requestData",
".",
"call",
"(",
"this",
")",
";",
"}",
"}",
",",
"true",
")",
";",
"_",
"(",
"this",
")",
".",
"parent",
".",
"appendChild",
"(",
"_",
"(",
"this",
")",
".",
"el",
")",
";",
"}"
] | Creates a shortcut view object which we can use to access
our DOM elements. Also sets up event handlers for the content.
@method prepareView
@private | [
"Creates",
"a",
"shortcut",
"view",
"object",
"which",
"we",
"can",
"use",
"to",
"access",
"our",
"DOM",
"elements",
".",
"Also",
"sets",
"up",
"event",
"handlers",
"for",
"the",
"content",
"."
] | bc3d5ff20eecae19b7fc13fc233d9ea33990c503 | https://github.com/PepsRyuu/virtual-scrolling-tree/blob/bc3d5ff20eecae19b7fc13fc233d9ea33990c503/src/virtual-scrolling-tree/VirtualScrollingTree.js#L171-L220 | train |
PepsRyuu/virtual-scrolling-tree | src/virtual-scrolling-tree/VirtualScrollingTree.js | updateViewDimensions | function updateViewDimensions(totalItems) {
let visibleItems = Math.floor(_(this).parent.offsetHeight / _(this).itemHeight);
_(this).view.scrollbar.style.height = visibleItems * _(this).itemHeight + 'px';
_(this).view.scrollbarContent.style.height = totalItems * _(this).itemHeight + 'px';
let scrollbarWidth = totalItems < visibleItems? 0 : getNativeScrollbarWidth.call(this);
if (!_(this).smoothScrolling) {
_(this).view.content.style.width = Math.floor(_(this).el.getBoundingClientRect().width) - scrollbarWidth - 1 + 'px';
_(this).view.scrollbar.style.width = scrollbarWidth + 1 + 'px';
// Not needed for smooth
_(this).view.content.style.height = visibleItems * _(this).itemHeight + 'px';
} else {
_(this).view.scrollbar.style.width = '100%';
_(this).view.content.style.width = 'calc(100% - 1px)';
}
} | javascript | function updateViewDimensions(totalItems) {
let visibleItems = Math.floor(_(this).parent.offsetHeight / _(this).itemHeight);
_(this).view.scrollbar.style.height = visibleItems * _(this).itemHeight + 'px';
_(this).view.scrollbarContent.style.height = totalItems * _(this).itemHeight + 'px';
let scrollbarWidth = totalItems < visibleItems? 0 : getNativeScrollbarWidth.call(this);
if (!_(this).smoothScrolling) {
_(this).view.content.style.width = Math.floor(_(this).el.getBoundingClientRect().width) - scrollbarWidth - 1 + 'px';
_(this).view.scrollbar.style.width = scrollbarWidth + 1 + 'px';
// Not needed for smooth
_(this).view.content.style.height = visibleItems * _(this).itemHeight + 'px';
} else {
_(this).view.scrollbar.style.width = '100%';
_(this).view.content.style.width = 'calc(100% - 1px)';
}
} | [
"function",
"updateViewDimensions",
"(",
"totalItems",
")",
"{",
"let",
"visibleItems",
"=",
"Math",
".",
"floor",
"(",
"_",
"(",
"this",
")",
".",
"parent",
".",
"offsetHeight",
"/",
"_",
"(",
"this",
")",
".",
"itemHeight",
")",
";",
"_",
"(",
"this",
")",
".",
"view",
".",
"scrollbar",
".",
"style",
".",
"height",
"=",
"visibleItems",
"*",
"_",
"(",
"this",
")",
".",
"itemHeight",
"+",
"'px'",
";",
"_",
"(",
"this",
")",
".",
"view",
".",
"scrollbarContent",
".",
"style",
".",
"height",
"=",
"totalItems",
"*",
"_",
"(",
"this",
")",
".",
"itemHeight",
"+",
"'px'",
";",
"let",
"scrollbarWidth",
"=",
"totalItems",
"<",
"visibleItems",
"?",
"0",
":",
"getNativeScrollbarWidth",
".",
"call",
"(",
"this",
")",
";",
"if",
"(",
"!",
"_",
"(",
"this",
")",
".",
"smoothScrolling",
")",
"{",
"_",
"(",
"this",
")",
".",
"view",
".",
"content",
".",
"style",
".",
"width",
"=",
"Math",
".",
"floor",
"(",
"_",
"(",
"this",
")",
".",
"el",
".",
"getBoundingClientRect",
"(",
")",
".",
"width",
")",
"-",
"scrollbarWidth",
"-",
"1",
"+",
"'px'",
";",
"_",
"(",
"this",
")",
".",
"view",
".",
"scrollbar",
".",
"style",
".",
"width",
"=",
"scrollbarWidth",
"+",
"1",
"+",
"'px'",
";",
"_",
"(",
"this",
")",
".",
"view",
".",
"content",
".",
"style",
".",
"height",
"=",
"visibleItems",
"*",
"_",
"(",
"this",
")",
".",
"itemHeight",
"+",
"'px'",
";",
"}",
"else",
"{",
"_",
"(",
"this",
")",
".",
"view",
".",
"scrollbar",
".",
"style",
".",
"width",
"=",
"'100%'",
";",
"_",
"(",
"this",
")",
".",
"view",
".",
"content",
".",
"style",
".",
"width",
"=",
"'calc(100% - 1px)'",
";",
"}",
"}"
] | Updates the width of the tree to match its containing element.
@method updateViewDimensions
@private | [
"Updates",
"the",
"width",
"of",
"the",
"tree",
"to",
"match",
"its",
"containing",
"element",
"."
] | bc3d5ff20eecae19b7fc13fc233d9ea33990c503 | https://github.com/PepsRyuu/virtual-scrolling-tree/blob/bc3d5ff20eecae19b7fc13fc233d9ea33990c503/src/virtual-scrolling-tree/VirtualScrollingTree.js#L228-L245 | train |
PepsRyuu/virtual-scrolling-tree | src/virtual-scrolling-tree/VirtualScrollingTree.js | getNativeScrollbarWidth | function getNativeScrollbarWidth() {
let outer = document.createElement('div');
outer.style.overflowY = 'scroll';
outer.setAttribute('class', _(this).scrollbarClass);
outer.style.visibility = 'hidden';
outer.style.width = '100px';
document.body.appendChild(outer);
let content = document.createElement('div');
outer.appendChild(content);
var width = 100 - Math.floor(content.getBoundingClientRect().width);
document.body.removeChild(outer);
return width;
} | javascript | function getNativeScrollbarWidth() {
let outer = document.createElement('div');
outer.style.overflowY = 'scroll';
outer.setAttribute('class', _(this).scrollbarClass);
outer.style.visibility = 'hidden';
outer.style.width = '100px';
document.body.appendChild(outer);
let content = document.createElement('div');
outer.appendChild(content);
var width = 100 - Math.floor(content.getBoundingClientRect().width);
document.body.removeChild(outer);
return width;
} | [
"function",
"getNativeScrollbarWidth",
"(",
")",
"{",
"let",
"outer",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"outer",
".",
"style",
".",
"overflowY",
"=",
"'scroll'",
";",
"outer",
".",
"setAttribute",
"(",
"'class'",
",",
"_",
"(",
"this",
")",
".",
"scrollbarClass",
")",
";",
"outer",
".",
"style",
".",
"visibility",
"=",
"'hidden'",
";",
"outer",
".",
"style",
".",
"width",
"=",
"'100px'",
";",
"document",
".",
"body",
".",
"appendChild",
"(",
"outer",
")",
";",
"let",
"content",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"outer",
".",
"appendChild",
"(",
"content",
")",
";",
"var",
"width",
"=",
"100",
"-",
"Math",
".",
"floor",
"(",
"content",
".",
"getBoundingClientRect",
"(",
")",
".",
"width",
")",
";",
"document",
".",
"body",
".",
"removeChild",
"(",
"outer",
")",
";",
"return",
"width",
";",
"}"
] | Creates a div which is used to calculate the width
of the scrollbar for the current browser.
@method getNativeScrollbarWidth
@private
@return {number} | [
"Creates",
"a",
"div",
"which",
"is",
"used",
"to",
"calculate",
"the",
"width",
"of",
"the",
"scrollbar",
"for",
"the",
"current",
"browser",
"."
] | bc3d5ff20eecae19b7fc13fc233d9ea33990c503 | https://github.com/PepsRyuu/virtual-scrolling-tree/blob/bc3d5ff20eecae19b7fc13fc233d9ea33990c503/src/virtual-scrolling-tree/VirtualScrollingTree.js#L255-L267 | train |
PepsRyuu/virtual-scrolling-tree | src/virtual-scrolling-tree/VirtualScrollingTree.js | requestData | function requestData() {
let visible = Math.ceil(_(this).parent.offsetHeight / _(this).itemHeight);
let scrollIndex = Math.floor(_(this).view.scrollbar.scrollTop / _(this).itemHeight);
let request = buildRequest.call(this, scrollIndex, visible);
_(this).request = request;
_(this).onDataFetch(request, setData.bind(this));
} | javascript | function requestData() {
let visible = Math.ceil(_(this).parent.offsetHeight / _(this).itemHeight);
let scrollIndex = Math.floor(_(this).view.scrollbar.scrollTop / _(this).itemHeight);
let request = buildRequest.call(this, scrollIndex, visible);
_(this).request = request;
_(this).onDataFetch(request, setData.bind(this));
} | [
"function",
"requestData",
"(",
")",
"{",
"let",
"visible",
"=",
"Math",
".",
"ceil",
"(",
"_",
"(",
"this",
")",
".",
"parent",
".",
"offsetHeight",
"/",
"_",
"(",
"this",
")",
".",
"itemHeight",
")",
";",
"let",
"scrollIndex",
"=",
"Math",
".",
"floor",
"(",
"_",
"(",
"this",
")",
".",
"view",
".",
"scrollbar",
".",
"scrollTop",
"/",
"_",
"(",
"this",
")",
".",
"itemHeight",
")",
";",
"let",
"request",
"=",
"buildRequest",
".",
"call",
"(",
"this",
",",
"scrollIndex",
",",
"visible",
")",
";",
"_",
"(",
"this",
")",
".",
"request",
"=",
"request",
";",
"_",
"(",
"this",
")",
".",
"onDataFetch",
"(",
"request",
",",
"setData",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] | Builds query, and triggers the onDataFetch call for the developer.
When the developer calls success the data of the tree gets updated.
@method requestData
@private | [
"Builds",
"query",
"and",
"triggers",
"the",
"onDataFetch",
"call",
"for",
"the",
"developer",
".",
"When",
"the",
"developer",
"calls",
"success",
"the",
"data",
"of",
"the",
"tree",
"gets",
"updated",
"."
] | bc3d5ff20eecae19b7fc13fc233d9ea33990c503 | https://github.com/PepsRyuu/virtual-scrolling-tree/blob/bc3d5ff20eecae19b7fc13fc233d9ea33990c503/src/virtual-scrolling-tree/VirtualScrollingTree.js#L276-L282 | train |
PepsRyuu/virtual-scrolling-tree | src/virtual-scrolling-tree/VirtualScrollingTree.js | renderItem | function renderItem (element, data, updating) {
_(this).onItemRender(element, {
...data.original,
expanded: isExpanded.call(this, data.id),
indent: calculateLevel.call(this, data),
toggle: () => {
// Check to see if this item is expanded or not
let expanded = isExpanded.call(this, data.id);
if (expanded) {
collapseItem.call(this, data);
} else {
expandItem.call(this, data);
}
// Each time we expand or collapse we need to re-request data.
requestData.call(this);
}
}, updating);
} | javascript | function renderItem (element, data, updating) {
_(this).onItemRender(element, {
...data.original,
expanded: isExpanded.call(this, data.id),
indent: calculateLevel.call(this, data),
toggle: () => {
// Check to see if this item is expanded or not
let expanded = isExpanded.call(this, data.id);
if (expanded) {
collapseItem.call(this, data);
} else {
expandItem.call(this, data);
}
// Each time we expand or collapse we need to re-request data.
requestData.call(this);
}
}, updating);
} | [
"function",
"renderItem",
"(",
"element",
",",
"data",
",",
"updating",
")",
"{",
"_",
"(",
"this",
")",
".",
"onItemRender",
"(",
"element",
",",
"{",
"...",
"data",
".",
"original",
",",
"expanded",
":",
"isExpanded",
".",
"call",
"(",
"this",
",",
"data",
".",
"id",
")",
",",
"indent",
":",
"calculateLevel",
".",
"call",
"(",
"this",
",",
"data",
")",
",",
"toggle",
":",
"(",
")",
"=>",
"{",
"let",
"expanded",
"=",
"isExpanded",
".",
"call",
"(",
"this",
",",
"data",
".",
"id",
")",
";",
"if",
"(",
"expanded",
")",
"{",
"collapseItem",
".",
"call",
"(",
"this",
",",
"data",
")",
";",
"}",
"else",
"{",
"expandItem",
".",
"call",
"(",
"this",
",",
"data",
")",
";",
"}",
"requestData",
".",
"call",
"(",
"this",
")",
";",
"}",
"}",
",",
"updating",
")",
";",
"}"
] | Calls the onItemRender option.
@method renderItem
@private
@param {HTMLElement} element
@param {Object} data
@param {Boolean} updating | [
"Calls",
"the",
"onItemRender",
"option",
"."
] | bc3d5ff20eecae19b7fc13fc233d9ea33990c503 | https://github.com/PepsRyuu/virtual-scrolling-tree/blob/bc3d5ff20eecae19b7fc13fc233d9ea33990c503/src/virtual-scrolling-tree/VirtualScrollingTree.js#L428-L446 | train |
PepsRyuu/virtual-scrolling-tree | src/virtual-scrolling-tree/VirtualScrollingTree.js | createItem | function createItem (data) {
let itemEl = document.createElement('div');
itemEl.setAttribute('class', 'VirtualScrollingTree-item');
renderItem.call(this, itemEl, data);
return {
id: data.id,
el: itemEl
};
} | javascript | function createItem (data) {
let itemEl = document.createElement('div');
itemEl.setAttribute('class', 'VirtualScrollingTree-item');
renderItem.call(this, itemEl, data);
return {
id: data.id,
el: itemEl
};
} | [
"function",
"createItem",
"(",
"data",
")",
"{",
"let",
"itemEl",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"itemEl",
".",
"setAttribute",
"(",
"'class'",
",",
"'VirtualScrollingTree-item'",
")",
";",
"renderItem",
".",
"call",
"(",
"this",
",",
"itemEl",
",",
"data",
")",
";",
"return",
"{",
"id",
":",
"data",
".",
"id",
",",
"el",
":",
"itemEl",
"}",
";",
"}"
] | Creates a HTMLElement to render an item into.
@method createItem
@private
@param {Object} data
@return {Object} | [
"Creates",
"a",
"HTMLElement",
"to",
"render",
"an",
"item",
"into",
"."
] | bc3d5ff20eecae19b7fc13fc233d9ea33990c503 | https://github.com/PepsRyuu/virtual-scrolling-tree/blob/bc3d5ff20eecae19b7fc13fc233d9ea33990c503/src/virtual-scrolling-tree/VirtualScrollingTree.js#L456-L466 | train |
PepsRyuu/virtual-scrolling-tree | src/virtual-scrolling-tree/VirtualScrollingTree.js | forEachExpansion | function forEachExpansion(expansions, fn) {
let impl = function(expansions) {
expansions.forEach((expansion) => {
fn(expansion);
impl(expansion.expansions);
});
};
impl(expansions);
} | javascript | function forEachExpansion(expansions, fn) {
let impl = function(expansions) {
expansions.forEach((expansion) => {
fn(expansion);
impl(expansion.expansions);
});
};
impl(expansions);
} | [
"function",
"forEachExpansion",
"(",
"expansions",
",",
"fn",
")",
"{",
"let",
"impl",
"=",
"function",
"(",
"expansions",
")",
"{",
"expansions",
".",
"forEach",
"(",
"(",
"expansion",
")",
"=>",
"{",
"fn",
"(",
"expansion",
")",
";",
"impl",
"(",
"expansion",
".",
"expansions",
")",
";",
"}",
")",
";",
"}",
";",
"impl",
"(",
"expansions",
")",
";",
"}"
] | Recursively iterate over the expansions and
execute the passed callback against it.
@method forEachExpansion
@private
@param {Array<Object>} expansions
@param {Functin} fn | [
"Recursively",
"iterate",
"over",
"the",
"expansions",
"and",
"execute",
"the",
"passed",
"callback",
"against",
"it",
"."
] | bc3d5ff20eecae19b7fc13fc233d9ea33990c503 | https://github.com/PepsRyuu/virtual-scrolling-tree/blob/bc3d5ff20eecae19b7fc13fc233d9ea33990c503/src/virtual-scrolling-tree/VirtualScrollingTree.js#L477-L486 | train |
PepsRyuu/virtual-scrolling-tree | src/virtual-scrolling-tree/VirtualScrollingTree.js | findExpansion | function findExpansion(id) {
let result;
forEachExpansion(_(this).expansions, (expansion) => {
if (expansion.id === id) {
result = expansion;
}
});
return result;
} | javascript | function findExpansion(id) {
let result;
forEachExpansion(_(this).expansions, (expansion) => {
if (expansion.id === id) {
result = expansion;
}
});
return result;
} | [
"function",
"findExpansion",
"(",
"id",
")",
"{",
"let",
"result",
";",
"forEachExpansion",
"(",
"_",
"(",
"this",
")",
".",
"expansions",
",",
"(",
"expansion",
")",
"=>",
"{",
"if",
"(",
"expansion",
".",
"id",
"===",
"id",
")",
"{",
"result",
"=",
"expansion",
";",
"}",
"}",
")",
";",
"return",
"result",
";",
"}"
] | Finds the expansion with the id specified.
@method findExpansion
@private
@param {String} id
@return {Object} | [
"Finds",
"the",
"expansion",
"with",
"the",
"id",
"specified",
"."
] | bc3d5ff20eecae19b7fc13fc233d9ea33990c503 | https://github.com/PepsRyuu/virtual-scrolling-tree/blob/bc3d5ff20eecae19b7fc13fc233d9ea33990c503/src/virtual-scrolling-tree/VirtualScrollingTree.js#L496-L506 | train |
PepsRyuu/virtual-scrolling-tree | src/virtual-scrolling-tree/VirtualScrollingTree.js | collapseItem | function collapseItem(data) {
let parentExpansions = findExpansion.call(this, data.parent).expansions;
let index = parentExpansions.findIndex((expansion) => {
return expansion.id === data.id;
});
parentExpansions.splice(index, 1);
} | javascript | function collapseItem(data) {
let parentExpansions = findExpansion.call(this, data.parent).expansions;
let index = parentExpansions.findIndex((expansion) => {
return expansion.id === data.id;
});
parentExpansions.splice(index, 1);
} | [
"function",
"collapseItem",
"(",
"data",
")",
"{",
"let",
"parentExpansions",
"=",
"findExpansion",
".",
"call",
"(",
"this",
",",
"data",
".",
"parent",
")",
".",
"expansions",
";",
"let",
"index",
"=",
"parentExpansions",
".",
"findIndex",
"(",
"(",
"expansion",
")",
"=>",
"{",
"return",
"expansion",
".",
"id",
"===",
"data",
".",
"id",
";",
"}",
")",
";",
"parentExpansions",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"}"
] | Removes item to list of expansions.
@method collapseItem
@private
@params {Object} data | [
"Removes",
"item",
"to",
"list",
"of",
"expansions",
"."
] | bc3d5ff20eecae19b7fc13fc233d9ea33990c503 | https://github.com/PepsRyuu/virtual-scrolling-tree/blob/bc3d5ff20eecae19b7fc13fc233d9ea33990c503/src/virtual-scrolling-tree/VirtualScrollingTree.js#L539-L547 | train |
PepsRyuu/virtual-scrolling-tree | src/virtual-scrolling-tree/VirtualScrollingTree.js | expandItem | function expandItem(data) {
// Cloning to avoid modification of the original data item.
data = JSON.parse(JSON.stringify(data));
if (!data.expansions) {
data.expansions = [];
}
// Expansions are stored in a tree structure.
let obj = findExpansion.call(this, data.parent);
obj.expansions.push(data);
} | javascript | function expandItem(data) {
// Cloning to avoid modification of the original data item.
data = JSON.parse(JSON.stringify(data));
if (!data.expansions) {
data.expansions = [];
}
// Expansions are stored in a tree structure.
let obj = findExpansion.call(this, data.parent);
obj.expansions.push(data);
} | [
"function",
"expandItem",
"(",
"data",
")",
"{",
"data",
"=",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"data",
")",
")",
";",
"if",
"(",
"!",
"data",
".",
"expansions",
")",
"{",
"data",
".",
"expansions",
"=",
"[",
"]",
";",
"}",
"let",
"obj",
"=",
"findExpansion",
".",
"call",
"(",
"this",
",",
"data",
".",
"parent",
")",
";",
"obj",
".",
"expansions",
".",
"push",
"(",
"data",
")",
";",
"}"
] | Adds item to list of expansions.
@method expandItem
@private
@params {Object} data | [
"Adds",
"item",
"to",
"list",
"of",
"expansions",
"."
] | bc3d5ff20eecae19b7fc13fc233d9ea33990c503 | https://github.com/PepsRyuu/virtual-scrolling-tree/blob/bc3d5ff20eecae19b7fc13fc233d9ea33990c503/src/virtual-scrolling-tree/VirtualScrollingTree.js#L556-L567 | train |
PepsRyuu/virtual-scrolling-tree | src/virtual-scrolling-tree/VirtualScrollingTree.js | sortExpansions | function sortExpansions() {
let impl = function(expansions) {
expansions.sort((a, b) => {
return a.offset - b.offset;
});
for (let i = 0; i < expansions.length; i++) {
impl(expansions[i].expansions);
}
}
impl(_(this).expansions);
} | javascript | function sortExpansions() {
let impl = function(expansions) {
expansions.sort((a, b) => {
return a.offset - b.offset;
});
for (let i = 0; i < expansions.length; i++) {
impl(expansions[i].expansions);
}
}
impl(_(this).expansions);
} | [
"function",
"sortExpansions",
"(",
")",
"{",
"let",
"impl",
"=",
"function",
"(",
"expansions",
")",
"{",
"expansions",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"{",
"return",
"a",
".",
"offset",
"-",
"b",
".",
"offset",
";",
"}",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"expansions",
".",
"length",
";",
"i",
"++",
")",
"{",
"impl",
"(",
"expansions",
"[",
"i",
"]",
".",
"expansions",
")",
";",
"}",
"}",
"impl",
"(",
"_",
"(",
"this",
")",
".",
"expansions",
")",
";",
"}"
] | Sorting expansions makes the query more accurate.
@method sortExpansions
@private | [
"Sorting",
"expansions",
"makes",
"the",
"query",
"more",
"accurate",
"."
] | bc3d5ff20eecae19b7fc13fc233d9ea33990c503 | https://github.com/PepsRyuu/virtual-scrolling-tree/blob/bc3d5ff20eecae19b7fc13fc233d9ea33990c503/src/virtual-scrolling-tree/VirtualScrollingTree.js#L575-L587 | train |
PepsRyuu/virtual-scrolling-tree | src/virtual-scrolling-tree/VirtualScrollingTree.js | calculateExpansions | function calculateExpansions() {
let impl = function(expansions, parentStart, parentLevel) {
expansions.forEach((expansion, index) => {
expansion._level = parentLevel;
// We need to calculate the start position of this expansion. The start
// position isn't just the offset of the item relative to the parent, but
// also takes into account expanded items above it.
//
// One easy way to do this is to just check the previous item and get its end index.
// We fetch the one on the same level not above or below. That should in theory
// already have a start/end relative to the parent. If there isn't a previous sibling
// then we will take the parent start value. Add onto this the offset for the item
// and we've got our starting value.
//
// eg.
// Item 1 <-- start 0, end 0
// Item 2 <-- start 2, end 8
// Item 2.1 <-- start 3, end 3
// Item 2.1.1
// Item 2.2
// Item 2.3 <-- start 6, end 6
// Item 2.3.1
// Item 2.4 <-- start 8, end 8
// Item 2.4.1
// Item 3
// Item 4 <-- start 11, end 12
// Item 4.1
// Item 4.2
let start, end;
let prevSibling = expansions[index - 1];
if (prevSibling) {
start = prevSibling._end + 1 + (expansion.offset - prevSibling.offset);
} else {
start = parentStart + 1 + expansion.offset;
}
expansion._start = start;
// To calculate the ending, we recursively add the children
// for this expansion, and that will be added to the start value.
let totalChildren = expansion.children;
forEachExpansion(expansion.expansions, (expansion) => {
totalChildren += expansion.children;
});
// We add the children and substract one. We subtract one because
// the start is one of the children.
expansion._end = expansion._start + totalChildren - 1;
// Repeat this recursively for all of the nested expansions.
// The nested expansions will have a relative start to this
// expansion.
impl(expansion.expansions, expansion._start, parentLevel + 1);
});
}
impl(_(this).expansions, -1, 0);
} | javascript | function calculateExpansions() {
let impl = function(expansions, parentStart, parentLevel) {
expansions.forEach((expansion, index) => {
expansion._level = parentLevel;
// We need to calculate the start position of this expansion. The start
// position isn't just the offset of the item relative to the parent, but
// also takes into account expanded items above it.
//
// One easy way to do this is to just check the previous item and get its end index.
// We fetch the one on the same level not above or below. That should in theory
// already have a start/end relative to the parent. If there isn't a previous sibling
// then we will take the parent start value. Add onto this the offset for the item
// and we've got our starting value.
//
// eg.
// Item 1 <-- start 0, end 0
// Item 2 <-- start 2, end 8
// Item 2.1 <-- start 3, end 3
// Item 2.1.1
// Item 2.2
// Item 2.3 <-- start 6, end 6
// Item 2.3.1
// Item 2.4 <-- start 8, end 8
// Item 2.4.1
// Item 3
// Item 4 <-- start 11, end 12
// Item 4.1
// Item 4.2
let start, end;
let prevSibling = expansions[index - 1];
if (prevSibling) {
start = prevSibling._end + 1 + (expansion.offset - prevSibling.offset);
} else {
start = parentStart + 1 + expansion.offset;
}
expansion._start = start;
// To calculate the ending, we recursively add the children
// for this expansion, and that will be added to the start value.
let totalChildren = expansion.children;
forEachExpansion(expansion.expansions, (expansion) => {
totalChildren += expansion.children;
});
// We add the children and substract one. We subtract one because
// the start is one of the children.
expansion._end = expansion._start + totalChildren - 1;
// Repeat this recursively for all of the nested expansions.
// The nested expansions will have a relative start to this
// expansion.
impl(expansion.expansions, expansion._start, parentLevel + 1);
});
}
impl(_(this).expansions, -1, 0);
} | [
"function",
"calculateExpansions",
"(",
")",
"{",
"let",
"impl",
"=",
"function",
"(",
"expansions",
",",
"parentStart",
",",
"parentLevel",
")",
"{",
"expansions",
".",
"forEach",
"(",
"(",
"expansion",
",",
"index",
")",
"=>",
"{",
"expansion",
".",
"_level",
"=",
"parentLevel",
";",
"let",
"start",
",",
"end",
";",
"let",
"prevSibling",
"=",
"expansions",
"[",
"index",
"-",
"1",
"]",
";",
"if",
"(",
"prevSibling",
")",
"{",
"start",
"=",
"prevSibling",
".",
"_end",
"+",
"1",
"+",
"(",
"expansion",
".",
"offset",
"-",
"prevSibling",
".",
"offset",
")",
";",
"}",
"else",
"{",
"start",
"=",
"parentStart",
"+",
"1",
"+",
"expansion",
".",
"offset",
";",
"}",
"expansion",
".",
"_start",
"=",
"start",
";",
"let",
"totalChildren",
"=",
"expansion",
".",
"children",
";",
"forEachExpansion",
"(",
"expansion",
".",
"expansions",
",",
"(",
"expansion",
")",
"=>",
"{",
"totalChildren",
"+=",
"expansion",
".",
"children",
";",
"}",
")",
";",
"expansion",
".",
"_end",
"=",
"expansion",
".",
"_start",
"+",
"totalChildren",
"-",
"1",
";",
"impl",
"(",
"expansion",
".",
"expansions",
",",
"expansion",
".",
"_start",
",",
"parentLevel",
"+",
"1",
")",
";",
"}",
")",
";",
"}",
"impl",
"(",
"_",
"(",
"this",
")",
".",
"expansions",
",",
"-",
"1",
",",
"0",
")",
";",
"}"
] | Sorts and calculates the scroll indexes for the expansions.
@method calculateExpansions
@private | [
"Sorts",
"and",
"calculates",
"the",
"scroll",
"indexes",
"for",
"the",
"expansions",
"."
] | bc3d5ff20eecae19b7fc13fc233d9ea33990c503 | https://github.com/PepsRyuu/virtual-scrolling-tree/blob/bc3d5ff20eecae19b7fc13fc233d9ea33990c503/src/virtual-scrolling-tree/VirtualScrollingTree.js#L595-L653 | train |
PepsRyuu/virtual-scrolling-tree | src/virtual-scrolling-tree/VirtualScrollingTree.js | buildRequest | function buildRequest(scrollPos, viewport) {
// Variables
let queries = [];
let requestedTotal = 0;
let expanded = _(this).expansions;
sortExpansions.call(this);
calculateExpansions.call(this);
// One-dimensional collision detection.
// It checks to see if start/end are both either before
// the viewport, and after. If it's not before or after, it's colliding.
let inViewPort = function(v1, v2, e1, e2) {
return !((e1 < v1 && e2 < v1) || (e1 > v2 && e2 > v2));
};
let calculateExpansionQueries = function(expansions, parentQuery) {
expansions.forEach((e) => {
if (inViewPort(scrollPos, scrollPos + viewport, e._start, e._end)) {
// We want to find out how many items for this expansion are
// visible in the view port. To do this we find the first item that's
// visible, the last item that's visible, subtract them and cap it to the viewport size.
let start = Math.max(scrollPos, e._start);
let end = Math.min(scrollPos + viewport - 1, e._end);
let visible = Math.max(0, Math.min(end - start + 1, viewport));
if (parentQuery) {
// If there are nested children visible, we need to subtract
// this from the parent. Note that visible also includes any expanded
// children nested further because we're using the _start and _end
// values we've already calculated.
parentQuery.limit -= visible;
if (scrollPos > e._start) {
let notVisible = (e._end - e._start + 1) - visible;
if (notVisible > 0) {
parentQuery.offset -= notVisible;
}
}
}
// This query object is what's given to the end user.
// The parent represents who we want the children of.
// The offset is based on how much we've scrolled past the beginning.
// The limit is total items that are visible in the viewport.
let query = {
parent: e.id,
offset: scrollPos > e._start? scrollPos - e._start : 0,
limit: Math.min(visible, viewport)
};
queries.push(query);
calculateExpansionQueries(e.expansions, query);
} else if (scrollPos > e._end && parentQuery) {
// If we've completely scrolled past this object, just substract all of its expanded children from the parent offset.
parentQuery.offset -= (e._end - e._start + 1);
}
});
};
calculateExpansionQueries(_(this).expansions);
return queries;
} | javascript | function buildRequest(scrollPos, viewport) {
// Variables
let queries = [];
let requestedTotal = 0;
let expanded = _(this).expansions;
sortExpansions.call(this);
calculateExpansions.call(this);
// One-dimensional collision detection.
// It checks to see if start/end are both either before
// the viewport, and after. If it's not before or after, it's colliding.
let inViewPort = function(v1, v2, e1, e2) {
return !((e1 < v1 && e2 < v1) || (e1 > v2 && e2 > v2));
};
let calculateExpansionQueries = function(expansions, parentQuery) {
expansions.forEach((e) => {
if (inViewPort(scrollPos, scrollPos + viewport, e._start, e._end)) {
// We want to find out how many items for this expansion are
// visible in the view port. To do this we find the first item that's
// visible, the last item that's visible, subtract them and cap it to the viewport size.
let start = Math.max(scrollPos, e._start);
let end = Math.min(scrollPos + viewport - 1, e._end);
let visible = Math.max(0, Math.min(end - start + 1, viewport));
if (parentQuery) {
// If there are nested children visible, we need to subtract
// this from the parent. Note that visible also includes any expanded
// children nested further because we're using the _start and _end
// values we've already calculated.
parentQuery.limit -= visible;
if (scrollPos > e._start) {
let notVisible = (e._end - e._start + 1) - visible;
if (notVisible > 0) {
parentQuery.offset -= notVisible;
}
}
}
// This query object is what's given to the end user.
// The parent represents who we want the children of.
// The offset is based on how much we've scrolled past the beginning.
// The limit is total items that are visible in the viewport.
let query = {
parent: e.id,
offset: scrollPos > e._start? scrollPos - e._start : 0,
limit: Math.min(visible, viewport)
};
queries.push(query);
calculateExpansionQueries(e.expansions, query);
} else if (scrollPos > e._end && parentQuery) {
// If we've completely scrolled past this object, just substract all of its expanded children from the parent offset.
parentQuery.offset -= (e._end - e._start + 1);
}
});
};
calculateExpansionQueries(_(this).expansions);
return queries;
} | [
"function",
"buildRequest",
"(",
"scrollPos",
",",
"viewport",
")",
"{",
"let",
"queries",
"=",
"[",
"]",
";",
"let",
"requestedTotal",
"=",
"0",
";",
"let",
"expanded",
"=",
"_",
"(",
"this",
")",
".",
"expansions",
";",
"sortExpansions",
".",
"call",
"(",
"this",
")",
";",
"calculateExpansions",
".",
"call",
"(",
"this",
")",
";",
"let",
"inViewPort",
"=",
"function",
"(",
"v1",
",",
"v2",
",",
"e1",
",",
"e2",
")",
"{",
"return",
"!",
"(",
"(",
"e1",
"<",
"v1",
"&&",
"e2",
"<",
"v1",
")",
"||",
"(",
"e1",
">",
"v2",
"&&",
"e2",
">",
"v2",
")",
")",
";",
"}",
";",
"let",
"calculateExpansionQueries",
"=",
"function",
"(",
"expansions",
",",
"parentQuery",
")",
"{",
"expansions",
".",
"forEach",
"(",
"(",
"e",
")",
"=>",
"{",
"if",
"(",
"inViewPort",
"(",
"scrollPos",
",",
"scrollPos",
"+",
"viewport",
",",
"e",
".",
"_start",
",",
"e",
".",
"_end",
")",
")",
"{",
"let",
"start",
"=",
"Math",
".",
"max",
"(",
"scrollPos",
",",
"e",
".",
"_start",
")",
";",
"let",
"end",
"=",
"Math",
".",
"min",
"(",
"scrollPos",
"+",
"viewport",
"-",
"1",
",",
"e",
".",
"_end",
")",
";",
"let",
"visible",
"=",
"Math",
".",
"max",
"(",
"0",
",",
"Math",
".",
"min",
"(",
"end",
"-",
"start",
"+",
"1",
",",
"viewport",
")",
")",
";",
"if",
"(",
"parentQuery",
")",
"{",
"parentQuery",
".",
"limit",
"-=",
"visible",
";",
"if",
"(",
"scrollPos",
">",
"e",
".",
"_start",
")",
"{",
"let",
"notVisible",
"=",
"(",
"e",
".",
"_end",
"-",
"e",
".",
"_start",
"+",
"1",
")",
"-",
"visible",
";",
"if",
"(",
"notVisible",
">",
"0",
")",
"{",
"parentQuery",
".",
"offset",
"-=",
"notVisible",
";",
"}",
"}",
"}",
"let",
"query",
"=",
"{",
"parent",
":",
"e",
".",
"id",
",",
"offset",
":",
"scrollPos",
">",
"e",
".",
"_start",
"?",
"scrollPos",
"-",
"e",
".",
"_start",
":",
"0",
",",
"limit",
":",
"Math",
".",
"min",
"(",
"visible",
",",
"viewport",
")",
"}",
";",
"queries",
".",
"push",
"(",
"query",
")",
";",
"calculateExpansionQueries",
"(",
"e",
".",
"expansions",
",",
"query",
")",
";",
"}",
"else",
"if",
"(",
"scrollPos",
">",
"e",
".",
"_end",
"&&",
"parentQuery",
")",
"{",
"parentQuery",
".",
"offset",
"-=",
"(",
"e",
".",
"_end",
"-",
"e",
".",
"_start",
"+",
"1",
")",
";",
"}",
"}",
")",
";",
"}",
";",
"calculateExpansionQueries",
"(",
"_",
"(",
"this",
")",
".",
"expansions",
")",
";",
"return",
"queries",
";",
"}"
] | Calculates what's in the viewport and generates a series
of queries for the developer to respond to.
@method buildRequest
@private | [
"Calculates",
"what",
"s",
"in",
"the",
"viewport",
"and",
"generates",
"a",
"series",
"of",
"queries",
"for",
"the",
"developer",
"to",
"respond",
"to",
"."
] | bc3d5ff20eecae19b7fc13fc233d9ea33990c503 | https://github.com/PepsRyuu/virtual-scrolling-tree/blob/bc3d5ff20eecae19b7fc13fc233d9ea33990c503/src/virtual-scrolling-tree/VirtualScrollingTree.js#L662-L729 | train |
express-vue/vue-pronto | lib/utils/head.js | BuildHead | function BuildHead(metaObject = {}) {
const metaCopy = Object.assign({}, metaObject);
let finalString = "";
if (metaCopy.title) {
finalString += `<title>${metaCopy.title}</title>`;
}
if (metaCopy.meta) {
throw new Error("WARNING - DEPRECATED: It looks like you're using the old meta object, please migrate to the new one");
}
if (metaCopy.metas) {
for (let index = 0; index < metaCopy.metas.length; index++) {
const headItem = metaCopy.metas[index];
const processedItem = ProcessMetaItem(headItem);
if (processedItem !== undefined) {
finalString += processedItem;
}
}
}
if (metaCopy.scripts) {
for (let index = 0; index < metaCopy.scripts.length; index++) {
const headItem = metaCopy.scripts[index];
const processedItem = ProcessScriptItem(headItem);
if (processedItem !== undefined) {
finalString += processedItem;
}
}
}
if (metaCopy.styles) {
for (let index = 0; index < metaCopy.styles.length; index++) {
const headItem = metaCopy.styles[index];
const processedItem = ProcessStyleItem(headItem);
if (processedItem !== undefined) {
finalString += processedItem;
}
}
}
if (metaCopy.structuredData) {
finalString += `<script type="application/ld+json">${JSON.stringify(metaCopy.structuredData)}</script>`;
}
return finalString;
} | javascript | function BuildHead(metaObject = {}) {
const metaCopy = Object.assign({}, metaObject);
let finalString = "";
if (metaCopy.title) {
finalString += `<title>${metaCopy.title}</title>`;
}
if (metaCopy.meta) {
throw new Error("WARNING - DEPRECATED: It looks like you're using the old meta object, please migrate to the new one");
}
if (metaCopy.metas) {
for (let index = 0; index < metaCopy.metas.length; index++) {
const headItem = metaCopy.metas[index];
const processedItem = ProcessMetaItem(headItem);
if (processedItem !== undefined) {
finalString += processedItem;
}
}
}
if (metaCopy.scripts) {
for (let index = 0; index < metaCopy.scripts.length; index++) {
const headItem = metaCopy.scripts[index];
const processedItem = ProcessScriptItem(headItem);
if (processedItem !== undefined) {
finalString += processedItem;
}
}
}
if (metaCopy.styles) {
for (let index = 0; index < metaCopy.styles.length; index++) {
const headItem = metaCopy.styles[index];
const processedItem = ProcessStyleItem(headItem);
if (processedItem !== undefined) {
finalString += processedItem;
}
}
}
if (metaCopy.structuredData) {
finalString += `<script type="application/ld+json">${JSON.stringify(metaCopy.structuredData)}</script>`;
}
return finalString;
} | [
"function",
"BuildHead",
"(",
"metaObject",
"=",
"{",
"}",
")",
"{",
"const",
"metaCopy",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"metaObject",
")",
";",
"let",
"finalString",
"=",
"\"\"",
";",
"if",
"(",
"metaCopy",
".",
"title",
")",
"{",
"finalString",
"+=",
"`",
"${",
"metaCopy",
".",
"title",
"}",
"`",
";",
"}",
"if",
"(",
"metaCopy",
".",
"meta",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"WARNING - DEPRECATED: It looks like you're using the old meta object, please migrate to the new one\"",
")",
";",
"}",
"if",
"(",
"metaCopy",
".",
"metas",
")",
"{",
"for",
"(",
"let",
"index",
"=",
"0",
";",
"index",
"<",
"metaCopy",
".",
"metas",
".",
"length",
";",
"index",
"++",
")",
"{",
"const",
"headItem",
"=",
"metaCopy",
".",
"metas",
"[",
"index",
"]",
";",
"const",
"processedItem",
"=",
"ProcessMetaItem",
"(",
"headItem",
")",
";",
"if",
"(",
"processedItem",
"!==",
"undefined",
")",
"{",
"finalString",
"+=",
"processedItem",
";",
"}",
"}",
"}",
"if",
"(",
"metaCopy",
".",
"scripts",
")",
"{",
"for",
"(",
"let",
"index",
"=",
"0",
";",
"index",
"<",
"metaCopy",
".",
"scripts",
".",
"length",
";",
"index",
"++",
")",
"{",
"const",
"headItem",
"=",
"metaCopy",
".",
"scripts",
"[",
"index",
"]",
";",
"const",
"processedItem",
"=",
"ProcessScriptItem",
"(",
"headItem",
")",
";",
"if",
"(",
"processedItem",
"!==",
"undefined",
")",
"{",
"finalString",
"+=",
"processedItem",
";",
"}",
"}",
"}",
"if",
"(",
"metaCopy",
".",
"styles",
")",
"{",
"for",
"(",
"let",
"index",
"=",
"0",
";",
"index",
"<",
"metaCopy",
".",
"styles",
".",
"length",
";",
"index",
"++",
")",
"{",
"const",
"headItem",
"=",
"metaCopy",
".",
"styles",
"[",
"index",
"]",
";",
"const",
"processedItem",
"=",
"ProcessStyleItem",
"(",
"headItem",
")",
";",
"if",
"(",
"processedItem",
"!==",
"undefined",
")",
"{",
"finalString",
"+=",
"processedItem",
";",
"}",
"}",
"}",
"if",
"(",
"metaCopy",
".",
"structuredData",
")",
"{",
"finalString",
"+=",
"`",
"${",
"JSON",
".",
"stringify",
"(",
"metaCopy",
".",
"structuredData",
")",
"}",
"`",
";",
"}",
"return",
"finalString",
";",
"}"
] | BuildHead takes the array and splits it up for processing
@param {object} metaObject
@returns {String} | [
"BuildHead",
"takes",
"the",
"array",
"and",
"splits",
"it",
"up",
"for",
"processing"
] | 3fac4d204af4c7d569f68236885fd288904f8bbd | https://github.com/express-vue/vue-pronto/blob/3fac4d204af4c7d569f68236885fd288904f8bbd/lib/utils/head.js#L8-L54 | train |
PepsRyuu/virtual-scrolling-tree | examples/preact/index.js | findItemInDataForExpansion | function findItemInDataForExpansion (label) {
for (let i = 0; i < data.length; i++) {
if (data[i].label === label) {
let item = data[i];
let offset = data.filter(d => d.parent === item.parent).findIndex(d => d.id === item.id);
return {
parent: item.parent,
id: item.id,
children: item.children,
offset: offset
};
}
}
} | javascript | function findItemInDataForExpansion (label) {
for (let i = 0; i < data.length; i++) {
if (data[i].label === label) {
let item = data[i];
let offset = data.filter(d => d.parent === item.parent).findIndex(d => d.id === item.id);
return {
parent: item.parent,
id: item.id,
children: item.children,
offset: offset
};
}
}
} | [
"function",
"findItemInDataForExpansion",
"(",
"label",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"data",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"data",
"[",
"i",
"]",
".",
"label",
"===",
"label",
")",
"{",
"let",
"item",
"=",
"data",
"[",
"i",
"]",
";",
"let",
"offset",
"=",
"data",
".",
"filter",
"(",
"d",
"=>",
"d",
".",
"parent",
"===",
"item",
".",
"parent",
")",
".",
"findIndex",
"(",
"d",
"=>",
"d",
".",
"id",
"===",
"item",
".",
"id",
")",
";",
"return",
"{",
"parent",
":",
"item",
".",
"parent",
",",
"id",
":",
"item",
".",
"id",
",",
"children",
":",
"item",
".",
"children",
",",
"offset",
":",
"offset",
"}",
";",
"}",
"}",
"}"
] | Helper function for demo to dynamically expand items | [
"Helper",
"function",
"for",
"demo",
"to",
"dynamically",
"expand",
"items"
] | bc3d5ff20eecae19b7fc13fc233d9ea33990c503 | https://github.com/PepsRyuu/virtual-scrolling-tree/blob/bc3d5ff20eecae19b7fc13fc233d9ea33990c503/examples/preact/index.js#L33-L47 | train |
PepsRyuu/virtual-scrolling-tree | examples/preact/index.js | onDataFetch | function onDataFetch(query, resolve) {
let output = [];
query.forEach(function(query) {
let filteredItems = data.filter(function(obj) {
return obj.parent === query.parent;
});
output.push({
parent: query.parent,
items: filteredItems.splice(query.offset, query.limit)
});
});
resolve(JSON.parse(JSON.stringify(output)));
} | javascript | function onDataFetch(query, resolve) {
let output = [];
query.forEach(function(query) {
let filteredItems = data.filter(function(obj) {
return obj.parent === query.parent;
});
output.push({
parent: query.parent,
items: filteredItems.splice(query.offset, query.limit)
});
});
resolve(JSON.parse(JSON.stringify(output)));
} | [
"function",
"onDataFetch",
"(",
"query",
",",
"resolve",
")",
"{",
"let",
"output",
"=",
"[",
"]",
";",
"query",
".",
"forEach",
"(",
"function",
"(",
"query",
")",
"{",
"let",
"filteredItems",
"=",
"data",
".",
"filter",
"(",
"function",
"(",
"obj",
")",
"{",
"return",
"obj",
".",
"parent",
"===",
"query",
".",
"parent",
";",
"}",
")",
";",
"output",
".",
"push",
"(",
"{",
"parent",
":",
"query",
".",
"parent",
",",
"items",
":",
"filteredItems",
".",
"splice",
"(",
"query",
".",
"offset",
",",
"query",
".",
"limit",
")",
"}",
")",
";",
"}",
")",
";",
"resolve",
"(",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"output",
")",
")",
")",
";",
"}"
] | Called by the VST to get data.
@method onDataFetch | [
"Called",
"by",
"the",
"VST",
"to",
"get",
"data",
"."
] | bc3d5ff20eecae19b7fc13fc233d9ea33990c503 | https://github.com/PepsRyuu/virtual-scrolling-tree/blob/bc3d5ff20eecae19b7fc13fc233d9ea33990c503/examples/preact/index.js#L54-L70 | train |
duizendnegen/ember-cli-lazy-load | ember-addon.js | EmberAddon | function EmberAddon() {
var args = [];
var options = {};
console.log("Addon init")
for (var i = 0, l = arguments.length; i < l; i++) {
args.push(arguments[i]);
}
if (args.length === 1) {
options = args[0];
} else if (args.length > 1) {
args.reverse();
options = defaults.apply(null, args);
}
process.env.EMBER_ADDON_ENV = process.env.EMBER_ADDON_ENV || 'development';
this.appConstructor(defaults(options, {
name: 'dummy',
configPath: './tests/dummy/config/environment',
trees: {
app: 'tests/dummy/app',
styles: 'tests/dummy/app/styles',
templates: 'tests/dummy/app/templates',
public: 'tests/dummy/public',
tests: new Funnel('tests', {
exclude: [ /^dummy/ ]
})
},
jshintrc: {
tests: './tests',
app: './tests/dummy'
},
}));
} | javascript | function EmberAddon() {
var args = [];
var options = {};
console.log("Addon init")
for (var i = 0, l = arguments.length; i < l; i++) {
args.push(arguments[i]);
}
if (args.length === 1) {
options = args[0];
} else if (args.length > 1) {
args.reverse();
options = defaults.apply(null, args);
}
process.env.EMBER_ADDON_ENV = process.env.EMBER_ADDON_ENV || 'development';
this.appConstructor(defaults(options, {
name: 'dummy',
configPath: './tests/dummy/config/environment',
trees: {
app: 'tests/dummy/app',
styles: 'tests/dummy/app/styles',
templates: 'tests/dummy/app/templates',
public: 'tests/dummy/public',
tests: new Funnel('tests', {
exclude: [ /^dummy/ ]
})
},
jshintrc: {
tests: './tests',
app: './tests/dummy'
},
}));
} | [
"function",
"EmberAddon",
"(",
")",
"{",
"var",
"args",
"=",
"[",
"]",
";",
"var",
"options",
"=",
"{",
"}",
";",
"console",
".",
"log",
"(",
"\"Addon init\"",
")",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"arguments",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"args",
".",
"push",
"(",
"arguments",
"[",
"i",
"]",
")",
";",
"}",
"if",
"(",
"args",
".",
"length",
"===",
"1",
")",
"{",
"options",
"=",
"args",
"[",
"0",
"]",
";",
"}",
"else",
"if",
"(",
"args",
".",
"length",
">",
"1",
")",
"{",
"args",
".",
"reverse",
"(",
")",
";",
"options",
"=",
"defaults",
".",
"apply",
"(",
"null",
",",
"args",
")",
";",
"}",
"process",
".",
"env",
".",
"EMBER_ADDON_ENV",
"=",
"process",
".",
"env",
".",
"EMBER_ADDON_ENV",
"||",
"'development'",
";",
"this",
".",
"appConstructor",
"(",
"defaults",
"(",
"options",
",",
"{",
"name",
":",
"'dummy'",
",",
"configPath",
":",
"'./tests/dummy/config/environment'",
",",
"trees",
":",
"{",
"app",
":",
"'tests/dummy/app'",
",",
"styles",
":",
"'tests/dummy/app/styles'",
",",
"templates",
":",
"'tests/dummy/app/templates'",
",",
"public",
":",
"'tests/dummy/public'",
",",
"tests",
":",
"new",
"Funnel",
"(",
"'tests'",
",",
"{",
"exclude",
":",
"[",
"/",
"^dummy",
"/",
"]",
"}",
")",
"}",
",",
"jshintrc",
":",
"{",
"tests",
":",
"'./tests'",
",",
"app",
":",
"'./tests/dummy'",
"}",
",",
"}",
")",
")",
";",
"}"
] | EmberAddon is used during addon development.
@class EmberAddon
@extends EmberApp
@constructor
@param options | [
"EmberAddon",
"is",
"used",
"during",
"addon",
"development",
"."
] | ae1adcc0a1d5e8e6b11d7ff79cf3844852adbf17 | https://github.com/duizendnegen/ember-cli-lazy-load/blob/ae1adcc0a1d5e8e6b11d7ff79cf3844852adbf17/ember-addon.js#L21-L56 | train |
drkibitz/node-pixi | src/pixi/display/Sprite.js | Sprite | function Sprite(texture)
{
DisplayObjectContainer.call(this);
/**
* The anchor sets the origin point of the texture.
* The default is 0,0 this means the textures origin is the top left
* Setting than anchor to 0.5,0.5 means the textures origin is centered
* Setting the anchor to 1,1 would mean the textures origin points will be the bottom right
*
* @property anchor
* @type Point
*/
this.anchor = new Point();
/**
* The texture that the sprite is using
*
* @property texture
* @type Texture
*/
this.texture = texture;
/**
* The blend mode of sprite.
* currently supports blendModes.NORMAL and blendModes.SCREEN
*
* @property blendMode
* @type Number
*/
this.blendMode = blendModes.NORMAL;
/**
* The width of the sprite (this is initially set by the texture)
*
* @property _width
* @type Number
* @private
*/
this._width = 0;
/**
* The height of the sprite (this is initially set by the texture)
*
* @property _height
* @type Number
* @private
*/
this._height = 0;
if(texture.baseTexture.hasLoaded)
{
this.updateFrame = true;
}
else
{
var that = this;
this.texture.addEventListener( 'update', function () {
that.onTextureUpdate();
});
}
this.renderable = true;
} | javascript | function Sprite(texture)
{
DisplayObjectContainer.call(this);
/**
* The anchor sets the origin point of the texture.
* The default is 0,0 this means the textures origin is the top left
* Setting than anchor to 0.5,0.5 means the textures origin is centered
* Setting the anchor to 1,1 would mean the textures origin points will be the bottom right
*
* @property anchor
* @type Point
*/
this.anchor = new Point();
/**
* The texture that the sprite is using
*
* @property texture
* @type Texture
*/
this.texture = texture;
/**
* The blend mode of sprite.
* currently supports blendModes.NORMAL and blendModes.SCREEN
*
* @property blendMode
* @type Number
*/
this.blendMode = blendModes.NORMAL;
/**
* The width of the sprite (this is initially set by the texture)
*
* @property _width
* @type Number
* @private
*/
this._width = 0;
/**
* The height of the sprite (this is initially set by the texture)
*
* @property _height
* @type Number
* @private
*/
this._height = 0;
if(texture.baseTexture.hasLoaded)
{
this.updateFrame = true;
}
else
{
var that = this;
this.texture.addEventListener( 'update', function () {
that.onTextureUpdate();
});
}
this.renderable = true;
} | [
"function",
"Sprite",
"(",
"texture",
")",
"{",
"DisplayObjectContainer",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"anchor",
"=",
"new",
"Point",
"(",
")",
";",
"this",
".",
"texture",
"=",
"texture",
";",
"this",
".",
"blendMode",
"=",
"blendModes",
".",
"NORMAL",
";",
"this",
".",
"_width",
"=",
"0",
";",
"this",
".",
"_height",
"=",
"0",
";",
"if",
"(",
"texture",
".",
"baseTexture",
".",
"hasLoaded",
")",
"{",
"this",
".",
"updateFrame",
"=",
"true",
";",
"}",
"else",
"{",
"var",
"that",
"=",
"this",
";",
"this",
".",
"texture",
".",
"addEventListener",
"(",
"'update'",
",",
"function",
"(",
")",
"{",
"that",
".",
"onTextureUpdate",
"(",
")",
";",
"}",
")",
";",
"}",
"this",
".",
"renderable",
"=",
"true",
";",
"}"
] | The SPrite object is the base for all textured objects that are rendered to the screen
@class Sprite
@extends DisplayObjectContainer
@constructor
@param texture {Texture} The texture for this sprite
@type String | [
"The",
"SPrite",
"object",
"is",
"the",
"base",
"for",
"all",
"textured",
"objects",
"that",
"are",
"rendered",
"to",
"the",
"screen"
] | 2ddb5361c50293419a46a76bf4771cecd6d9aef4 | https://github.com/drkibitz/node-pixi/blob/2ddb5361c50293419a46a76bf4771cecd6d9aef4/src/pixi/display/Sprite.js#L20-L83 | train |
drkibitz/node-pixi | src/pixi/textures/Texture.js | Texture | function Texture(baseTexture, frame)
{
EventTarget.call( this );
if(!frame)
{
this.noFrame = true;
frame = new Rectangle(0,0,1,1);
}
if(baseTexture instanceof Texture)
baseTexture = baseTexture.baseTexture;
/**
* The base texture of this texture
*
* @property baseTexture
* @type BaseTexture
*/
this.baseTexture = baseTexture;
/**
* The frame specifies the region of the base texture that this texture uses
*
* @property frame
* @type Rectangle
*/
this.frame = frame;
/**
* The trim point
*
* @property trim
* @type Point
*/
this.trim = new Point();
this.scope = this;
if(baseTexture.hasLoaded)
{
if(this.noFrame)frame = new Rectangle(0,0, baseTexture.width, baseTexture.height);
//console.log(frame)
this.setFrame(frame);
}
else
{
var scope = this;
baseTexture.addEventListener('loaded', function(){ scope.onBaseTextureLoaded(); });
}
} | javascript | function Texture(baseTexture, frame)
{
EventTarget.call( this );
if(!frame)
{
this.noFrame = true;
frame = new Rectangle(0,0,1,1);
}
if(baseTexture instanceof Texture)
baseTexture = baseTexture.baseTexture;
/**
* The base texture of this texture
*
* @property baseTexture
* @type BaseTexture
*/
this.baseTexture = baseTexture;
/**
* The frame specifies the region of the base texture that this texture uses
*
* @property frame
* @type Rectangle
*/
this.frame = frame;
/**
* The trim point
*
* @property trim
* @type Point
*/
this.trim = new Point();
this.scope = this;
if(baseTexture.hasLoaded)
{
if(this.noFrame)frame = new Rectangle(0,0, baseTexture.width, baseTexture.height);
//console.log(frame)
this.setFrame(frame);
}
else
{
var scope = this;
baseTexture.addEventListener('loaded', function(){ scope.onBaseTextureLoaded(); });
}
} | [
"function",
"Texture",
"(",
"baseTexture",
",",
"frame",
")",
"{",
"EventTarget",
".",
"call",
"(",
"this",
")",
";",
"if",
"(",
"!",
"frame",
")",
"{",
"this",
".",
"noFrame",
"=",
"true",
";",
"frame",
"=",
"new",
"Rectangle",
"(",
"0",
",",
"0",
",",
"1",
",",
"1",
")",
";",
"}",
"if",
"(",
"baseTexture",
"instanceof",
"Texture",
")",
"baseTexture",
"=",
"baseTexture",
".",
"baseTexture",
";",
"this",
".",
"baseTexture",
"=",
"baseTexture",
";",
"this",
".",
"frame",
"=",
"frame",
";",
"this",
".",
"trim",
"=",
"new",
"Point",
"(",
")",
";",
"this",
".",
"scope",
"=",
"this",
";",
"if",
"(",
"baseTexture",
".",
"hasLoaded",
")",
"{",
"if",
"(",
"this",
".",
"noFrame",
")",
"frame",
"=",
"new",
"Rectangle",
"(",
"0",
",",
"0",
",",
"baseTexture",
".",
"width",
",",
"baseTexture",
".",
"height",
")",
";",
"this",
".",
"setFrame",
"(",
"frame",
")",
";",
"}",
"else",
"{",
"var",
"scope",
"=",
"this",
";",
"baseTexture",
".",
"addEventListener",
"(",
"'loaded'",
",",
"function",
"(",
")",
"{",
"scope",
".",
"onBaseTextureLoaded",
"(",
")",
";",
"}",
")",
";",
"}",
"}"
] | A texture stores the information that represents an image or part of an image. It cannot be added
to the display list directly. To do this use Sprite. If no frame is provided then the whole image is used
@class Texture
@uses EventTarget
@constructor
@param baseTexture {BaseTexture} The base texture source to create the texture from
@param frame {Rectangle} The rectangle frame of the texture to show | [
"A",
"texture",
"stores",
"the",
"information",
"that",
"represents",
"an",
"image",
"or",
"part",
"of",
"an",
"image",
".",
"It",
"cannot",
"be",
"added",
"to",
"the",
"display",
"list",
"directly",
".",
"To",
"do",
"this",
"use",
"Sprite",
".",
"If",
"no",
"frame",
"is",
"provided",
"then",
"the",
"whole",
"image",
"is",
"used"
] | 2ddb5361c50293419a46a76bf4771cecd6d9aef4 | https://github.com/drkibitz/node-pixi/blob/2ddb5361c50293419a46a76bf4771cecd6d9aef4/src/pixi/textures/Texture.js#L21-L72 | train |
drkibitz/node-pixi | src/pixi/textures/BaseTexture.js | BaseTexture | function BaseTexture(source, scaleMode)
{
EventTarget.call(this);
/**
* [read-only] The width of the base texture set when the image has loaded
*
* @property width
* @type Number
* @readOnly
*/
this.width = 100;
/**
* [read-only] The height of the base texture set when the image has loaded
*
* @property height
* @type Number
* @readOnly
*/
this.height = 100;
/**
* The scale mode to apply when scaling this texture
* @property scaleMode
* @type PIXI.BaseTexture.SCALE_MODE
* @default PIXI.BaseTexture.SCALE_MODE.LINEAR
*/
this.scaleMode = scaleMode || BaseTexture.SCALE_MODE.DEFAULT;
/**
* [read-only] Describes if the base texture has loaded or not
*
* @property hasLoaded
* @type Boolean
* @readOnly
*/
this.hasLoaded = false;
/**
* The source that is loaded to create the texture
*
* @property source
* @type Image
*/
this.source = source;
if(!source)return;
if('complete' in this.source)
{
if(this.source.complete)
{
this.hasLoaded = true;
this.width = this.source.width;
this.height = this.source.height;
globals.texturesToUpdate.push(this);
}
else
{
var scope = this;
this.source.onload = function() {
scope.hasLoaded = true;
scope.width = scope.source.width;
scope.height = scope.source.height;
// add it to somewhere...
globals.texturesToUpdate.push(scope);
scope.dispatchEvent( { type: 'loaded', content: scope } );
};
//this.image.src = imageUrl;
}
}
else
{
this.hasLoaded = true;
this.width = this.source.width;
this.height = this.source.height;
globals.texturesToUpdate.push(this);
}
this.imageUrl = null;
this._powerOf2 = false;
} | javascript | function BaseTexture(source, scaleMode)
{
EventTarget.call(this);
/**
* [read-only] The width of the base texture set when the image has loaded
*
* @property width
* @type Number
* @readOnly
*/
this.width = 100;
/**
* [read-only] The height of the base texture set when the image has loaded
*
* @property height
* @type Number
* @readOnly
*/
this.height = 100;
/**
* The scale mode to apply when scaling this texture
* @property scaleMode
* @type PIXI.BaseTexture.SCALE_MODE
* @default PIXI.BaseTexture.SCALE_MODE.LINEAR
*/
this.scaleMode = scaleMode || BaseTexture.SCALE_MODE.DEFAULT;
/**
* [read-only] Describes if the base texture has loaded or not
*
* @property hasLoaded
* @type Boolean
* @readOnly
*/
this.hasLoaded = false;
/**
* The source that is loaded to create the texture
*
* @property source
* @type Image
*/
this.source = source;
if(!source)return;
if('complete' in this.source)
{
if(this.source.complete)
{
this.hasLoaded = true;
this.width = this.source.width;
this.height = this.source.height;
globals.texturesToUpdate.push(this);
}
else
{
var scope = this;
this.source.onload = function() {
scope.hasLoaded = true;
scope.width = scope.source.width;
scope.height = scope.source.height;
// add it to somewhere...
globals.texturesToUpdate.push(scope);
scope.dispatchEvent( { type: 'loaded', content: scope } );
};
//this.image.src = imageUrl;
}
}
else
{
this.hasLoaded = true;
this.width = this.source.width;
this.height = this.source.height;
globals.texturesToUpdate.push(this);
}
this.imageUrl = null;
this._powerOf2 = false;
} | [
"function",
"BaseTexture",
"(",
"source",
",",
"scaleMode",
")",
"{",
"EventTarget",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"width",
"=",
"100",
";",
"this",
".",
"height",
"=",
"100",
";",
"this",
".",
"scaleMode",
"=",
"scaleMode",
"||",
"BaseTexture",
".",
"SCALE_MODE",
".",
"DEFAULT",
";",
"this",
".",
"hasLoaded",
"=",
"false",
";",
"this",
".",
"source",
"=",
"source",
";",
"if",
"(",
"!",
"source",
")",
"return",
";",
"if",
"(",
"'complete'",
"in",
"this",
".",
"source",
")",
"{",
"if",
"(",
"this",
".",
"source",
".",
"complete",
")",
"{",
"this",
".",
"hasLoaded",
"=",
"true",
";",
"this",
".",
"width",
"=",
"this",
".",
"source",
".",
"width",
";",
"this",
".",
"height",
"=",
"this",
".",
"source",
".",
"height",
";",
"globals",
".",
"texturesToUpdate",
".",
"push",
"(",
"this",
")",
";",
"}",
"else",
"{",
"var",
"scope",
"=",
"this",
";",
"this",
".",
"source",
".",
"onload",
"=",
"function",
"(",
")",
"{",
"scope",
".",
"hasLoaded",
"=",
"true",
";",
"scope",
".",
"width",
"=",
"scope",
".",
"source",
".",
"width",
";",
"scope",
".",
"height",
"=",
"scope",
".",
"source",
".",
"height",
";",
"globals",
".",
"texturesToUpdate",
".",
"push",
"(",
"scope",
")",
";",
"scope",
".",
"dispatchEvent",
"(",
"{",
"type",
":",
"'loaded'",
",",
"content",
":",
"scope",
"}",
")",
";",
"}",
";",
"}",
"}",
"else",
"{",
"this",
".",
"hasLoaded",
"=",
"true",
";",
"this",
".",
"width",
"=",
"this",
".",
"source",
".",
"width",
";",
"this",
".",
"height",
"=",
"this",
".",
"source",
".",
"height",
";",
"globals",
".",
"texturesToUpdate",
".",
"push",
"(",
"this",
")",
";",
"}",
"this",
".",
"imageUrl",
"=",
"null",
";",
"this",
".",
"_powerOf2",
"=",
"false",
";",
"}"
] | A texture stores the information that represents an image. All textures have a base texture
@class BaseTexture
@uses EventTarget
@constructor
@param source {String} the source object (image or canvas) | [
"A",
"texture",
"stores",
"the",
"information",
"that",
"represents",
"an",
"image",
".",
"All",
"textures",
"have",
"a",
"base",
"texture"
] | 2ddb5361c50293419a46a76bf4771cecd6d9aef4 | https://github.com/drkibitz/node-pixi/blob/2ddb5361c50293419a46a76bf4771cecd6d9aef4/src/pixi/textures/BaseTexture.js#L19-L106 | train |
drkibitz/node-pixi | src/pixi/utils/Polyk.js | pointInTriangle | function pointInTriangle(px, py, ax, ay, bx, by, cx, cy)
{
var v0x = cx-ax;
var v0y = cy-ay;
var v1x = bx-ax;
var v1y = by-ay;
var v2x = px-ax;
var v2y = py-ay;
var dot00 = v0x*v0x+v0y*v0y;
var dot01 = v0x*v1x+v0y*v1y;
var dot02 = v0x*v2x+v0y*v2y;
var dot11 = v1x*v1x+v1y*v1y;
var dot12 = v1x*v2x+v1y*v2y;
var invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
var v = (dot00 * dot12 - dot01 * dot02) * invDenom;
// Check if point is in triangle
return (u >= 0) && (v >= 0) && (u + v < 1);
} | javascript | function pointInTriangle(px, py, ax, ay, bx, by, cx, cy)
{
var v0x = cx-ax;
var v0y = cy-ay;
var v1x = bx-ax;
var v1y = by-ay;
var v2x = px-ax;
var v2y = py-ay;
var dot00 = v0x*v0x+v0y*v0y;
var dot01 = v0x*v1x+v0y*v1y;
var dot02 = v0x*v2x+v0y*v2y;
var dot11 = v1x*v1x+v1y*v1y;
var dot12 = v1x*v2x+v1y*v2y;
var invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
var v = (dot00 * dot12 - dot01 * dot02) * invDenom;
// Check if point is in triangle
return (u >= 0) && (v >= 0) && (u + v < 1);
} | [
"function",
"pointInTriangle",
"(",
"px",
",",
"py",
",",
"ax",
",",
"ay",
",",
"bx",
",",
"by",
",",
"cx",
",",
"cy",
")",
"{",
"var",
"v0x",
"=",
"cx",
"-",
"ax",
";",
"var",
"v0y",
"=",
"cy",
"-",
"ay",
";",
"var",
"v1x",
"=",
"bx",
"-",
"ax",
";",
"var",
"v1y",
"=",
"by",
"-",
"ay",
";",
"var",
"v2x",
"=",
"px",
"-",
"ax",
";",
"var",
"v2y",
"=",
"py",
"-",
"ay",
";",
"var",
"dot00",
"=",
"v0x",
"*",
"v0x",
"+",
"v0y",
"*",
"v0y",
";",
"var",
"dot01",
"=",
"v0x",
"*",
"v1x",
"+",
"v0y",
"*",
"v1y",
";",
"var",
"dot02",
"=",
"v0x",
"*",
"v2x",
"+",
"v0y",
"*",
"v2y",
";",
"var",
"dot11",
"=",
"v1x",
"*",
"v1x",
"+",
"v1y",
"*",
"v1y",
";",
"var",
"dot12",
"=",
"v1x",
"*",
"v2x",
"+",
"v1y",
"*",
"v2y",
";",
"var",
"invDenom",
"=",
"1",
"/",
"(",
"dot00",
"*",
"dot11",
"-",
"dot01",
"*",
"dot01",
")",
";",
"var",
"u",
"=",
"(",
"dot11",
"*",
"dot02",
"-",
"dot01",
"*",
"dot12",
")",
"*",
"invDenom",
";",
"var",
"v",
"=",
"(",
"dot00",
"*",
"dot12",
"-",
"dot01",
"*",
"dot02",
")",
"*",
"invDenom",
";",
"return",
"(",
"u",
">=",
"0",
")",
"&&",
"(",
"v",
">=",
"0",
")",
"&&",
"(",
"u",
"+",
"v",
"<",
"1",
")",
";",
"}"
] | Checks if a point is within a triangle
@private | [
"Checks",
"if",
"a",
"point",
"is",
"within",
"a",
"triangle"
] | 2ddb5361c50293419a46a76bf4771cecd6d9aef4 | https://github.com/drkibitz/node-pixi/blob/2ddb5361c50293419a46a76bf4771cecd6d9aef4/src/pixi/utils/Polyk.js#L42-L63 | train |
drkibitz/node-pixi | src/pixi/utils/Polyk.js | convex | function convex(ax, ay, bx, by, cx, cy, sign)
{
return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign;
} | javascript | function convex(ax, ay, bx, by, cx, cy, sign)
{
return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign;
} | [
"function",
"convex",
"(",
"ax",
",",
"ay",
",",
"bx",
",",
"by",
",",
"cx",
",",
"cy",
",",
"sign",
")",
"{",
"return",
"(",
"(",
"ay",
"-",
"by",
")",
"*",
"(",
"cx",
"-",
"bx",
")",
"+",
"(",
"bx",
"-",
"ax",
")",
"*",
"(",
"cy",
"-",
"by",
")",
">=",
"0",
")",
"===",
"sign",
";",
"}"
] | Checks if a shape is convex
@private | [
"Checks",
"if",
"a",
"shape",
"is",
"convex"
] | 2ddb5361c50293419a46a76bf4771cecd6d9aef4 | https://github.com/drkibitz/node-pixi/blob/2ddb5361c50293419a46a76bf4771cecd6d9aef4/src/pixi/utils/Polyk.js#L70-L73 | train |
drkibitz/node-pixi | src/pixi/geom/Circle.js | Circle | function Circle(x, y, radius)
{
/**
* @property x
* @type Number
* @default 0
*/
this.x = x || 0;
/**
* @property y
* @type Number
* @default 0
*/
this.y = y || 0;
/**
* @property radius
* @type Number
* @default 0
*/
this.radius = radius || 0;
} | javascript | function Circle(x, y, radius)
{
/**
* @property x
* @type Number
* @default 0
*/
this.x = x || 0;
/**
* @property y
* @type Number
* @default 0
*/
this.y = y || 0;
/**
* @property radius
* @type Number
* @default 0
*/
this.radius = radius || 0;
} | [
"function",
"Circle",
"(",
"x",
",",
"y",
",",
"radius",
")",
"{",
"this",
".",
"x",
"=",
"x",
"||",
"0",
";",
"this",
".",
"y",
"=",
"y",
"||",
"0",
";",
"this",
".",
"radius",
"=",
"radius",
"||",
"0",
";",
"}"
] | The Circle object can be used to specify a hit area for displayobjects
@class Circle
@constructor
@param x {Number} The X coord of the upper-left corner of the framing rectangle of this circle
@param y {Number} The Y coord of the upper-left corner of the framing rectangle of this circle
@param radius {Number} The radius of the circle | [
"The",
"Circle",
"object",
"can",
"be",
"used",
"to",
"specify",
"a",
"hit",
"area",
"for",
"displayobjects"
] | 2ddb5361c50293419a46a76bf4771cecd6d9aef4 | https://github.com/drkibitz/node-pixi/blob/2ddb5361c50293419a46a76bf4771cecd6d9aef4/src/pixi/geom/Circle.js#L15-L37 | train |
drkibitz/node-pixi | src/bundle-node.js | ImageMock | function ImageMock() {
var _complete = true;
var _width = 0;
var _height = 0;
var _src = '';
var _onLoad = null;
var _loadTimeoutId;
Object.defineProperties(this, {
complete: {
get: function getComplete() {
return _complete;
},
enumerable: true
},
onload: {
get: function getOnload() {
return _onLoad;
},
set: function setOnload(callback) {
_onLoad = callback;
},
enumerable: true
},
width: {
get: function getWidth() {
return _width;
},
enumerable: true
},
height: {
get: function getHeight() {
return _height;
},
enumerable: true
},
src: {
get: function getSrc() {
return _src;
},
set: function setSrc(src) {
_complete = false;
platform.global.clearTimeout(_loadTimeoutId);
if (src) {
_loadTimeoutId = platform.global.setTimeout(function () {
_width = 10;
_height = 10;
_complete = true;
if (this.onload) this.onload(/*no event used*/);
}.bind(this), 200);
_src = src;
} else {
_width = 0;
_height = 0;
_src = '';
}
},
enumerable: true
}
});
} | javascript | function ImageMock() {
var _complete = true;
var _width = 0;
var _height = 0;
var _src = '';
var _onLoad = null;
var _loadTimeoutId;
Object.defineProperties(this, {
complete: {
get: function getComplete() {
return _complete;
},
enumerable: true
},
onload: {
get: function getOnload() {
return _onLoad;
},
set: function setOnload(callback) {
_onLoad = callback;
},
enumerable: true
},
width: {
get: function getWidth() {
return _width;
},
enumerable: true
},
height: {
get: function getHeight() {
return _height;
},
enumerable: true
},
src: {
get: function getSrc() {
return _src;
},
set: function setSrc(src) {
_complete = false;
platform.global.clearTimeout(_loadTimeoutId);
if (src) {
_loadTimeoutId = platform.global.setTimeout(function () {
_width = 10;
_height = 10;
_complete = true;
if (this.onload) this.onload(/*no event used*/);
}.bind(this), 200);
_src = src;
} else {
_width = 0;
_height = 0;
_src = '';
}
},
enumerable: true
}
});
} | [
"function",
"ImageMock",
"(",
")",
"{",
"var",
"_complete",
"=",
"true",
";",
"var",
"_width",
"=",
"0",
";",
"var",
"_height",
"=",
"0",
";",
"var",
"_src",
"=",
"''",
";",
"var",
"_onLoad",
"=",
"null",
";",
"var",
"_loadTimeoutId",
";",
"Object",
".",
"defineProperties",
"(",
"this",
",",
"{",
"complete",
":",
"{",
"get",
":",
"function",
"getComplete",
"(",
")",
"{",
"return",
"_complete",
";",
"}",
",",
"enumerable",
":",
"true",
"}",
",",
"onload",
":",
"{",
"get",
":",
"function",
"getOnload",
"(",
")",
"{",
"return",
"_onLoad",
";",
"}",
",",
"set",
":",
"function",
"setOnload",
"(",
"callback",
")",
"{",
"_onLoad",
"=",
"callback",
";",
"}",
",",
"enumerable",
":",
"true",
"}",
",",
"width",
":",
"{",
"get",
":",
"function",
"getWidth",
"(",
")",
"{",
"return",
"_width",
";",
"}",
",",
"enumerable",
":",
"true",
"}",
",",
"height",
":",
"{",
"get",
":",
"function",
"getHeight",
"(",
")",
"{",
"return",
"_height",
";",
"}",
",",
"enumerable",
":",
"true",
"}",
",",
"src",
":",
"{",
"get",
":",
"function",
"getSrc",
"(",
")",
"{",
"return",
"_src",
";",
"}",
",",
"set",
":",
"function",
"setSrc",
"(",
"src",
")",
"{",
"_complete",
"=",
"false",
";",
"platform",
".",
"global",
".",
"clearTimeout",
"(",
"_loadTimeoutId",
")",
";",
"if",
"(",
"src",
")",
"{",
"_loadTimeoutId",
"=",
"platform",
".",
"global",
".",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"_width",
"=",
"10",
";",
"_height",
"=",
"10",
";",
"_complete",
"=",
"true",
";",
"if",
"(",
"this",
".",
"onload",
")",
"this",
".",
"onload",
"(",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
",",
"200",
")",
";",
"_src",
"=",
"src",
";",
"}",
"else",
"{",
"_width",
"=",
"0",
";",
"_height",
"=",
"0",
";",
"_src",
"=",
"''",
";",
"}",
"}",
",",
"enumerable",
":",
"true",
"}",
"}",
")",
";",
"}"
] | Minimal Image Element mock
This does not implement anything
further than what pixi uses. | [
"Minimal",
"Image",
"Element",
"mock"
] | 2ddb5361c50293419a46a76bf4771cecd6d9aef4 | https://github.com/drkibitz/node-pixi/blob/2ddb5361c50293419a46a76bf4771cecd6d9aef4/src/bundle-node.js#L16-L77 | train |
geut/postcss-copy | src/index.js | ignore | function ignore(fileMeta, opts) {
if (typeof opts.ignore === 'function') {
return opts.ignore(fileMeta, opts);
}
if (typeof opts.ignore === 'string' || Array.isArray(opts.ignore)) {
return micromatch.any(fileMeta.sourceValue, opts.ignore);
}
return false;
} | javascript | function ignore(fileMeta, opts) {
if (typeof opts.ignore === 'function') {
return opts.ignore(fileMeta, opts);
}
if (typeof opts.ignore === 'string' || Array.isArray(opts.ignore)) {
return micromatch.any(fileMeta.sourceValue, opts.ignore);
}
return false;
} | [
"function",
"ignore",
"(",
"fileMeta",
",",
"opts",
")",
"{",
"if",
"(",
"typeof",
"opts",
".",
"ignore",
"===",
"'function'",
")",
"{",
"return",
"opts",
".",
"ignore",
"(",
"fileMeta",
",",
"opts",
")",
";",
"}",
"if",
"(",
"typeof",
"opts",
".",
"ignore",
"===",
"'string'",
"||",
"Array",
".",
"isArray",
"(",
"opts",
".",
"ignore",
")",
")",
"{",
"return",
"micromatch",
".",
"any",
"(",
"fileMeta",
".",
"sourceValue",
",",
"opts",
".",
"ignore",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Helper function to ignore files
@param {string} filename
@param {string} extra
@param {Object} opts plugin options
@return {boolean} | [
"Helper",
"function",
"to",
"ignore",
"files"
] | 50f6f086336632c22f5db89143cc07b61f34093d | https://github.com/geut/postcss-copy/blob/50f6f086336632c22f5db89143cc07b61f34093d/src/index.js#L20-L30 | train |
geut/postcss-copy | src/index.js | getFileMeta | function getFileMeta(dirname, sourceInputFile, value, opts) {
const parsedUrl = url.parse(value, true);
const filename = decodeURI(parsedUrl.pathname);
const pathname = path.resolve(dirname, filename);
const params = parsedUrl.search || '';
const hash = parsedUrl.hash || '';
// path between the basePath and the filename
const basePath = findBasePath(opts.basePath, pathname);
if (!basePath) {
throw Error(`"basePath" not found in ${pathname}`);
}
const ext = path.extname(pathname);
const fileMeta = {
sourceInputFile,
sourceValue: value,
filename,
// the absolute path without the #hash param and ?query
absolutePath: pathname,
fullName: path.basename(pathname),
path: path.relative(basePath, path.dirname(pathname)),
// name without extension
name: path.basename(pathname, ext),
// extension without the '.'
ext: ext.slice(1),
query: params + hash,
qparams: params.length > 0 ? params.slice(1) : '',
qhash: hash.length > 0 ? hash.slice(1) : '',
basePath
};
return fileMeta;
} | javascript | function getFileMeta(dirname, sourceInputFile, value, opts) {
const parsedUrl = url.parse(value, true);
const filename = decodeURI(parsedUrl.pathname);
const pathname = path.resolve(dirname, filename);
const params = parsedUrl.search || '';
const hash = parsedUrl.hash || '';
// path between the basePath and the filename
const basePath = findBasePath(opts.basePath, pathname);
if (!basePath) {
throw Error(`"basePath" not found in ${pathname}`);
}
const ext = path.extname(pathname);
const fileMeta = {
sourceInputFile,
sourceValue: value,
filename,
// the absolute path without the #hash param and ?query
absolutePath: pathname,
fullName: path.basename(pathname),
path: path.relative(basePath, path.dirname(pathname)),
// name without extension
name: path.basename(pathname, ext),
// extension without the '.'
ext: ext.slice(1),
query: params + hash,
qparams: params.length > 0 ? params.slice(1) : '',
qhash: hash.length > 0 ? hash.slice(1) : '',
basePath
};
return fileMeta;
} | [
"function",
"getFileMeta",
"(",
"dirname",
",",
"sourceInputFile",
",",
"value",
",",
"opts",
")",
"{",
"const",
"parsedUrl",
"=",
"url",
".",
"parse",
"(",
"value",
",",
"true",
")",
";",
"const",
"filename",
"=",
"decodeURI",
"(",
"parsedUrl",
".",
"pathname",
")",
";",
"const",
"pathname",
"=",
"path",
".",
"resolve",
"(",
"dirname",
",",
"filename",
")",
";",
"const",
"params",
"=",
"parsedUrl",
".",
"search",
"||",
"''",
";",
"const",
"hash",
"=",
"parsedUrl",
".",
"hash",
"||",
"''",
";",
"const",
"basePath",
"=",
"findBasePath",
"(",
"opts",
".",
"basePath",
",",
"pathname",
")",
";",
"if",
"(",
"!",
"basePath",
")",
"{",
"throw",
"Error",
"(",
"`",
"${",
"pathname",
"}",
"`",
")",
";",
"}",
"const",
"ext",
"=",
"path",
".",
"extname",
"(",
"pathname",
")",
";",
"const",
"fileMeta",
"=",
"{",
"sourceInputFile",
",",
"sourceValue",
":",
"value",
",",
"filename",
",",
"absolutePath",
":",
"pathname",
",",
"fullName",
":",
"path",
".",
"basename",
"(",
"pathname",
")",
",",
"path",
":",
"path",
".",
"relative",
"(",
"basePath",
",",
"path",
".",
"dirname",
"(",
"pathname",
")",
")",
",",
"name",
":",
"path",
".",
"basename",
"(",
"pathname",
",",
"ext",
")",
",",
"ext",
":",
"ext",
".",
"slice",
"(",
"1",
")",
",",
"query",
":",
"params",
"+",
"hash",
",",
"qparams",
":",
"params",
".",
"length",
">",
"0",
"?",
"params",
".",
"slice",
"(",
"1",
")",
":",
"''",
",",
"qhash",
":",
"hash",
".",
"length",
">",
"0",
"?",
"hash",
".",
"slice",
"(",
"1",
")",
":",
"''",
",",
"basePath",
"}",
";",
"return",
"fileMeta",
";",
"}"
] | Helper function that reads the file ang get some helpful information
to the copy process.
@param {string} dirname path of the read file css
@param {string} sourceInputFile path to the source input file css
@param {string} value url
@param {Object} opts plugin options
@return {Promise} resolve => fileMeta | reject => error message | [
"Helper",
"function",
"that",
"reads",
"the",
"file",
"ang",
"get",
"some",
"helpful",
"information",
"to",
"the",
"copy",
"process",
"."
] | 50f6f086336632c22f5db89143cc07b61f34093d | https://github.com/geut/postcss-copy/blob/50f6f086336632c22f5db89143cc07b61f34093d/src/index.js#L42-L75 | train |
geut/postcss-copy | src/index.js | processUrl | function processUrl(result, decl, node, opts) {
// ignore from the css file by `!`
if (node.value.indexOf('!') === 0) {
node.value = node.value.slice(1);
return Promise.resolve();
}
if (
node.value.indexOf('/') === 0 ||
node.value.indexOf('data:') === 0 ||
node.value.indexOf('#') === 0 ||
/^[a-z]+:\/\//.test(node.value)
) {
return Promise.resolve();
}
/**
* dirname of the read file css
* @type {String}
*/
const dirname = path.dirname(decl.source.input.file);
let fileMeta = getFileMeta(
dirname,
decl.source.input.file,
node.value,
opts
);
// ignore from the fileMeta config
if (ignore(fileMeta, opts)) {
return Promise.resolve();
}
return copy(
fileMeta.absolutePath,
() => fileMeta.resultAbsolutePath,
(contents, isModified) => {
fileMeta.contents = contents;
return Promise.resolve(
isModified ? opts.transform(fileMeta) : fileMeta
)
.then(fileMetaTransformed => {
fileMetaTransformed.hash = opts.hashFunction(
fileMetaTransformed.contents
);
let tpl = opts.template;
if (typeof tpl === 'function') {
tpl = tpl(fileMetaTransformed);
} else {
tags.forEach(tag => {
tpl = tpl.replace(
'[' + tag + ']',
fileMetaTransformed[tag] || opts[tag] || ''
);
});
}
const resultUrl = url.parse(tpl);
fileMetaTransformed.resultAbsolutePath = decodeURI(
path.resolve(
opts.dest,
resultUrl.pathname
)
);
fileMetaTransformed.extra = (resultUrl.search || '') +
(resultUrl.hash || '');
return fileMetaTransformed;
})
.then(fileMetaTransformed => fileMetaTransformed.contents);
}
).then(() => {
const destPath = defineCSSDestPath(
dirname,
fileMeta.basePath,
result,
opts
);
node.value = path
.relative(destPath, fileMeta.resultAbsolutePath)
.split('\\')
.join('/') + fileMeta.extra;
});
} | javascript | function processUrl(result, decl, node, opts) {
// ignore from the css file by `!`
if (node.value.indexOf('!') === 0) {
node.value = node.value.slice(1);
return Promise.resolve();
}
if (
node.value.indexOf('/') === 0 ||
node.value.indexOf('data:') === 0 ||
node.value.indexOf('#') === 0 ||
/^[a-z]+:\/\//.test(node.value)
) {
return Promise.resolve();
}
/**
* dirname of the read file css
* @type {String}
*/
const dirname = path.dirname(decl.source.input.file);
let fileMeta = getFileMeta(
dirname,
decl.source.input.file,
node.value,
opts
);
// ignore from the fileMeta config
if (ignore(fileMeta, opts)) {
return Promise.resolve();
}
return copy(
fileMeta.absolutePath,
() => fileMeta.resultAbsolutePath,
(contents, isModified) => {
fileMeta.contents = contents;
return Promise.resolve(
isModified ? opts.transform(fileMeta) : fileMeta
)
.then(fileMetaTransformed => {
fileMetaTransformed.hash = opts.hashFunction(
fileMetaTransformed.contents
);
let tpl = opts.template;
if (typeof tpl === 'function') {
tpl = tpl(fileMetaTransformed);
} else {
tags.forEach(tag => {
tpl = tpl.replace(
'[' + tag + ']',
fileMetaTransformed[tag] || opts[tag] || ''
);
});
}
const resultUrl = url.parse(tpl);
fileMetaTransformed.resultAbsolutePath = decodeURI(
path.resolve(
opts.dest,
resultUrl.pathname
)
);
fileMetaTransformed.extra = (resultUrl.search || '') +
(resultUrl.hash || '');
return fileMetaTransformed;
})
.then(fileMetaTransformed => fileMetaTransformed.contents);
}
).then(() => {
const destPath = defineCSSDestPath(
dirname,
fileMeta.basePath,
result,
opts
);
node.value = path
.relative(destPath, fileMeta.resultAbsolutePath)
.split('\\')
.join('/') + fileMeta.extra;
});
} | [
"function",
"processUrl",
"(",
"result",
",",
"decl",
",",
"node",
",",
"opts",
")",
"{",
"if",
"(",
"node",
".",
"value",
".",
"indexOf",
"(",
"'!'",
")",
"===",
"0",
")",
"{",
"node",
".",
"value",
"=",
"node",
".",
"value",
".",
"slice",
"(",
"1",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
")",
";",
"}",
"if",
"(",
"node",
".",
"value",
".",
"indexOf",
"(",
"'/'",
")",
"===",
"0",
"||",
"node",
".",
"value",
".",
"indexOf",
"(",
"'data:'",
")",
"===",
"0",
"||",
"node",
".",
"value",
".",
"indexOf",
"(",
"'#'",
")",
"===",
"0",
"||",
"/",
"^[a-z]+:\\/\\/",
"/",
".",
"test",
"(",
"node",
".",
"value",
")",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
")",
";",
"}",
"const",
"dirname",
"=",
"path",
".",
"dirname",
"(",
"decl",
".",
"source",
".",
"input",
".",
"file",
")",
";",
"let",
"fileMeta",
"=",
"getFileMeta",
"(",
"dirname",
",",
"decl",
".",
"source",
".",
"input",
".",
"file",
",",
"node",
".",
"value",
",",
"opts",
")",
";",
"if",
"(",
"ignore",
"(",
"fileMeta",
",",
"opts",
")",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
")",
";",
"}",
"return",
"copy",
"(",
"fileMeta",
".",
"absolutePath",
",",
"(",
")",
"=>",
"fileMeta",
".",
"resultAbsolutePath",
",",
"(",
"contents",
",",
"isModified",
")",
"=>",
"{",
"fileMeta",
".",
"contents",
"=",
"contents",
";",
"return",
"Promise",
".",
"resolve",
"(",
"isModified",
"?",
"opts",
".",
"transform",
"(",
"fileMeta",
")",
":",
"fileMeta",
")",
".",
"then",
"(",
"fileMetaTransformed",
"=>",
"{",
"fileMetaTransformed",
".",
"hash",
"=",
"opts",
".",
"hashFunction",
"(",
"fileMetaTransformed",
".",
"contents",
")",
";",
"let",
"tpl",
"=",
"opts",
".",
"template",
";",
"if",
"(",
"typeof",
"tpl",
"===",
"'function'",
")",
"{",
"tpl",
"=",
"tpl",
"(",
"fileMetaTransformed",
")",
";",
"}",
"else",
"{",
"tags",
".",
"forEach",
"(",
"tag",
"=>",
"{",
"tpl",
"=",
"tpl",
".",
"replace",
"(",
"'['",
"+",
"tag",
"+",
"']'",
",",
"fileMetaTransformed",
"[",
"tag",
"]",
"||",
"opts",
"[",
"tag",
"]",
"||",
"''",
")",
";",
"}",
")",
";",
"}",
"const",
"resultUrl",
"=",
"url",
".",
"parse",
"(",
"tpl",
")",
";",
"fileMetaTransformed",
".",
"resultAbsolutePath",
"=",
"decodeURI",
"(",
"path",
".",
"resolve",
"(",
"opts",
".",
"dest",
",",
"resultUrl",
".",
"pathname",
")",
")",
";",
"fileMetaTransformed",
".",
"extra",
"=",
"(",
"resultUrl",
".",
"search",
"||",
"''",
")",
"+",
"(",
"resultUrl",
".",
"hash",
"||",
"''",
")",
";",
"return",
"fileMetaTransformed",
";",
"}",
")",
".",
"then",
"(",
"fileMetaTransformed",
"=>",
"fileMetaTransformed",
".",
"contents",
")",
";",
"}",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"const",
"destPath",
"=",
"defineCSSDestPath",
"(",
"dirname",
",",
"fileMeta",
".",
"basePath",
",",
"result",
",",
"opts",
")",
";",
"node",
".",
"value",
"=",
"path",
".",
"relative",
"(",
"destPath",
",",
"fileMeta",
".",
"resultAbsolutePath",
")",
".",
"split",
"(",
"'\\\\'",
")",
".",
"\\\\",
"join",
"+",
"(",
"'/'",
")",
";",
"}",
")",
";",
"}"
] | process to copy an asset based on the css file, destination
and the url value
@param {Object} result
@param {Object} decl postcss declaration
@param {Object} node postcss-value-parser
@param {Object} opts plugin options
@return {Promise} | [
"process",
"to",
"copy",
"an",
"asset",
"based",
"on",
"the",
"css",
"file",
"destination",
"and",
"the",
"url",
"value"
] | 50f6f086336632c22f5db89143cc07b61f34093d | https://github.com/geut/postcss-copy/blob/50f6f086336632c22f5db89143cc07b61f34093d/src/index.js#L87-L173 | train |
geut/postcss-copy | src/index.js | processDecl | function processDecl(result, decl, opts) {
const promises = [];
decl.value = valueParser(decl.value).walk(node => {
if (
node.type !== 'function' ||
node.value !== 'url' ||
node.nodes.length === 0
) {
return;
}
const promise = Promise.resolve()
.then(() => processUrl(result, decl, node.nodes[0], opts))
.catch(err => {
decl.warn(result, err.message);
});
promises.push(promise);
});
return Promise.all(promises).then(() => decl);
} | javascript | function processDecl(result, decl, opts) {
const promises = [];
decl.value = valueParser(decl.value).walk(node => {
if (
node.type !== 'function' ||
node.value !== 'url' ||
node.nodes.length === 0
) {
return;
}
const promise = Promise.resolve()
.then(() => processUrl(result, decl, node.nodes[0], opts))
.catch(err => {
decl.warn(result, err.message);
});
promises.push(promise);
});
return Promise.all(promises).then(() => decl);
} | [
"function",
"processDecl",
"(",
"result",
",",
"decl",
",",
"opts",
")",
"{",
"const",
"promises",
"=",
"[",
"]",
";",
"decl",
".",
"value",
"=",
"valueParser",
"(",
"decl",
".",
"value",
")",
".",
"walk",
"(",
"node",
"=>",
"{",
"if",
"(",
"node",
".",
"type",
"!==",
"'function'",
"||",
"node",
".",
"value",
"!==",
"'url'",
"||",
"node",
".",
"nodes",
".",
"length",
"===",
"0",
")",
"{",
"return",
";",
"}",
"const",
"promise",
"=",
"Promise",
".",
"resolve",
"(",
")",
".",
"then",
"(",
"(",
")",
"=>",
"processUrl",
"(",
"result",
",",
"decl",
",",
"node",
".",
"nodes",
"[",
"0",
"]",
",",
"opts",
")",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"decl",
".",
"warn",
"(",
"result",
",",
"err",
".",
"message",
")",
";",
"}",
")",
";",
"promises",
".",
"push",
"(",
"promise",
")",
";",
"}",
")",
";",
"return",
"Promise",
".",
"all",
"(",
"promises",
")",
".",
"then",
"(",
"(",
")",
"=>",
"decl",
")",
";",
"}"
] | Processes each declaration using postcss-value-parser
@param {Object} result
@param {Object} decl postcss declaration
@param {Object} opts plugin options
@return {Promise} | [
"Processes",
"each",
"declaration",
"using",
"postcss",
"-",
"value",
"-",
"parser"
] | 50f6f086336632c22f5db89143cc07b61f34093d | https://github.com/geut/postcss-copy/blob/50f6f086336632c22f5db89143cc07b61f34093d/src/index.js#L183-L205 | train |
geut/postcss-copy | src/index.js | init | function init(userOpts = {}) {
const opts = Object.assign(
{
template: '[hash].[ext][query]',
preservePath: false,
hashFunction(contents) {
return crypto
.createHash('sha1')
.update(contents)
.digest('hex')
.substr(0, 16);
},
transform(fileMeta) {
return fileMeta;
},
ignore: []
},
userOpts
);
return (style, result) => {
if (opts.basePath) {
if (typeof opts.basePath === 'string') {
opts.basePath = [path.resolve(opts.basePath)];
} else {
opts.basePath = opts.basePath.map(elem => path.resolve(elem));
}
} else {
opts.basePath = [process.cwd()];
}
if (opts.dest) {
opts.dest = path.resolve(opts.dest);
} else {
throw new Error('Option `dest` is required in postcss-copy');
}
const promises = [];
style.walkDecls(decl => {
if (decl.value && decl.value.indexOf('url(') > -1) {
promises.push(processDecl(result, decl, opts));
}
});
return Promise.all(promises).then(decls =>
decls.forEach(decl => {
decl.value = String(decl.value);
})
);
};
} | javascript | function init(userOpts = {}) {
const opts = Object.assign(
{
template: '[hash].[ext][query]',
preservePath: false,
hashFunction(contents) {
return crypto
.createHash('sha1')
.update(contents)
.digest('hex')
.substr(0, 16);
},
transform(fileMeta) {
return fileMeta;
},
ignore: []
},
userOpts
);
return (style, result) => {
if (opts.basePath) {
if (typeof opts.basePath === 'string') {
opts.basePath = [path.resolve(opts.basePath)];
} else {
opts.basePath = opts.basePath.map(elem => path.resolve(elem));
}
} else {
opts.basePath = [process.cwd()];
}
if (opts.dest) {
opts.dest = path.resolve(opts.dest);
} else {
throw new Error('Option `dest` is required in postcss-copy');
}
const promises = [];
style.walkDecls(decl => {
if (decl.value && decl.value.indexOf('url(') > -1) {
promises.push(processDecl(result, decl, opts));
}
});
return Promise.all(promises).then(decls =>
decls.forEach(decl => {
decl.value = String(decl.value);
})
);
};
} | [
"function",
"init",
"(",
"userOpts",
"=",
"{",
"}",
")",
"{",
"const",
"opts",
"=",
"Object",
".",
"assign",
"(",
"{",
"template",
":",
"'[hash].[ext][query]'",
",",
"preservePath",
":",
"false",
",",
"hashFunction",
"(",
"contents",
")",
"{",
"return",
"crypto",
".",
"createHash",
"(",
"'sha1'",
")",
".",
"update",
"(",
"contents",
")",
".",
"digest",
"(",
"'hex'",
")",
".",
"substr",
"(",
"0",
",",
"16",
")",
";",
"}",
",",
"transform",
"(",
"fileMeta",
")",
"{",
"return",
"fileMeta",
";",
"}",
",",
"ignore",
":",
"[",
"]",
"}",
",",
"userOpts",
")",
";",
"return",
"(",
"style",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"opts",
".",
"basePath",
")",
"{",
"if",
"(",
"typeof",
"opts",
".",
"basePath",
"===",
"'string'",
")",
"{",
"opts",
".",
"basePath",
"=",
"[",
"path",
".",
"resolve",
"(",
"opts",
".",
"basePath",
")",
"]",
";",
"}",
"else",
"{",
"opts",
".",
"basePath",
"=",
"opts",
".",
"basePath",
".",
"map",
"(",
"elem",
"=>",
"path",
".",
"resolve",
"(",
"elem",
")",
")",
";",
"}",
"}",
"else",
"{",
"opts",
".",
"basePath",
"=",
"[",
"process",
".",
"cwd",
"(",
")",
"]",
";",
"}",
"if",
"(",
"opts",
".",
"dest",
")",
"{",
"opts",
".",
"dest",
"=",
"path",
".",
"resolve",
"(",
"opts",
".",
"dest",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Option `dest` is required in postcss-copy'",
")",
";",
"}",
"const",
"promises",
"=",
"[",
"]",
";",
"style",
".",
"walkDecls",
"(",
"decl",
"=>",
"{",
"if",
"(",
"decl",
".",
"value",
"&&",
"decl",
".",
"value",
".",
"indexOf",
"(",
"'url('",
")",
">",
"-",
"1",
")",
"{",
"promises",
".",
"push",
"(",
"processDecl",
"(",
"result",
",",
"decl",
",",
"opts",
")",
")",
";",
"}",
"}",
")",
";",
"return",
"Promise",
".",
"all",
"(",
"promises",
")",
".",
"then",
"(",
"decls",
"=>",
"decls",
".",
"forEach",
"(",
"decl",
"=>",
"{",
"decl",
".",
"value",
"=",
"String",
"(",
"decl",
".",
"value",
")",
";",
"}",
")",
")",
";",
"}",
";",
"}"
] | Initialize the postcss-copy plugin
@param {Object} plugin options
@return {plugin} | [
"Initialize",
"the",
"postcss",
"-",
"copy",
"plugin"
] | 50f6f086336632c22f5db89143cc07b61f34093d | https://github.com/geut/postcss-copy/blob/50f6f086336632c22f5db89143cc07b61f34093d/src/index.js#L212-L261 | train |
drkibitz/node-pixi | src/pixi/display/Stage.js | Stage | function Stage(backgroundColor)
{
DisplayObjectContainer.call(this);
/**
* [read-only] Current transform of the object based on world (parent) factors
*
* @property worldTransform
* @type Mat3
* @readOnly
* @private
*/
this.worldTransform = mat3.create();
/**
* Whether or not the stage is interactive
*
* @property interactive
* @type Boolean
*/
this.interactive = true;
/**
* The interaction manage for this stage, manages all interactive activity on the stage
*
* @property interactive
* @type InteractionManager
*/
this.interactionManager = new InteractionManager(this);
/**
* Whether the stage is dirty and needs to have interactions updated
*
* @property dirty
* @type Boolean
* @private
*/
this.dirty = true;
this.__childrenAdded = [];
this.__childrenRemoved = [];
//the stage is it's own stage
this.stage = this;
//optimize hit detection a bit
this.stage.hitArea = new Rectangle(0,0,100000, 100000);
this.setBackgroundColor(backgroundColor);
this.worldVisible = true;
} | javascript | function Stage(backgroundColor)
{
DisplayObjectContainer.call(this);
/**
* [read-only] Current transform of the object based on world (parent) factors
*
* @property worldTransform
* @type Mat3
* @readOnly
* @private
*/
this.worldTransform = mat3.create();
/**
* Whether or not the stage is interactive
*
* @property interactive
* @type Boolean
*/
this.interactive = true;
/**
* The interaction manage for this stage, manages all interactive activity on the stage
*
* @property interactive
* @type InteractionManager
*/
this.interactionManager = new InteractionManager(this);
/**
* Whether the stage is dirty and needs to have interactions updated
*
* @property dirty
* @type Boolean
* @private
*/
this.dirty = true;
this.__childrenAdded = [];
this.__childrenRemoved = [];
//the stage is it's own stage
this.stage = this;
//optimize hit detection a bit
this.stage.hitArea = new Rectangle(0,0,100000, 100000);
this.setBackgroundColor(backgroundColor);
this.worldVisible = true;
} | [
"function",
"Stage",
"(",
"backgroundColor",
")",
"{",
"DisplayObjectContainer",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"worldTransform",
"=",
"mat3",
".",
"create",
"(",
")",
";",
"this",
".",
"interactive",
"=",
"true",
";",
"this",
".",
"interactionManager",
"=",
"new",
"InteractionManager",
"(",
"this",
")",
";",
"this",
".",
"dirty",
"=",
"true",
";",
"this",
".",
"__childrenAdded",
"=",
"[",
"]",
";",
"this",
".",
"__childrenRemoved",
"=",
"[",
"]",
";",
"this",
".",
"stage",
"=",
"this",
";",
"this",
".",
"stage",
".",
"hitArea",
"=",
"new",
"Rectangle",
"(",
"0",
",",
"0",
",",
"100000",
",",
"100000",
")",
";",
"this",
".",
"setBackgroundColor",
"(",
"backgroundColor",
")",
";",
"this",
".",
"worldVisible",
"=",
"true",
";",
"}"
] | A Stage represents the root of the display tree. Everything connected to the stage is rendered
@class Stage
@extends DisplayObjectContainer
@constructor
@param backgroundColor {Number} the background color of the stage, easiest way to pass this in is in hex format
like: 0xFFFFFF for white | [
"A",
"Stage",
"represents",
"the",
"root",
"of",
"the",
"display",
"tree",
".",
"Everything",
"connected",
"to",
"the",
"stage",
"is",
"rendered"
] | 2ddb5361c50293419a46a76bf4771cecd6d9aef4 | https://github.com/drkibitz/node-pixi/blob/2ddb5361c50293419a46a76bf4771cecd6d9aef4/src/pixi/display/Stage.js#L23-L73 | train |
drkibitz/node-pixi | src/pixi/loaders/AtlasLoader.js | AtlasLoader | function AtlasLoader(url, crossorigin) {
EventTarget.call(this);
this.url = url;
this.baseUrl = url.replace(/[^\/]*$/, '');
this.crossorigin = crossorigin;
this.loaded = false;
} | javascript | function AtlasLoader(url, crossorigin) {
EventTarget.call(this);
this.url = url;
this.baseUrl = url.replace(/[^\/]*$/, '');
this.crossorigin = crossorigin;
this.loaded = false;
} | [
"function",
"AtlasLoader",
"(",
"url",
",",
"crossorigin",
")",
"{",
"EventTarget",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"url",
"=",
"url",
";",
"this",
".",
"baseUrl",
"=",
"url",
".",
"replace",
"(",
"/",
"[^\\/]*$",
"/",
",",
"''",
")",
";",
"this",
".",
"crossorigin",
"=",
"crossorigin",
";",
"this",
".",
"loaded",
"=",
"false",
";",
"}"
] | The atlas file loader is used to load in Atlas data and parsing it
When loaded this class will dispatch a 'loaded' event
If load failed this class will dispatch a 'error' event
@class AtlasLoader
@extends EventTarget
@constructor
@param {String} url the url of the JSON file
@param {Boolean} crossorigin | [
"The",
"atlas",
"file",
"loader",
"is",
"used",
"to",
"load",
"in",
"Atlas",
"data",
"and",
"parsing",
"it",
"When",
"loaded",
"this",
"class",
"will",
"dispatch",
"a",
"loaded",
"event",
"If",
"load",
"failed",
"this",
"class",
"will",
"dispatch",
"a",
"error",
"event"
] | 2ddb5361c50293419a46a76bf4771cecd6d9aef4 | https://github.com/drkibitz/node-pixi/blob/2ddb5361c50293419a46a76bf4771cecd6d9aef4/src/pixi/loaders/AtlasLoader.js#L21-L27 | train |
Flexberry/ember-flexberry-data | addon/stores/base-store/decorate-adapter.js | addIdToSnapshot | function addIdToSnapshot(snapshot) {
var record = snapshot.record;
record.get('store').updateId(record, { id: generateUniqueId() });
return record._createSnapshot();
} | javascript | function addIdToSnapshot(snapshot) {
var record = snapshot.record;
record.get('store').updateId(record, { id: generateUniqueId() });
return record._createSnapshot();
} | [
"function",
"addIdToSnapshot",
"(",
"snapshot",
")",
"{",
"var",
"record",
"=",
"snapshot",
".",
"record",
";",
"record",
".",
"get",
"(",
"'store'",
")",
".",
"updateId",
"(",
"record",
",",
"{",
"id",
":",
"generateUniqueId",
"(",
")",
"}",
")",
";",
"return",
"record",
".",
"_createSnapshot",
"(",
")",
";",
"}"
] | Add an id to record before create in local | [
"Add",
"an",
"id",
"to",
"record",
"before",
"create",
"in",
"local"
] | fd8fa5ad8488f759b5d872435d8044bfbb96b5a4 | https://github.com/Flexberry/ember-flexberry-data/blob/fd8fa5ad8488f759b5d872435d8044bfbb96b5a4/addon/stores/base-store/decorate-adapter.js#L91-L95 | train |
here-be/snapdragon-node | index.js | assign | function assign(node, token, clone) {
copy(node, token, clone);
ensureNodes(node, clone);
if (token.constructor && token.constructor.name === 'Token') {
copy(node, token.constructor.prototype, clone);
}
} | javascript | function assign(node, token, clone) {
copy(node, token, clone);
ensureNodes(node, clone);
if (token.constructor && token.constructor.name === 'Token') {
copy(node, token.constructor.prototype, clone);
}
} | [
"function",
"assign",
"(",
"node",
",",
"token",
",",
"clone",
")",
"{",
"copy",
"(",
"node",
",",
"token",
",",
"clone",
")",
";",
"ensureNodes",
"(",
"node",
",",
"clone",
")",
";",
"if",
"(",
"token",
".",
"constructor",
"&&",
"token",
".",
"constructor",
".",
"name",
"===",
"'Token'",
")",
"{",
"copy",
"(",
"node",
",",
"token",
".",
"constructor",
".",
"prototype",
",",
"clone",
")",
";",
"}",
"}"
] | assign `token` properties to `node` | [
"assign",
"token",
"properties",
"to",
"node"
] | bd9c41060c9a31f550847b3095148085546db349 | https://github.com/here-be/snapdragon-node/blob/bd9c41060c9a31f550847b3095148085546db349/index.js#L629-L636 | train |
Flexberry/ember-flexberry-data | addon/query/indexeddb-adapter.js | function(a, b) {
let aVal = a[sortField];
let bVal = b[sortField];
return (!aVal && bVal) || (aVal < bVal) ? -1 : (aVal && !bVal) || (aVal > bVal) ? 1 : 0;
} | javascript | function(a, b) {
let aVal = a[sortField];
let bVal = b[sortField];
return (!aVal && bVal) || (aVal < bVal) ? -1 : (aVal && !bVal) || (aVal > bVal) ? 1 : 0;
} | [
"function",
"(",
"a",
",",
"b",
")",
"{",
"let",
"aVal",
"=",
"a",
"[",
"sortField",
"]",
";",
"let",
"bVal",
"=",
"b",
"[",
"sortField",
"]",
";",
"return",
"(",
"!",
"aVal",
"&&",
"bVal",
")",
"||",
"(",
"aVal",
"<",
"bVal",
")",
"?",
"-",
"1",
":",
"(",
"aVal",
"&&",
"!",
"bVal",
")",
"||",
"(",
"aVal",
">",
"bVal",
")",
"?",
"1",
":",
"0",
";",
"}"
] | Sorting array by `sortField` and asc. | [
"Sorting",
"array",
"by",
"sortField",
"and",
"asc",
"."
] | fd8fa5ad8488f759b5d872435d8044bfbb96b5a4 | https://github.com/Flexberry/ember-flexberry-data/blob/fd8fa5ad8488f759b5d872435d8044bfbb96b5a4/addon/query/indexeddb-adapter.js#L67-L71 | train |
|
Flexberry/ember-flexberry-data | addon/query/indexeddb-adapter.js | containsRelationships | function containsRelationships(query) {
let contains = false;
if (query.predicate instanceof SimplePredicate || query.predicate instanceof StringPredicate || query.predicate instanceof DatePredicate) {
contains = Information.parseAttributePath(query.predicate.attributePath).length > 1;
}
if (query.predicate instanceof DetailPredicate) {
return true;
}
if (query.predicate instanceof ComplexPredicate) {
query.predicate.predicates.forEach((predicate) => {
if (containsRelationships({ predicate })) {
contains = true;
}
});
}
if (query.order) {
for (let i = 0; i < query.order.length; i++) {
let attributePath = query.order.attribute(i).name;
if (Information.parseAttributePath(attributePath).length > 1) {
contains = true;
}
}
}
return contains;
} | javascript | function containsRelationships(query) {
let contains = false;
if (query.predicate instanceof SimplePredicate || query.predicate instanceof StringPredicate || query.predicate instanceof DatePredicate) {
contains = Information.parseAttributePath(query.predicate.attributePath).length > 1;
}
if (query.predicate instanceof DetailPredicate) {
return true;
}
if (query.predicate instanceof ComplexPredicate) {
query.predicate.predicates.forEach((predicate) => {
if (containsRelationships({ predicate })) {
contains = true;
}
});
}
if (query.order) {
for (let i = 0; i < query.order.length; i++) {
let attributePath = query.order.attribute(i).name;
if (Information.parseAttributePath(attributePath).length > 1) {
contains = true;
}
}
}
return contains;
} | [
"function",
"containsRelationships",
"(",
"query",
")",
"{",
"let",
"contains",
"=",
"false",
";",
"if",
"(",
"query",
".",
"predicate",
"instanceof",
"SimplePredicate",
"||",
"query",
".",
"predicate",
"instanceof",
"StringPredicate",
"||",
"query",
".",
"predicate",
"instanceof",
"DatePredicate",
")",
"{",
"contains",
"=",
"Information",
".",
"parseAttributePath",
"(",
"query",
".",
"predicate",
".",
"attributePath",
")",
".",
"length",
">",
"1",
";",
"}",
"if",
"(",
"query",
".",
"predicate",
"instanceof",
"DetailPredicate",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"query",
".",
"predicate",
"instanceof",
"ComplexPredicate",
")",
"{",
"query",
".",
"predicate",
".",
"predicates",
".",
"forEach",
"(",
"(",
"predicate",
")",
"=>",
"{",
"if",
"(",
"containsRelationships",
"(",
"{",
"predicate",
"}",
")",
")",
"{",
"contains",
"=",
"true",
";",
"}",
"}",
")",
";",
"}",
"if",
"(",
"query",
".",
"order",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"query",
".",
"order",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"attributePath",
"=",
"query",
".",
"order",
".",
"attribute",
"(",
"i",
")",
".",
"name",
";",
"if",
"(",
"Information",
".",
"parseAttributePath",
"(",
"attributePath",
")",
".",
"length",
">",
"1",
")",
"{",
"contains",
"=",
"true",
";",
"}",
"}",
"}",
"return",
"contains",
";",
"}"
] | Checks query on contains restrictions by relationships.
@method containsRelationships
@param {QueryObject} query
@return {Boolean} | [
"Checks",
"query",
"on",
"contains",
"restrictions",
"by",
"relationships",
"."
] | fd8fa5ad8488f759b5d872435d8044bfbb96b5a4 | https://github.com/Flexberry/ember-flexberry-data/blob/fd8fa5ad8488f759b5d872435d8044bfbb96b5a4/addon/query/indexeddb-adapter.js#L695-L723 | train |
Khan/fuzzy-match-utils | dist/fuzzy-match-utils.js | filterOptions | function filterOptions(options, filter, substitutions) {
// If the filter is blank, return the full list of Options.
if (!filter) {
return options;
}
var cleanFilter = cleanUpText(filter, substitutions);
return options
// Filter out undefined or null Options.
.filter(function (_ref) {
var label = _ref.label,
value = _ref.value;
return label != null && value != null;
})
// Create a {score, Option} pair for each Option based on its label's
// similarity to the filter text.
.map(function (option) {
return {
option: option,
score: typeaheadSimilarity(cleanUpText(option.label, substitutions), cleanFilter)
};
})
// Only include matches of the entire substring, with a slight
// affordance for transposition or extra characters.
.filter(function (pair) {
return pair.score >= cleanFilter.length - 2;
})
// Sort 'em by order of their score.
.sort(function (a, b) {
return b.score - a.score;
})
// …and grab the original Options back from their pairs.
.map(function (pair) {
return pair.option;
});
} | javascript | function filterOptions(options, filter, substitutions) {
// If the filter is blank, return the full list of Options.
if (!filter) {
return options;
}
var cleanFilter = cleanUpText(filter, substitutions);
return options
// Filter out undefined or null Options.
.filter(function (_ref) {
var label = _ref.label,
value = _ref.value;
return label != null && value != null;
})
// Create a {score, Option} pair for each Option based on its label's
// similarity to the filter text.
.map(function (option) {
return {
option: option,
score: typeaheadSimilarity(cleanUpText(option.label, substitutions), cleanFilter)
};
})
// Only include matches of the entire substring, with a slight
// affordance for transposition or extra characters.
.filter(function (pair) {
return pair.score >= cleanFilter.length - 2;
})
// Sort 'em by order of their score.
.sort(function (a, b) {
return b.score - a.score;
})
// …and grab the original Options back from their pairs.
.map(function (pair) {
return pair.option;
});
} | [
"function",
"filterOptions",
"(",
"options",
",",
"filter",
",",
"substitutions",
")",
"{",
"if",
"(",
"!",
"filter",
")",
"{",
"return",
"options",
";",
"}",
"var",
"cleanFilter",
"=",
"cleanUpText",
"(",
"filter",
",",
"substitutions",
")",
";",
"return",
"options",
".",
"filter",
"(",
"function",
"(",
"_ref",
")",
"{",
"var",
"label",
"=",
"_ref",
".",
"label",
",",
"value",
"=",
"_ref",
".",
"value",
";",
"return",
"label",
"!=",
"null",
"&&",
"value",
"!=",
"null",
";",
"}",
")",
".",
"map",
"(",
"function",
"(",
"option",
")",
"{",
"return",
"{",
"option",
":",
"option",
",",
"score",
":",
"typeaheadSimilarity",
"(",
"cleanUpText",
"(",
"option",
".",
"label",
",",
"substitutions",
")",
",",
"cleanFilter",
")",
"}",
";",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"pair",
")",
"{",
"return",
"pair",
".",
"score",
">=",
"cleanFilter",
".",
"length",
"-",
"2",
";",
"}",
")",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"b",
".",
"score",
"-",
"a",
".",
"score",
";",
"}",
")",
".",
"map",
"(",
"function",
"(",
"pair",
")",
"{",
"return",
"pair",
".",
"option",
";",
"}",
")",
";",
"}"
] | A collection of string matching algorithms built with React Select in mind.
Option type from React Select and similar libraries. | [
"A",
"collection",
"of",
"string",
"matching",
"algorithms",
"built",
"with",
"React",
"Select",
"in",
"mind",
".",
"Option",
"type",
"from",
"React",
"Select",
"and",
"similar",
"libraries",
"."
] | 6d22f93324271a301e5840bcc542e945074abcfe | https://github.com/Khan/fuzzy-match-utils/blob/6d22f93324271a301e5840bcc542e945074abcfe/dist/fuzzy-match-utils.js#L31-L66 | train |
Khan/fuzzy-match-utils | dist/fuzzy-match-utils.js | typeaheadSimilarity | function typeaheadSimilarity(a, b) {
var aLength = a.length;
var bLength = b.length;
var table = [];
if (!aLength || !bLength) {
return 0;
}
// Ensure `a` isn't shorter than `b`.
if (aLength < bLength) {
var _ref2 = [b, a];
a = _ref2[0];
b = _ref2[1];
}
// Early exit if `a` includes `b`; these will be scored higher than any
// other options with the same `b` (filter string), with a preference for
// shorter `a` strings (option labels).
if (a.indexOf(b) !== -1) {
return bLength + 1 / aLength;
}
// Initialize the table axes:
//
// 0 0 0 0 ... bLength
// 0
// 0
//
// ...
//
// aLength
//
for (var x = 0; x <= aLength; ++x) {
table[x] = [0];
}
for (var y = 0; y <= bLength; ++y) {
table[0][y] = 0;
}
// Populate the rest of the table with a dynamic programming algorithm.
for (var _x = 1; _x <= aLength; ++_x) {
for (var _y = 1; _y <= bLength; ++_y) {
table[_x][_y] = a[_x - 1] === b[_y - 1] ? 1 + table[_x - 1][_y - 1] : Math.max(table[_x][_y - 1], table[_x - 1][_y]);
}
}
return table[aLength][bLength];
} | javascript | function typeaheadSimilarity(a, b) {
var aLength = a.length;
var bLength = b.length;
var table = [];
if (!aLength || !bLength) {
return 0;
}
// Ensure `a` isn't shorter than `b`.
if (aLength < bLength) {
var _ref2 = [b, a];
a = _ref2[0];
b = _ref2[1];
}
// Early exit if `a` includes `b`; these will be scored higher than any
// other options with the same `b` (filter string), with a preference for
// shorter `a` strings (option labels).
if (a.indexOf(b) !== -1) {
return bLength + 1 / aLength;
}
// Initialize the table axes:
//
// 0 0 0 0 ... bLength
// 0
// 0
//
// ...
//
// aLength
//
for (var x = 0; x <= aLength; ++x) {
table[x] = [0];
}
for (var y = 0; y <= bLength; ++y) {
table[0][y] = 0;
}
// Populate the rest of the table with a dynamic programming algorithm.
for (var _x = 1; _x <= aLength; ++_x) {
for (var _y = 1; _y <= bLength; ++_y) {
table[_x][_y] = a[_x - 1] === b[_y - 1] ? 1 + table[_x - 1][_y - 1] : Math.max(table[_x][_y - 1], table[_x - 1][_y]);
}
}
return table[aLength][bLength];
} | [
"function",
"typeaheadSimilarity",
"(",
"a",
",",
"b",
")",
"{",
"var",
"aLength",
"=",
"a",
".",
"length",
";",
"var",
"bLength",
"=",
"b",
".",
"length",
";",
"var",
"table",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"aLength",
"||",
"!",
"bLength",
")",
"{",
"return",
"0",
";",
"}",
"if",
"(",
"aLength",
"<",
"bLength",
")",
"{",
"var",
"_ref2",
"=",
"[",
"b",
",",
"a",
"]",
";",
"a",
"=",
"_ref2",
"[",
"0",
"]",
";",
"b",
"=",
"_ref2",
"[",
"1",
"]",
";",
"}",
"if",
"(",
"a",
".",
"indexOf",
"(",
"b",
")",
"!==",
"-",
"1",
")",
"{",
"return",
"bLength",
"+",
"1",
"/",
"aLength",
";",
"}",
"for",
"(",
"var",
"x",
"=",
"0",
";",
"x",
"<=",
"aLength",
";",
"++",
"x",
")",
"{",
"table",
"[",
"x",
"]",
"=",
"[",
"0",
"]",
";",
"}",
"for",
"(",
"var",
"y",
"=",
"0",
";",
"y",
"<=",
"bLength",
";",
"++",
"y",
")",
"{",
"table",
"[",
"0",
"]",
"[",
"y",
"]",
"=",
"0",
";",
"}",
"for",
"(",
"var",
"_x",
"=",
"1",
";",
"_x",
"<=",
"aLength",
";",
"++",
"_x",
")",
"{",
"for",
"(",
"var",
"_y",
"=",
"1",
";",
"_y",
"<=",
"bLength",
";",
"++",
"_y",
")",
"{",
"table",
"[",
"_x",
"]",
"[",
"_y",
"]",
"=",
"a",
"[",
"_x",
"-",
"1",
"]",
"===",
"b",
"[",
"_y",
"-",
"1",
"]",
"?",
"1",
"+",
"table",
"[",
"_x",
"-",
"1",
"]",
"[",
"_y",
"-",
"1",
"]",
":",
"Math",
".",
"max",
"(",
"table",
"[",
"_x",
"]",
"[",
"_y",
"-",
"1",
"]",
",",
"table",
"[",
"_x",
"-",
"1",
"]",
"[",
"_y",
"]",
")",
";",
"}",
"}",
"return",
"table",
"[",
"aLength",
"]",
"[",
"bLength",
"]",
";",
"}"
] | Scores the similarity between two strings by returning the length of the
longest common subsequence. Intended for comparing strings of different
lengths; eg. when matching a typeahead search input with a school name.
Meant for use in an instant search box where results are being fetched
as a user is typing.
@param a The longer string (though, we flip them if it's shorter).
@param b The shorter string, eg. a typeahead search input.
@return The length of the longest common subsequence. Higher scores indicate
closer matches. | [
"Scores",
"the",
"similarity",
"between",
"two",
"strings",
"by",
"returning",
"the",
"length",
"of",
"the",
"longest",
"common",
"subsequence",
".",
"Intended",
"for",
"comparing",
"strings",
"of",
"different",
"lengths",
";",
"eg",
".",
"when",
"matching",
"a",
"typeahead",
"search",
"input",
"with",
"a",
"school",
"name",
"."
] | 6d22f93324271a301e5840bcc542e945074abcfe | https://github.com/Khan/fuzzy-match-utils/blob/6d22f93324271a301e5840bcc542e945074abcfe/dist/fuzzy-match-utils.js#L82-L130 | train |
Khan/fuzzy-match-utils | dist/fuzzy-match-utils.js | fullStringDistance | function fullStringDistance(a, b) {
var aLength = a.length;
var bLength = b.length;
var table = [];
if (!aLength) {
return bLength;
}
if (!bLength) {
return aLength;
}
// Initialize the table axes:
//
// 0 1 2 3 4 ... bLength
// 1
// 2
//
// ...
//
// aLength
//
for (var x = 0; x <= aLength; ++x) {
table[x] = [x];
}
for (var y = 0; y <= bLength; ++y) {
table[0][y] = y;
}
// Populate the rest of the table with a dynamic programming algorithm.
for (var _x2 = 1; _x2 <= aLength; ++_x2) {
for (var _y2 = 1; _y2 <= bLength; ++_y2) {
table[_x2][_y2] = a[_x2 - 1] === b[_y2 - 1] ? table[_x2 - 1][_y2 - 1] : 1 + Math.min(table[_x2 - 1][_y2], // Substitution,
table[_x2][_y2 - 1], // insertion,
table[_x2 - 1][_y2 - 1]); // and deletion.
}
}
return table[aLength][bLength];
} | javascript | function fullStringDistance(a, b) {
var aLength = a.length;
var bLength = b.length;
var table = [];
if (!aLength) {
return bLength;
}
if (!bLength) {
return aLength;
}
// Initialize the table axes:
//
// 0 1 2 3 4 ... bLength
// 1
// 2
//
// ...
//
// aLength
//
for (var x = 0; x <= aLength; ++x) {
table[x] = [x];
}
for (var y = 0; y <= bLength; ++y) {
table[0][y] = y;
}
// Populate the rest of the table with a dynamic programming algorithm.
for (var _x2 = 1; _x2 <= aLength; ++_x2) {
for (var _y2 = 1; _y2 <= bLength; ++_y2) {
table[_x2][_y2] = a[_x2 - 1] === b[_y2 - 1] ? table[_x2 - 1][_y2 - 1] : 1 + Math.min(table[_x2 - 1][_y2], // Substitution,
table[_x2][_y2 - 1], // insertion,
table[_x2 - 1][_y2 - 1]); // and deletion.
}
}
return table[aLength][bLength];
} | [
"function",
"fullStringDistance",
"(",
"a",
",",
"b",
")",
"{",
"var",
"aLength",
"=",
"a",
".",
"length",
";",
"var",
"bLength",
"=",
"b",
".",
"length",
";",
"var",
"table",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"aLength",
")",
"{",
"return",
"bLength",
";",
"}",
"if",
"(",
"!",
"bLength",
")",
"{",
"return",
"aLength",
";",
"}",
"for",
"(",
"var",
"x",
"=",
"0",
";",
"x",
"<=",
"aLength",
";",
"++",
"x",
")",
"{",
"table",
"[",
"x",
"]",
"=",
"[",
"x",
"]",
";",
"}",
"for",
"(",
"var",
"y",
"=",
"0",
";",
"y",
"<=",
"bLength",
";",
"++",
"y",
")",
"{",
"table",
"[",
"0",
"]",
"[",
"y",
"]",
"=",
"y",
";",
"}",
"for",
"(",
"var",
"_x2",
"=",
"1",
";",
"_x2",
"<=",
"aLength",
";",
"++",
"_x2",
")",
"{",
"for",
"(",
"var",
"_y2",
"=",
"1",
";",
"_y2",
"<=",
"bLength",
";",
"++",
"_y2",
")",
"{",
"table",
"[",
"_x2",
"]",
"[",
"_y2",
"]",
"=",
"a",
"[",
"_x2",
"-",
"1",
"]",
"===",
"b",
"[",
"_y2",
"-",
"1",
"]",
"?",
"table",
"[",
"_x2",
"-",
"1",
"]",
"[",
"_y2",
"-",
"1",
"]",
":",
"1",
"+",
"Math",
".",
"min",
"(",
"table",
"[",
"_x2",
"-",
"1",
"]",
"[",
"_y2",
"]",
",",
"table",
"[",
"_x2",
"]",
"[",
"_y2",
"-",
"1",
"]",
",",
"table",
"[",
"_x2",
"-",
"1",
"]",
"[",
"_y2",
"-",
"1",
"]",
")",
";",
"}",
"}",
"return",
"table",
"[",
"aLength",
"]",
"[",
"bLength",
"]",
";",
"}"
] | Returns the Levenshtein distance between two strings.
NOTE: The Jaro-Winkler distance also worked well and is slightly more
performant. Levenshtein seems to match more reliably, which is more
important here.
@param a The first string for comparison.
@param b The second string for comparison.
@return The Levenshtein distance, where lower distance indicates higher
similarity. | [
"Returns",
"the",
"Levenshtein",
"distance",
"between",
"two",
"strings",
"."
] | 6d22f93324271a301e5840bcc542e945074abcfe | https://github.com/Khan/fuzzy-match-utils/blob/6d22f93324271a301e5840bcc542e945074abcfe/dist/fuzzy-match-utils.js#L145-L184 | train |
Khan/fuzzy-match-utils | dist/fuzzy-match-utils.js | cleanUpText | function cleanUpText(input, substitutions) {
if (!input) {
return '';
}
// Uppercase and remove all non-alphanumeric, non-accented characters.
// Also remove underscores.
input = input.toUpperCase().replace(/((?=[^\u00E0-\u00FC])\W)|_/g, '');
if (!substitutions) {
return input;
}
var safeSubstitutions = substitutions; // For Flow.
// Replace all strings in `safeSubstitutions` with their standardized
// counterparts.
return Object.keys(safeSubstitutions).reduce(function (output, substitution) {
var unsubbed = new RegExp(substitution, 'g');
return output.replace(unsubbed, safeSubstitutions[substitution]);
}, input);
} | javascript | function cleanUpText(input, substitutions) {
if (!input) {
return '';
}
// Uppercase and remove all non-alphanumeric, non-accented characters.
// Also remove underscores.
input = input.toUpperCase().replace(/((?=[^\u00E0-\u00FC])\W)|_/g, '');
if (!substitutions) {
return input;
}
var safeSubstitutions = substitutions; // For Flow.
// Replace all strings in `safeSubstitutions` with their standardized
// counterparts.
return Object.keys(safeSubstitutions).reduce(function (output, substitution) {
var unsubbed = new RegExp(substitution, 'g');
return output.replace(unsubbed, safeSubstitutions[substitution]);
}, input);
} | [
"function",
"cleanUpText",
"(",
"input",
",",
"substitutions",
")",
"{",
"if",
"(",
"!",
"input",
")",
"{",
"return",
"''",
";",
"}",
"input",
"=",
"input",
".",
"toUpperCase",
"(",
")",
".",
"replace",
"(",
"/",
"((?=[^\\u00E0-\\u00FC])\\W)|_",
"/",
"g",
",",
"''",
")",
";",
"if",
"(",
"!",
"substitutions",
")",
"{",
"return",
"input",
";",
"}",
"var",
"safeSubstitutions",
"=",
"substitutions",
";",
"return",
"Object",
".",
"keys",
"(",
"safeSubstitutions",
")",
".",
"reduce",
"(",
"function",
"(",
"output",
",",
"substitution",
")",
"{",
"var",
"unsubbed",
"=",
"new",
"RegExp",
"(",
"substitution",
",",
"'g'",
")",
";",
"return",
"output",
".",
"replace",
"(",
"unsubbed",
",",
"safeSubstitutions",
"[",
"substitution",
"]",
")",
";",
"}",
",",
"input",
")",
";",
"}"
] | Apply string substitutions, remove non-alphanumeric characters, and convert
all letters to uppercase.
eg. 'Scoil Bhríde Primary School' may become 'SCOILBHRIDEPRIMARYSCHOOL'.
@param input An unsanitized input string.
@param substitutions Strings with multiple spellings or variations that we
expect to match, for example accented characters or abbreviated
words.
@return The sanitized text. | [
"Apply",
"string",
"substitutions",
"remove",
"non",
"-",
"alphanumeric",
"characters",
"and",
"convert",
"all",
"letters",
"to",
"uppercase",
"."
] | 6d22f93324271a301e5840bcc542e945074abcfe | https://github.com/Khan/fuzzy-match-utils/blob/6d22f93324271a301e5840bcc542e945074abcfe/dist/fuzzy-match-utils.js#L199-L219 | train |
Q42Philips/hue-color-converter | index.js | function(red, green, blue, model) {
red = red / 255;
green = green / 255;
blue = blue / 255;
var r = red > 0.04045 ? Math.pow(((red + 0.055) / 1.055), 2.4000000953674316) : red / 12.92;
var g = green > 0.04045 ? Math.pow(((green + 0.055) / 1.055), 2.4000000953674316) : green / 12.92;
var b = blue > 0.04045 ? Math.pow(((blue + 0.055) / 1.055), 2.4000000953674316) : blue / 12.92;
var x = r * 0.664511 + g * 0.154324 + b * 0.162028;
var y = r * 0.283881 + g * 0.668433 + b * 0.047685;
var z = r * 8.8E-5 + g * 0.07231 + b * 0.986039;
var xy = [x / (x + y + z), y / (x + y + z)];
if (isNaN(xy[0])) {
xy[0] = 0.0;
}
if (isNaN(xy[1])) {
xy[1] = 0.0;
}
var colorPoints = colorPointsForModel(model);
var inReachOfLamps = checkPointInLampsReach(xy, colorPoints);
if (!inReachOfLamps) {
var pAB = getClosestPointToPoints(colorPoints[0], colorPoints[1], xy);
var pAC = getClosestPointToPoints(colorPoints[2], colorPoints[0], xy);
var pBC = getClosestPointToPoints(colorPoints[1], colorPoints[2], xy);
var dAB = getDistanceBetweenTwoPoints(xy, pAB);
var dAC = getDistanceBetweenTwoPoints(xy, pAC);
var dBC = getDistanceBetweenTwoPoints(xy, pBC);
var lowest = dAB;
var closestPoint = pAB;
if (dAC < dAB) {
lowest = dAC;
closestPoint = pAC;
}
if (dBC < lowest) {
closestPoint = pBC;
}
xy[0] = closestPoint[0];
xy[1] = closestPoint[1];
}
xy[0] = precision(xy[0]);
xy[1] = precision(xy[1]);
return xy;
} | javascript | function(red, green, blue, model) {
red = red / 255;
green = green / 255;
blue = blue / 255;
var r = red > 0.04045 ? Math.pow(((red + 0.055) / 1.055), 2.4000000953674316) : red / 12.92;
var g = green > 0.04045 ? Math.pow(((green + 0.055) / 1.055), 2.4000000953674316) : green / 12.92;
var b = blue > 0.04045 ? Math.pow(((blue + 0.055) / 1.055), 2.4000000953674316) : blue / 12.92;
var x = r * 0.664511 + g * 0.154324 + b * 0.162028;
var y = r * 0.283881 + g * 0.668433 + b * 0.047685;
var z = r * 8.8E-5 + g * 0.07231 + b * 0.986039;
var xy = [x / (x + y + z), y / (x + y + z)];
if (isNaN(xy[0])) {
xy[0] = 0.0;
}
if (isNaN(xy[1])) {
xy[1] = 0.0;
}
var colorPoints = colorPointsForModel(model);
var inReachOfLamps = checkPointInLampsReach(xy, colorPoints);
if (!inReachOfLamps) {
var pAB = getClosestPointToPoints(colorPoints[0], colorPoints[1], xy);
var pAC = getClosestPointToPoints(colorPoints[2], colorPoints[0], xy);
var pBC = getClosestPointToPoints(colorPoints[1], colorPoints[2], xy);
var dAB = getDistanceBetweenTwoPoints(xy, pAB);
var dAC = getDistanceBetweenTwoPoints(xy, pAC);
var dBC = getDistanceBetweenTwoPoints(xy, pBC);
var lowest = dAB;
var closestPoint = pAB;
if (dAC < dAB) {
lowest = dAC;
closestPoint = pAC;
}
if (dBC < lowest) {
closestPoint = pBC;
}
xy[0] = closestPoint[0];
xy[1] = closestPoint[1];
}
xy[0] = precision(xy[0]);
xy[1] = precision(xy[1]);
return xy;
} | [
"function",
"(",
"red",
",",
"green",
",",
"blue",
",",
"model",
")",
"{",
"red",
"=",
"red",
"/",
"255",
";",
"green",
"=",
"green",
"/",
"255",
";",
"blue",
"=",
"blue",
"/",
"255",
";",
"var",
"r",
"=",
"red",
">",
"0.04045",
"?",
"Math",
".",
"pow",
"(",
"(",
"(",
"red",
"+",
"0.055",
")",
"/",
"1.055",
")",
",",
"2.4000000953674316",
")",
":",
"red",
"/",
"12.92",
";",
"var",
"g",
"=",
"green",
">",
"0.04045",
"?",
"Math",
".",
"pow",
"(",
"(",
"(",
"green",
"+",
"0.055",
")",
"/",
"1.055",
")",
",",
"2.4000000953674316",
")",
":",
"green",
"/",
"12.92",
";",
"var",
"b",
"=",
"blue",
">",
"0.04045",
"?",
"Math",
".",
"pow",
"(",
"(",
"(",
"blue",
"+",
"0.055",
")",
"/",
"1.055",
")",
",",
"2.4000000953674316",
")",
":",
"blue",
"/",
"12.92",
";",
"var",
"x",
"=",
"r",
"*",
"0.664511",
"+",
"g",
"*",
"0.154324",
"+",
"b",
"*",
"0.162028",
";",
"var",
"y",
"=",
"r",
"*",
"0.283881",
"+",
"g",
"*",
"0.668433",
"+",
"b",
"*",
"0.047685",
";",
"var",
"z",
"=",
"r",
"*",
"8.8E-5",
"+",
"g",
"*",
"0.07231",
"+",
"b",
"*",
"0.986039",
";",
"var",
"xy",
"=",
"[",
"x",
"/",
"(",
"x",
"+",
"y",
"+",
"z",
")",
",",
"y",
"/",
"(",
"x",
"+",
"y",
"+",
"z",
")",
"]",
";",
"if",
"(",
"isNaN",
"(",
"xy",
"[",
"0",
"]",
")",
")",
"{",
"xy",
"[",
"0",
"]",
"=",
"0.0",
";",
"}",
"if",
"(",
"isNaN",
"(",
"xy",
"[",
"1",
"]",
")",
")",
"{",
"xy",
"[",
"1",
"]",
"=",
"0.0",
";",
"}",
"var",
"colorPoints",
"=",
"colorPointsForModel",
"(",
"model",
")",
";",
"var",
"inReachOfLamps",
"=",
"checkPointInLampsReach",
"(",
"xy",
",",
"colorPoints",
")",
";",
"if",
"(",
"!",
"inReachOfLamps",
")",
"{",
"var",
"pAB",
"=",
"getClosestPointToPoints",
"(",
"colorPoints",
"[",
"0",
"]",
",",
"colorPoints",
"[",
"1",
"]",
",",
"xy",
")",
";",
"var",
"pAC",
"=",
"getClosestPointToPoints",
"(",
"colorPoints",
"[",
"2",
"]",
",",
"colorPoints",
"[",
"0",
"]",
",",
"xy",
")",
";",
"var",
"pBC",
"=",
"getClosestPointToPoints",
"(",
"colorPoints",
"[",
"1",
"]",
",",
"colorPoints",
"[",
"2",
"]",
",",
"xy",
")",
";",
"var",
"dAB",
"=",
"getDistanceBetweenTwoPoints",
"(",
"xy",
",",
"pAB",
")",
";",
"var",
"dAC",
"=",
"getDistanceBetweenTwoPoints",
"(",
"xy",
",",
"pAC",
")",
";",
"var",
"dBC",
"=",
"getDistanceBetweenTwoPoints",
"(",
"xy",
",",
"pBC",
")",
";",
"var",
"lowest",
"=",
"dAB",
";",
"var",
"closestPoint",
"=",
"pAB",
";",
"if",
"(",
"dAC",
"<",
"dAB",
")",
"{",
"lowest",
"=",
"dAC",
";",
"closestPoint",
"=",
"pAC",
";",
"}",
"if",
"(",
"dBC",
"<",
"lowest",
")",
"{",
"closestPoint",
"=",
"pBC",
";",
"}",
"xy",
"[",
"0",
"]",
"=",
"closestPoint",
"[",
"0",
"]",
";",
"xy",
"[",
"1",
"]",
"=",
"closestPoint",
"[",
"1",
"]",
";",
"}",
"xy",
"[",
"0",
"]",
"=",
"precision",
"(",
"xy",
"[",
"0",
"]",
")",
";",
"xy",
"[",
"1",
"]",
"=",
"precision",
"(",
"xy",
"[",
"1",
"]",
")",
";",
"return",
"xy",
";",
"}"
] | Calculate XY color points for a given RGB value.
@param {number} red RGB red value (0-255)
@param {number} green RGB green value (0-255)
@param {number} blue RGB blue value (0-255)
@param {string} model Hue bulb model
@returns {number[]} | [
"Calculate",
"XY",
"color",
"points",
"for",
"a",
"given",
"RGB",
"value",
"."
] | 98d0faa08b776573deedb2f531b31c795a928a93 | https://github.com/Q42Philips/hue-color-converter/blob/98d0faa08b776573deedb2f531b31c795a928a93/index.js#L20-L66 | train |
|
thinkjs/think-helper | index.js | isInt | function isInt(value) {
if (isNaN(value) || exports.isString(value)) {
return false;
}
var x = parseFloat(value);
return (x | 0) === x;
} | javascript | function isInt(value) {
if (isNaN(value) || exports.isString(value)) {
return false;
}
var x = parseFloat(value);
return (x | 0) === x;
} | [
"function",
"isInt",
"(",
"value",
")",
"{",
"if",
"(",
"isNaN",
"(",
"value",
")",
"||",
"exports",
".",
"isString",
"(",
"value",
")",
")",
"{",
"return",
"false",
";",
"}",
"var",
"x",
"=",
"parseFloat",
"(",
"value",
")",
";",
"return",
"(",
"x",
"|",
"0",
")",
"===",
"x",
";",
"}"
] | check value is integer | [
"check",
"value",
"is",
"integer"
] | 43d7b132a47248ebb403a01901936c480906e8a0 | https://github.com/thinkjs/think-helper/blob/43d7b132a47248ebb403a01901936c480906e8a0/index.js#L64-L70 | train |
thinkjs/think-helper | index.js | isEmpty | function isEmpty(obj) {
if (isTrueEmpty(obj)) return true;
if (exports.isRegExp(obj)) {
return false;
} else if (exports.isDate(obj)) {
return false;
} else if (exports.isError(obj)) {
return false;
} else if (exports.isArray(obj)) {
return obj.length === 0;
} else if (exports.isString(obj)) {
return obj.length === 0;
} else if (exports.isNumber(obj)) {
return obj === 0;
} else if (exports.isBoolean(obj)) {
return !obj;
} else if (exports.isObject(obj)) {
for (const key in obj) {
return false && key; // only for eslint
}
return true;
}
return false;
} | javascript | function isEmpty(obj) {
if (isTrueEmpty(obj)) return true;
if (exports.isRegExp(obj)) {
return false;
} else if (exports.isDate(obj)) {
return false;
} else if (exports.isError(obj)) {
return false;
} else if (exports.isArray(obj)) {
return obj.length === 0;
} else if (exports.isString(obj)) {
return obj.length === 0;
} else if (exports.isNumber(obj)) {
return obj === 0;
} else if (exports.isBoolean(obj)) {
return !obj;
} else if (exports.isObject(obj)) {
for (const key in obj) {
return false && key; // only for eslint
}
return true;
}
return false;
} | [
"function",
"isEmpty",
"(",
"obj",
")",
"{",
"if",
"(",
"isTrueEmpty",
"(",
"obj",
")",
")",
"return",
"true",
";",
"if",
"(",
"exports",
".",
"isRegExp",
"(",
"obj",
")",
")",
"{",
"return",
"false",
";",
"}",
"else",
"if",
"(",
"exports",
".",
"isDate",
"(",
"obj",
")",
")",
"{",
"return",
"false",
";",
"}",
"else",
"if",
"(",
"exports",
".",
"isError",
"(",
"obj",
")",
")",
"{",
"return",
"false",
";",
"}",
"else",
"if",
"(",
"exports",
".",
"isArray",
"(",
"obj",
")",
")",
"{",
"return",
"obj",
".",
"length",
"===",
"0",
";",
"}",
"else",
"if",
"(",
"exports",
".",
"isString",
"(",
"obj",
")",
")",
"{",
"return",
"obj",
".",
"length",
"===",
"0",
";",
"}",
"else",
"if",
"(",
"exports",
".",
"isNumber",
"(",
"obj",
")",
")",
"{",
"return",
"obj",
"===",
"0",
";",
"}",
"else",
"if",
"(",
"exports",
".",
"isBoolean",
"(",
"obj",
")",
")",
"{",
"return",
"!",
"obj",
";",
"}",
"else",
"if",
"(",
"exports",
".",
"isObject",
"(",
"obj",
")",
")",
"{",
"for",
"(",
"const",
"key",
"in",
"obj",
")",
"{",
"return",
"false",
"&&",
"key",
";",
"}",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | check object is mepty
@param {[Mixed]} obj []
@return {Boolean} [] | [
"check",
"object",
"is",
"mepty"
] | 43d7b132a47248ebb403a01901936c480906e8a0 | https://github.com/thinkjs/think-helper/blob/43d7b132a47248ebb403a01901936c480906e8a0/index.js#L186-L209 | train |
thinkjs/think-helper | index.js | isExist | function isExist(dir) {
dir = path.normalize(dir);
try {
fs.accessSync(dir, fs.R_OK);
return true;
} catch (e) {
return false;
}
} | javascript | function isExist(dir) {
dir = path.normalize(dir);
try {
fs.accessSync(dir, fs.R_OK);
return true;
} catch (e) {
return false;
}
} | [
"function",
"isExist",
"(",
"dir",
")",
"{",
"dir",
"=",
"path",
".",
"normalize",
"(",
"dir",
")",
";",
"try",
"{",
"fs",
".",
"accessSync",
"(",
"dir",
",",
"fs",
".",
"R_OK",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"false",
";",
"}",
"}"
] | check path is exist | [
"check",
"path",
"is",
"exist"
] | 43d7b132a47248ebb403a01901936c480906e8a0 | https://github.com/thinkjs/think-helper/blob/43d7b132a47248ebb403a01901936c480906e8a0/index.js#L386-L394 | train |
thinkjs/think-helper | index.js | isFile | function isFile(filePath) {
if (!isExist(filePath)) return false;
try {
const stat = fs.statSync(filePath);
return stat.isFile();
} catch (e) {
return false;
}
} | javascript | function isFile(filePath) {
if (!isExist(filePath)) return false;
try {
const stat = fs.statSync(filePath);
return stat.isFile();
} catch (e) {
return false;
}
} | [
"function",
"isFile",
"(",
"filePath",
")",
"{",
"if",
"(",
"!",
"isExist",
"(",
"filePath",
")",
")",
"return",
"false",
";",
"try",
"{",
"const",
"stat",
"=",
"fs",
".",
"statSync",
"(",
"filePath",
")",
";",
"return",
"stat",
".",
"isFile",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"false",
";",
"}",
"}"
] | check filepath is file | [
"check",
"filepath",
"is",
"file"
] | 43d7b132a47248ebb403a01901936c480906e8a0 | https://github.com/thinkjs/think-helper/blob/43d7b132a47248ebb403a01901936c480906e8a0/index.js#L401-L409 | train |
thinkjs/think-helper | index.js | isDirectory | function isDirectory(filePath) {
if (!isExist(filePath)) return false;
try {
const stat = fs.statSync(filePath);
return stat.isDirectory();
} catch (e) {
return false;
}
} | javascript | function isDirectory(filePath) {
if (!isExist(filePath)) return false;
try {
const stat = fs.statSync(filePath);
return stat.isDirectory();
} catch (e) {
return false;
}
} | [
"function",
"isDirectory",
"(",
"filePath",
")",
"{",
"if",
"(",
"!",
"isExist",
"(",
"filePath",
")",
")",
"return",
"false",
";",
"try",
"{",
"const",
"stat",
"=",
"fs",
".",
"statSync",
"(",
"filePath",
")",
";",
"return",
"stat",
".",
"isDirectory",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"false",
";",
"}",
"}"
] | check path is directory | [
"check",
"path",
"is",
"directory"
] | 43d7b132a47248ebb403a01901936c480906e8a0 | https://github.com/thinkjs/think-helper/blob/43d7b132a47248ebb403a01901936c480906e8a0/index.js#L415-L423 | train |
thinkjs/think-helper | index.js | chmod | function chmod(p, mode) {
try {
fs.chmodSync(p, mode);
return true;
} catch (e) {
return false;
}
} | javascript | function chmod(p, mode) {
try {
fs.chmodSync(p, mode);
return true;
} catch (e) {
return false;
}
} | [
"function",
"chmod",
"(",
"p",
",",
"mode",
")",
"{",
"try",
"{",
"fs",
".",
"chmodSync",
"(",
"p",
",",
"mode",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"false",
";",
"}",
"}"
] | change path mode
@param {String} p [path]
@param {String} mode [path mode]
@return {Boolean} [] | [
"change",
"path",
"mode"
] | 43d7b132a47248ebb403a01901936c480906e8a0 | https://github.com/thinkjs/think-helper/blob/43d7b132a47248ebb403a01901936c480906e8a0/index.js#L432-L439 | train |
thinkjs/think-helper | index.js | getdirFiles | function getdirFiles(dir, prefix = '') {
dir = path.normalize(dir);
if (!fs.existsSync(dir)) return [];
const files = fs.readdirSync(dir);
let result = [];
files.forEach(item => {
const currentDir = path.join(dir, item);
const stat = fs.statSync(currentDir);
if (stat.isFile()) {
result.push(path.join(prefix, item));
} else if (stat.isDirectory()) {
const cFiles = getdirFiles(currentDir, path.join(prefix, item));
result = result.concat(cFiles);
}
});
return result;
} | javascript | function getdirFiles(dir, prefix = '') {
dir = path.normalize(dir);
if (!fs.existsSync(dir)) return [];
const files = fs.readdirSync(dir);
let result = [];
files.forEach(item => {
const currentDir = path.join(dir, item);
const stat = fs.statSync(currentDir);
if (stat.isFile()) {
result.push(path.join(prefix, item));
} else if (stat.isDirectory()) {
const cFiles = getdirFiles(currentDir, path.join(prefix, item));
result = result.concat(cFiles);
}
});
return result;
} | [
"function",
"getdirFiles",
"(",
"dir",
",",
"prefix",
"=",
"''",
")",
"{",
"dir",
"=",
"path",
".",
"normalize",
"(",
"dir",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"dir",
")",
")",
"return",
"[",
"]",
";",
"const",
"files",
"=",
"fs",
".",
"readdirSync",
"(",
"dir",
")",
";",
"let",
"result",
"=",
"[",
"]",
";",
"files",
".",
"forEach",
"(",
"item",
"=>",
"{",
"const",
"currentDir",
"=",
"path",
".",
"join",
"(",
"dir",
",",
"item",
")",
";",
"const",
"stat",
"=",
"fs",
".",
"statSync",
"(",
"currentDir",
")",
";",
"if",
"(",
"stat",
".",
"isFile",
"(",
")",
")",
"{",
"result",
".",
"push",
"(",
"path",
".",
"join",
"(",
"prefix",
",",
"item",
")",
")",
";",
"}",
"else",
"if",
"(",
"stat",
".",
"isDirectory",
"(",
")",
")",
"{",
"const",
"cFiles",
"=",
"getdirFiles",
"(",
"currentDir",
",",
"path",
".",
"join",
"(",
"prefix",
",",
"item",
")",
")",
";",
"result",
"=",
"result",
".",
"concat",
"(",
"cFiles",
")",
";",
"}",
"}",
")",
";",
"return",
"result",
";",
"}"
] | get files in path
@param {} dir []
@param {} prefix []
@return {} [] | [
"get",
"files",
"in",
"path"
] | 43d7b132a47248ebb403a01901936c480906e8a0 | https://github.com/thinkjs/think-helper/blob/43d7b132a47248ebb403a01901936c480906e8a0/index.js#L470-L486 | train |
thinkjs/think-helper | index.js | rmdir | function rmdir(p, reserve) {
if (!isDirectory(p)) return Promise.resolve();
return fsReaddir(p).then(files => {
const promises = files.map(item => {
const filepath = path.join(p, item);
if (isDirectory(filepath)) return rmdir(filepath, false);
return fsUnlink(filepath);
});
return Promise.all(promises).then(() => {
if (!reserve) return fsRmdir(p);
});
});
} | javascript | function rmdir(p, reserve) {
if (!isDirectory(p)) return Promise.resolve();
return fsReaddir(p).then(files => {
const promises = files.map(item => {
const filepath = path.join(p, item);
if (isDirectory(filepath)) return rmdir(filepath, false);
return fsUnlink(filepath);
});
return Promise.all(promises).then(() => {
if (!reserve) return fsRmdir(p);
});
});
} | [
"function",
"rmdir",
"(",
"p",
",",
"reserve",
")",
"{",
"if",
"(",
"!",
"isDirectory",
"(",
"p",
")",
")",
"return",
"Promise",
".",
"resolve",
"(",
")",
";",
"return",
"fsReaddir",
"(",
"p",
")",
".",
"then",
"(",
"files",
"=>",
"{",
"const",
"promises",
"=",
"files",
".",
"map",
"(",
"item",
"=>",
"{",
"const",
"filepath",
"=",
"path",
".",
"join",
"(",
"p",
",",
"item",
")",
";",
"if",
"(",
"isDirectory",
"(",
"filepath",
")",
")",
"return",
"rmdir",
"(",
"filepath",
",",
"false",
")",
";",
"return",
"fsUnlink",
"(",
"filepath",
")",
";",
"}",
")",
";",
"return",
"Promise",
".",
"all",
"(",
"promises",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"if",
"(",
"!",
"reserve",
")",
"return",
"fsRmdir",
"(",
"p",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | remove dir aync
@param {String} p [path]
@param {Boolean} reserve []
@return {Promise} [] | [
"remove",
"dir",
"aync"
] | 43d7b132a47248ebb403a01901936c480906e8a0 | https://github.com/thinkjs/think-helper/blob/43d7b132a47248ebb403a01901936c480906e8a0/index.js#L496-L508 | train |
ember-cli/node-modules-path | index.js | nodeModulePaths | function nodeModulePaths(from) {
// guarantee that 'from' is absolute.
from = path.resolve(from);
// note: this approach *only* works when the path is guaranteed
// to be absolute. Doing a fully-edge-case-correct path.split
// that works on both Windows and Posix is non-trivial.
var splitRe = process.platform === 'win32' ? /[\/\\]/ : /\//;
var paths = [];
var parts = from.split(splitRe);
for (var tip = parts.length - 1; tip >= 0; tip--) {
// don't search in .../node_modules/node_modules
if (parts[tip] === 'node_modules') {
continue;
}
var dir = parts.slice(0, tip + 1).concat('node_modules').join(path.sep);
paths.push(dir);
}
return paths;
} | javascript | function nodeModulePaths(from) {
// guarantee that 'from' is absolute.
from = path.resolve(from);
// note: this approach *only* works when the path is guaranteed
// to be absolute. Doing a fully-edge-case-correct path.split
// that works on both Windows and Posix is non-trivial.
var splitRe = process.platform === 'win32' ? /[\/\\]/ : /\//;
var paths = [];
var parts = from.split(splitRe);
for (var tip = parts.length - 1; tip >= 0; tip--) {
// don't search in .../node_modules/node_modules
if (parts[tip] === 'node_modules') {
continue;
}
var dir = parts.slice(0, tip + 1).concat('node_modules').join(path.sep);
paths.push(dir);
}
return paths;
} | [
"function",
"nodeModulePaths",
"(",
"from",
")",
"{",
"from",
"=",
"path",
".",
"resolve",
"(",
"from",
")",
";",
"var",
"splitRe",
"=",
"process",
".",
"platform",
"===",
"'win32'",
"?",
"/",
"[\\/\\\\]",
"/",
":",
"/",
"\\/",
"/",
";",
"var",
"paths",
"=",
"[",
"]",
";",
"var",
"parts",
"=",
"from",
".",
"split",
"(",
"splitRe",
")",
";",
"for",
"(",
"var",
"tip",
"=",
"parts",
".",
"length",
"-",
"1",
";",
"tip",
">=",
"0",
";",
"tip",
"--",
")",
"{",
"if",
"(",
"parts",
"[",
"tip",
"]",
"===",
"'node_modules'",
")",
"{",
"continue",
";",
"}",
"var",
"dir",
"=",
"parts",
".",
"slice",
"(",
"0",
",",
"tip",
"+",
"1",
")",
".",
"concat",
"(",
"'node_modules'",
")",
".",
"join",
"(",
"path",
".",
"sep",
")",
";",
"paths",
".",
"push",
"(",
"dir",
")",
";",
"}",
"return",
"paths",
";",
"}"
] | Due to the fact that the node community doesn't feel that the node_modules resolution algorithm should be public method we have copy pasta'd it here. | [
"Due",
"to",
"the",
"fact",
"that",
"the",
"node",
"community",
"doesn",
"t",
"feel",
"that",
"the",
"node_modules",
"resolution",
"algorithm",
"should",
"be",
"public",
"method",
"we",
"have",
"copy",
"pasta",
"d",
"it",
"here",
"."
] | adbcc4a5ebeeae3dfa0adffc1821170ce9b47dad | https://github.com/ember-cli/node-modules-path/blob/adbcc4a5ebeeae3dfa0adffc1821170ce9b47dad/index.js#L9-L31 | train |
c9/vfs-local | localfs.js | createStatEntry | function createStatEntry(file, fullpath, callback) {
fs.lstat(fullpath, function (err, stat) {
var entry = {
name: file
};
if (err) {
entry.err = err;
return callback(entry);
} else {
entry.size = stat.size;
entry.mtime = stat.mtime.valueOf();
if (stat.isDirectory()) {
entry.mime = "inode/directory";
} else if (stat.isBlockDevice()) entry.mime = "inode/blockdevice";
else if (stat.isCharacterDevice()) entry.mime = "inode/chardevice";
else if (stat.isSymbolicLink()) entry.mime = "inode/symlink";
else if (stat.isFIFO()) entry.mime = "inode/fifo";
else if (stat.isSocket()) entry.mime = "inode/socket";
else {
entry.mime = getMime(fullpath);
}
if (!stat.isSymbolicLink()) {
return callback(entry);
}
fs.readlink(fullpath, function (err, link) {
if (entry.name == link) {
entry.linkStatErr = "ELOOP: recursive symlink";
return callback(entry);
}
if (err) {
entry.linkErr = err.stack;
return callback(entry);
}
entry.link = link;
resolvePath(pathResolve(dirname(fullpath), link), {alreadyRooted: true}, function (err, newpath) {
if (err) {
entry.linkStatErr = err;
return callback(entry);
}
createStatEntry(basename(newpath), newpath, function (linkStat) {
entry.linkStat = linkStat;
linkStat.fullPath = newpath.substr(base.length) || "/";
return callback(entry);
});
});
});
}
});
} | javascript | function createStatEntry(file, fullpath, callback) {
fs.lstat(fullpath, function (err, stat) {
var entry = {
name: file
};
if (err) {
entry.err = err;
return callback(entry);
} else {
entry.size = stat.size;
entry.mtime = stat.mtime.valueOf();
if (stat.isDirectory()) {
entry.mime = "inode/directory";
} else if (stat.isBlockDevice()) entry.mime = "inode/blockdevice";
else if (stat.isCharacterDevice()) entry.mime = "inode/chardevice";
else if (stat.isSymbolicLink()) entry.mime = "inode/symlink";
else if (stat.isFIFO()) entry.mime = "inode/fifo";
else if (stat.isSocket()) entry.mime = "inode/socket";
else {
entry.mime = getMime(fullpath);
}
if (!stat.isSymbolicLink()) {
return callback(entry);
}
fs.readlink(fullpath, function (err, link) {
if (entry.name == link) {
entry.linkStatErr = "ELOOP: recursive symlink";
return callback(entry);
}
if (err) {
entry.linkErr = err.stack;
return callback(entry);
}
entry.link = link;
resolvePath(pathResolve(dirname(fullpath), link), {alreadyRooted: true}, function (err, newpath) {
if (err) {
entry.linkStatErr = err;
return callback(entry);
}
createStatEntry(basename(newpath), newpath, function (linkStat) {
entry.linkStat = linkStat;
linkStat.fullPath = newpath.substr(base.length) || "/";
return callback(entry);
});
});
});
}
});
} | [
"function",
"createStatEntry",
"(",
"file",
",",
"fullpath",
",",
"callback",
")",
"{",
"fs",
".",
"lstat",
"(",
"fullpath",
",",
"function",
"(",
"err",
",",
"stat",
")",
"{",
"var",
"entry",
"=",
"{",
"name",
":",
"file",
"}",
";",
"if",
"(",
"err",
")",
"{",
"entry",
".",
"err",
"=",
"err",
";",
"return",
"callback",
"(",
"entry",
")",
";",
"}",
"else",
"{",
"entry",
".",
"size",
"=",
"stat",
".",
"size",
";",
"entry",
".",
"mtime",
"=",
"stat",
".",
"mtime",
".",
"valueOf",
"(",
")",
";",
"if",
"(",
"stat",
".",
"isDirectory",
"(",
")",
")",
"{",
"entry",
".",
"mime",
"=",
"\"inode/directory\"",
";",
"}",
"else",
"if",
"(",
"stat",
".",
"isBlockDevice",
"(",
")",
")",
"entry",
".",
"mime",
"=",
"\"inode/blockdevice\"",
";",
"else",
"if",
"(",
"stat",
".",
"isCharacterDevice",
"(",
")",
")",
"entry",
".",
"mime",
"=",
"\"inode/chardevice\"",
";",
"else",
"if",
"(",
"stat",
".",
"isSymbolicLink",
"(",
")",
")",
"entry",
".",
"mime",
"=",
"\"inode/symlink\"",
";",
"else",
"if",
"(",
"stat",
".",
"isFIFO",
"(",
")",
")",
"entry",
".",
"mime",
"=",
"\"inode/fifo\"",
";",
"else",
"if",
"(",
"stat",
".",
"isSocket",
"(",
")",
")",
"entry",
".",
"mime",
"=",
"\"inode/socket\"",
";",
"else",
"{",
"entry",
".",
"mime",
"=",
"getMime",
"(",
"fullpath",
")",
";",
"}",
"if",
"(",
"!",
"stat",
".",
"isSymbolicLink",
"(",
")",
")",
"{",
"return",
"callback",
"(",
"entry",
")",
";",
"}",
"fs",
".",
"readlink",
"(",
"fullpath",
",",
"function",
"(",
"err",
",",
"link",
")",
"{",
"if",
"(",
"entry",
".",
"name",
"==",
"link",
")",
"{",
"entry",
".",
"linkStatErr",
"=",
"\"ELOOP: recursive symlink\"",
";",
"return",
"callback",
"(",
"entry",
")",
";",
"}",
"if",
"(",
"err",
")",
"{",
"entry",
".",
"linkErr",
"=",
"err",
".",
"stack",
";",
"return",
"callback",
"(",
"entry",
")",
";",
"}",
"entry",
".",
"link",
"=",
"link",
";",
"resolvePath",
"(",
"pathResolve",
"(",
"dirname",
"(",
"fullpath",
")",
",",
"link",
")",
",",
"{",
"alreadyRooted",
":",
"true",
"}",
",",
"function",
"(",
"err",
",",
"newpath",
")",
"{",
"if",
"(",
"err",
")",
"{",
"entry",
".",
"linkStatErr",
"=",
"err",
";",
"return",
"callback",
"(",
"entry",
")",
";",
"}",
"createStatEntry",
"(",
"basename",
"(",
"newpath",
")",
",",
"newpath",
",",
"function",
"(",
"linkStat",
")",
"{",
"entry",
".",
"linkStat",
"=",
"linkStat",
";",
"linkStat",
".",
"fullPath",
"=",
"newpath",
".",
"substr",
"(",
"base",
".",
"length",
")",
"||",
"\"/\"",
";",
"return",
"callback",
"(",
"entry",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] | This helper function doesn't follow node conventions in the callback, there is no err, only entry. | [
"This",
"helper",
"function",
"doesn",
"t",
"follow",
"node",
"conventions",
"in",
"the",
"callback",
"there",
"is",
"no",
"err",
"only",
"entry",
"."
] | 9569c00e2fca4a4e2c2c9c0227e440322cd74882 | https://github.com/c9/vfs-local/blob/9569c00e2fca4a4e2c2c9c0227e440322cd74882/localfs.js#L166-L218 | train |
c9/vfs-local | localfs.js | remove | function remove(path, fn, callback) {
var meta = {};
resolvePath(path, function (err, realpath) {
if (err) return callback(err);
fn(realpath, function (err) {
if (err) return callback(err);
// Remove metadata
resolvePath(WSMETAPATH + path, function (err, realpath) {
if (err) return callback(null, meta);
fn(realpath, function(){
return callback(null, meta);
});
});
});
});
} | javascript | function remove(path, fn, callback) {
var meta = {};
resolvePath(path, function (err, realpath) {
if (err) return callback(err);
fn(realpath, function (err) {
if (err) return callback(err);
// Remove metadata
resolvePath(WSMETAPATH + path, function (err, realpath) {
if (err) return callback(null, meta);
fn(realpath, function(){
return callback(null, meta);
});
});
});
});
} | [
"function",
"remove",
"(",
"path",
",",
"fn",
",",
"callback",
")",
"{",
"var",
"meta",
"=",
"{",
"}",
";",
"resolvePath",
"(",
"path",
",",
"function",
"(",
"err",
",",
"realpath",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"fn",
"(",
"realpath",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"resolvePath",
"(",
"WSMETAPATH",
"+",
"path",
",",
"function",
"(",
"err",
",",
"realpath",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"null",
",",
"meta",
")",
";",
"fn",
"(",
"realpath",
",",
"function",
"(",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"meta",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Common logic used by rmdir and rmfile | [
"Common",
"logic",
"used",
"by",
"rmdir",
"and",
"rmfile"
] | 9569c00e2fca4a4e2c2c9c0227e440322cd74882 | https://github.com/c9/vfs-local/blob/9569c00e2fca4a4e2c2c9c0227e440322cd74882/localfs.js#L221-L238 | train |
c9/vfs-local | localfs.js | resolve | function resolve() {
resolvePath(path, function (err, _resolvedPath) {
if (err) {
if (err.code !== "ENOENT") {
return error(err);
}
// If checkSymlinks is on we'll get an ENOENT when creating a new file.
// In that case, just resolve the parent path and go from there.
resolvePath(dirname(path), function (err, dir) {
if (err) return error(err);
resolvedPath = join(dir, basename(path));
createTempFile();
});
return;
}
resolvedPath = _resolvedPath;
createTempFile();
});
} | javascript | function resolve() {
resolvePath(path, function (err, _resolvedPath) {
if (err) {
if (err.code !== "ENOENT") {
return error(err);
}
// If checkSymlinks is on we'll get an ENOENT when creating a new file.
// In that case, just resolve the parent path and go from there.
resolvePath(dirname(path), function (err, dir) {
if (err) return error(err);
resolvedPath = join(dir, basename(path));
createTempFile();
});
return;
}
resolvedPath = _resolvedPath;
createTempFile();
});
} | [
"function",
"resolve",
"(",
")",
"{",
"resolvePath",
"(",
"path",
",",
"function",
"(",
"err",
",",
"_resolvedPath",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"code",
"!==",
"\"ENOENT\"",
")",
"{",
"return",
"error",
"(",
"err",
")",
";",
"}",
"resolvePath",
"(",
"dirname",
"(",
"path",
")",
",",
"function",
"(",
"err",
",",
"dir",
")",
"{",
"if",
"(",
"err",
")",
"return",
"error",
"(",
"err",
")",
";",
"resolvedPath",
"=",
"join",
"(",
"dir",
",",
"basename",
"(",
"path",
")",
")",
";",
"createTempFile",
"(",
")",
";",
"}",
")",
";",
"return",
";",
"}",
"resolvedPath",
"=",
"_resolvedPath",
";",
"createTempFile",
"(",
")",
";",
"}",
")",
";",
"}"
] | Make sure the user has access to the directory and get the real path. | [
"Make",
"sure",
"the",
"user",
"has",
"access",
"to",
"the",
"directory",
"and",
"get",
"the",
"real",
"path",
"."
] | 9569c00e2fca4a4e2c2c9c0227e440322cd74882 | https://github.com/c9/vfs-local/blob/9569c00e2fca4a4e2c2c9c0227e440322cd74882/localfs.js#L500-L519 | train |
c9/vfs-local | localfs.js | consumeStream | function consumeStream(stream, callback) {
var chunks = [];
stream.on("data", onData);
stream.on("end", onEnd);
stream.on("error", onError);
function onData(chunk) {
chunks.push(chunk);
}
function onEnd() {
cleanup();
callback(null, chunks.join(""));
}
function onError(err) {
cleanup();
callback(err);
}
function cleanup() {
stream.removeListener("data", onData);
stream.removeListener("end", onEnd);
stream.removeListener("error", onError);
}
} | javascript | function consumeStream(stream, callback) {
var chunks = [];
stream.on("data", onData);
stream.on("end", onEnd);
stream.on("error", onError);
function onData(chunk) {
chunks.push(chunk);
}
function onEnd() {
cleanup();
callback(null, chunks.join(""));
}
function onError(err) {
cleanup();
callback(err);
}
function cleanup() {
stream.removeListener("data", onData);
stream.removeListener("end", onEnd);
stream.removeListener("error", onError);
}
} | [
"function",
"consumeStream",
"(",
"stream",
",",
"callback",
")",
"{",
"var",
"chunks",
"=",
"[",
"]",
";",
"stream",
".",
"on",
"(",
"\"data\"",
",",
"onData",
")",
";",
"stream",
".",
"on",
"(",
"\"end\"",
",",
"onEnd",
")",
";",
"stream",
".",
"on",
"(",
"\"error\"",
",",
"onError",
")",
";",
"function",
"onData",
"(",
"chunk",
")",
"{",
"chunks",
".",
"push",
"(",
"chunk",
")",
";",
"}",
"function",
"onEnd",
"(",
")",
"{",
"cleanup",
"(",
")",
";",
"callback",
"(",
"null",
",",
"chunks",
".",
"join",
"(",
"\"\"",
")",
")",
";",
"}",
"function",
"onError",
"(",
"err",
")",
"{",
"cleanup",
"(",
")",
";",
"callback",
"(",
"err",
")",
";",
"}",
"function",
"cleanup",
"(",
")",
"{",
"stream",
".",
"removeListener",
"(",
"\"data\"",
",",
"onData",
")",
";",
"stream",
".",
"removeListener",
"(",
"\"end\"",
",",
"onEnd",
")",
";",
"stream",
".",
"removeListener",
"(",
"\"error\"",
",",
"onError",
")",
";",
"}",
"}"
] | Consume all data in a readable stream and call callback with full buffer. | [
"Consume",
"all",
"data",
"in",
"a",
"readable",
"stream",
"and",
"call",
"callback",
"with",
"full",
"buffer",
"."
] | 9569c00e2fca4a4e2c2c9c0227e440322cd74882 | https://github.com/c9/vfs-local/blob/9569c00e2fca4a4e2c2c9c0227e440322cd74882/localfs.js#L1114-L1135 | train |
c9/vfs-local | localfs.js | evaluate | function evaluate(code) {
var exports = {};
var module = { exports: exports };
vm.runInNewContext(code, {
require: require,
exports: exports,
module: module,
console: console,
global: global,
process: process,
Buffer: Buffer,
setTimeout: setTimeout,
clearTimeout: clearTimeout,
setInterval: setInterval,
clearInterval: clearInterval
}, "dynamic-" + Date.now().toString(36), true);
return module.exports;
} | javascript | function evaluate(code) {
var exports = {};
var module = { exports: exports };
vm.runInNewContext(code, {
require: require,
exports: exports,
module: module,
console: console,
global: global,
process: process,
Buffer: Buffer,
setTimeout: setTimeout,
clearTimeout: clearTimeout,
setInterval: setInterval,
clearInterval: clearInterval
}, "dynamic-" + Date.now().toString(36), true);
return module.exports;
} | [
"function",
"evaluate",
"(",
"code",
")",
"{",
"var",
"exports",
"=",
"{",
"}",
";",
"var",
"module",
"=",
"{",
"exports",
":",
"exports",
"}",
";",
"vm",
".",
"runInNewContext",
"(",
"code",
",",
"{",
"require",
":",
"require",
",",
"exports",
":",
"exports",
",",
"module",
":",
"module",
",",
"console",
":",
"console",
",",
"global",
":",
"global",
",",
"process",
":",
"process",
",",
"Buffer",
":",
"Buffer",
",",
"setTimeout",
":",
"setTimeout",
",",
"clearTimeout",
":",
"clearTimeout",
",",
"setInterval",
":",
"setInterval",
",",
"clearInterval",
":",
"clearInterval",
"}",
",",
"\"dynamic-\"",
"+",
"Date",
".",
"now",
"(",
")",
".",
"toString",
"(",
"36",
")",
",",
"true",
")",
";",
"return",
"module",
".",
"exports",
";",
"}"
] | node-style eval | [
"node",
"-",
"style",
"eval"
] | 9569c00e2fca4a4e2c2c9c0227e440322cd74882 | https://github.com/c9/vfs-local/blob/9569c00e2fca4a4e2c2c9c0227e440322cd74882/localfs.js#L1138-L1155 | train |
c9/vfs-local | localfs.js | calcEtag | function calcEtag(stat) {
return (stat.isFile() ? '': 'W/') + '"' + (stat.ino || 0).toString(36) + "-" + stat.size.toString(36) + "-" + stat.mtime.valueOf().toString(36) + '"';
} | javascript | function calcEtag(stat) {
return (stat.isFile() ? '': 'W/') + '"' + (stat.ino || 0).toString(36) + "-" + stat.size.toString(36) + "-" + stat.mtime.valueOf().toString(36) + '"';
} | [
"function",
"calcEtag",
"(",
"stat",
")",
"{",
"return",
"(",
"stat",
".",
"isFile",
"(",
")",
"?",
"''",
":",
"'W/'",
")",
"+",
"'\"'",
"+",
"(",
"stat",
".",
"ino",
"||",
"0",
")",
".",
"toString",
"(",
"36",
")",
"+",
"\"-\"",
"+",
"stat",
".",
"size",
".",
"toString",
"(",
"36",
")",
"+",
"\"-\"",
"+",
"stat",
".",
"mtime",
".",
"valueOf",
"(",
")",
".",
"toString",
"(",
"36",
")",
"+",
"'\"'",
";",
"}"
] | Calculate a proper etag from a nodefs stat object | [
"Calculate",
"a",
"proper",
"etag",
"from",
"a",
"nodefs",
"stat",
"object"
] | 9569c00e2fca4a4e2c2c9c0227e440322cd74882 | https://github.com/c9/vfs-local/blob/9569c00e2fca4a4e2c2c9c0227e440322cd74882/localfs.js#L1158-L1160 | train |
catamphetamine/react-styling | source/index.js | parse_style_json_object | function parse_style_json_object(text, options)
{
// remove multiline comments
text = text.replace(/\/\*([\s\S]*?)\*\//g, '')
// ignore curly braces for now.
// maybe support curly braces along with tabulation in future
text = text.replace(/[\{\}]/g, '')
const lines = text.split('\n')
// helper class for dealing with tabulation
const tabulator = new Tabulator(Tabulator.determine_tabulation(lines))
// parse text into JSON object
let style_json = parse_style_class(tabulator.extract_tabulation(lines), [])
// expand CSS shorthand properties
// (e.g. `margin: 1px` -> `margin-left: 1px; ...`)
if (options.expand)
{
style_json = style_builder.build(style_json)
}
// expand "modifier" style classes
// (which can override some of the expanded shorthand CSS properties)
return expand_modifier_style_classes(style_json)
} | javascript | function parse_style_json_object(text, options)
{
// remove multiline comments
text = text.replace(/\/\*([\s\S]*?)\*\//g, '')
// ignore curly braces for now.
// maybe support curly braces along with tabulation in future
text = text.replace(/[\{\}]/g, '')
const lines = text.split('\n')
// helper class for dealing with tabulation
const tabulator = new Tabulator(Tabulator.determine_tabulation(lines))
// parse text into JSON object
let style_json = parse_style_class(tabulator.extract_tabulation(lines), [])
// expand CSS shorthand properties
// (e.g. `margin: 1px` -> `margin-left: 1px; ...`)
if (options.expand)
{
style_json = style_builder.build(style_json)
}
// expand "modifier" style classes
// (which can override some of the expanded shorthand CSS properties)
return expand_modifier_style_classes(style_json)
} | [
"function",
"parse_style_json_object",
"(",
"text",
",",
"options",
")",
"{",
"text",
"=",
"text",
".",
"replace",
"(",
"/",
"\\/\\*([\\s\\S]*?)\\*\\/",
"/",
"g",
",",
"''",
")",
"text",
"=",
"text",
".",
"replace",
"(",
"/",
"[\\{\\}]",
"/",
"g",
",",
"''",
")",
"const",
"lines",
"=",
"text",
".",
"split",
"(",
"'\\n'",
")",
"\\n",
"const",
"tabulator",
"=",
"new",
"Tabulator",
"(",
"Tabulator",
".",
"determine_tabulation",
"(",
"lines",
")",
")",
"let",
"style_json",
"=",
"parse_style_class",
"(",
"tabulator",
".",
"extract_tabulation",
"(",
"lines",
")",
",",
"[",
"]",
")",
"if",
"(",
"options",
".",
"expand",
")",
"{",
"style_json",
"=",
"style_builder",
".",
"build",
"(",
"style_json",
")",
"}",
"}"
] | converts text to JSON object | [
"converts",
"text",
"to",
"JSON",
"object"
] | 24d6fc0de74de67ae6c08450d0542a992d388ff3 | https://github.com/catamphetamine/react-styling/blob/24d6fc0de74de67ae6c08450d0542a992d388ff3/source/index.js#L34-L61 | train |
catamphetamine/react-styling | source/index.js | split_into_style_lines_and_children_lines | function split_into_style_lines_and_children_lines(lines)
{
// get this node style lines
const style_lines = lines.filter(function(line)
{
// styles always have indentation of 1
if (line.tabs !== 1)
{
return false
}
// detect generic css style line (skip modifier classes and media queries)
const colon_index = line.line.indexOf(':')
// is not a modifier class
return !starts_with(line.line, '&')
// is not a media query style class name declaration
&& !starts_with(line.line, '@media')
// is not a keyframes style class name declaration
&& !starts_with(line.line, '@keyframes')
// has a colon
&& colon_index >= 0
// is not a state class (e.g. :hover) name declaration
&& colon_index !== 0
// is not a yaml-style class name declaration
&& colon_index < line.line.length - 1
})
// get children nodes' lines
const children_lines = lines.filter(line => style_lines.indexOf(line) < 0)
// reduce tabulation for this child node's (or these child nodes') child nodes' lines
children_lines.forEach(line => line.tabs--)
return { style_lines, children_lines}
} | javascript | function split_into_style_lines_and_children_lines(lines)
{
// get this node style lines
const style_lines = lines.filter(function(line)
{
// styles always have indentation of 1
if (line.tabs !== 1)
{
return false
}
// detect generic css style line (skip modifier classes and media queries)
const colon_index = line.line.indexOf(':')
// is not a modifier class
return !starts_with(line.line, '&')
// is not a media query style class name declaration
&& !starts_with(line.line, '@media')
// is not a keyframes style class name declaration
&& !starts_with(line.line, '@keyframes')
// has a colon
&& colon_index >= 0
// is not a state class (e.g. :hover) name declaration
&& colon_index !== 0
// is not a yaml-style class name declaration
&& colon_index < line.line.length - 1
})
// get children nodes' lines
const children_lines = lines.filter(line => style_lines.indexOf(line) < 0)
// reduce tabulation for this child node's (or these child nodes') child nodes' lines
children_lines.forEach(line => line.tabs--)
return { style_lines, children_lines}
} | [
"function",
"split_into_style_lines_and_children_lines",
"(",
"lines",
")",
"{",
"const",
"style_lines",
"=",
"lines",
".",
"filter",
"(",
"function",
"(",
"line",
")",
"{",
"if",
"(",
"line",
".",
"tabs",
"!==",
"1",
")",
"{",
"return",
"false",
"}",
"const",
"colon_index",
"=",
"line",
".",
"line",
".",
"indexOf",
"(",
"':'",
")",
"return",
"!",
"starts_with",
"(",
"line",
".",
"line",
",",
"'&'",
")",
"&&",
"!",
"starts_with",
"(",
"line",
".",
"line",
",",
"'@media'",
")",
"&&",
"!",
"starts_with",
"(",
"line",
".",
"line",
",",
"'@keyframes'",
")",
"&&",
"colon_index",
">=",
"0",
"&&",
"colon_index",
"!==",
"0",
"&&",
"colon_index",
"<",
"line",
".",
"line",
".",
"length",
"-",
"1",
"}",
")",
"const",
"children_lines",
"=",
"lines",
".",
"filter",
"(",
"line",
"=>",
"style_lines",
".",
"indexOf",
"(",
"line",
")",
"<",
"0",
")",
"children_lines",
".",
"forEach",
"(",
"line",
"=>",
"line",
".",
"tabs",
"--",
")",
"return",
"{",
"style_lines",
",",
"children_lines",
"}",
"}"
] | separates style lines from children lines | [
"separates",
"style",
"lines",
"from",
"children",
"lines"
] | 24d6fc0de74de67ae6c08450d0542a992d388ff3 | https://github.com/catamphetamine/react-styling/blob/24d6fc0de74de67ae6c08450d0542a992d388ff3/source/index.js#L105-L140 | train |
catamphetamine/react-styling | source/index.js | parse_node_name | function parse_node_name(name)
{
// is it a "modifier" style class
let is_a_modifier = false
// detect modifier style classes
if (starts_with(name, '&'))
{
name = name.substring('&'.length)
is_a_modifier = true
}
// support old-school CSS syntax
if (starts_with(name, '.'))
{
name = name.substring('.'.length)
}
// if there is a trailing colon in the style class name - trim it
// (Python people with yaml-alike syntax)
if (ends_with(name, ':'))
{
name = name.substring(0, name.length - ':'.length)
// throw new Error(`Remove the trailing colon at line: ${original_line}`)
}
return { name, is_a_modifier }
} | javascript | function parse_node_name(name)
{
// is it a "modifier" style class
let is_a_modifier = false
// detect modifier style classes
if (starts_with(name, '&'))
{
name = name.substring('&'.length)
is_a_modifier = true
}
// support old-school CSS syntax
if (starts_with(name, '.'))
{
name = name.substring('.'.length)
}
// if there is a trailing colon in the style class name - trim it
// (Python people with yaml-alike syntax)
if (ends_with(name, ':'))
{
name = name.substring(0, name.length - ':'.length)
// throw new Error(`Remove the trailing colon at line: ${original_line}`)
}
return { name, is_a_modifier }
} | [
"function",
"parse_node_name",
"(",
"name",
")",
"{",
"let",
"is_a_modifier",
"=",
"false",
"if",
"(",
"starts_with",
"(",
"name",
",",
"'&'",
")",
")",
"{",
"name",
"=",
"name",
".",
"substring",
"(",
"'&'",
".",
"length",
")",
"is_a_modifier",
"=",
"true",
"}",
"if",
"(",
"starts_with",
"(",
"name",
",",
"'.'",
")",
")",
"{",
"name",
"=",
"name",
".",
"substring",
"(",
"'.'",
".",
"length",
")",
"}",
"if",
"(",
"ends_with",
"(",
"name",
",",
"':'",
")",
")",
"{",
"name",
"=",
"name",
".",
"substring",
"(",
"0",
",",
"name",
".",
"length",
"-",
"':'",
".",
"length",
")",
"}",
"return",
"{",
"name",
",",
"is_a_modifier",
"}",
"}"
] | parses a style class node name | [
"parses",
"a",
"style",
"class",
"node",
"name"
] | 24d6fc0de74de67ae6c08450d0542a992d388ff3 | https://github.com/catamphetamine/react-styling/blob/24d6fc0de74de67ae6c08450d0542a992d388ff3/source/index.js#L143-L170 | train |
catamphetamine/react-styling | source/index.js | parse_children | function parse_children(lines, parent_node_names)
{
// preprocess the lines (filter out comments, blank lines, etc)
lines = filter_lines_for_parsing(lines)
// return empty object if there are no lines to parse
if (lines.length === 0)
{
return {}
}
// parse each child node's lines
return split_lines_by_child_nodes(lines).map(function(lines)
{
// the first line is this child node's name (or names)
const declaration_line = lines.shift()
// check for excessive indentation of the first child style class
if (declaration_line.tabs !== 0)
{
throw new Error(`Excessive indentation (${declaration_line.tabs} more "tabs" than needed) at line ${declaration_line.index}: "${declaration_line.original_line}"`)
}
// style class name declaration
const declaration = declaration_line.line
// child nodes' names
const names = declaration.split(',').map(name => name.trim())
// style class nesting validation
validate_child_style_class_types(parent_node_names, names)
// parse own CSS styles and recursively parse all child nodes
const style_json = parse_style_class(lines, names)
// generate style json for this child node (or child nodes)
return names.map(function(node_declaration)
{
// parse this child node name
const { name, is_a_modifier } = parse_node_name(node_declaration)
// clone the style JSON object for this child node
const json = extend({}, style_json)
// set the modifier flag if it's the case
if (is_a_modifier)
{
json._is_a_modifier = true
}
// this child node's style JSON object
return { name, json }
})
})
// convert an array of arrays to a flat array
.reduce(function(array, child_array)
{
return array.concat(child_array);
},
[])
// combine all the child nodes into a single JSON object
.reduce(function(nodes, node)
{
// if style already exists for this child node, extend it
if (nodes[node.name])
{
extend(nodes[node.name], node.json)
}
else
{
nodes[node.name] = node.json
}
return nodes
},
{})
} | javascript | function parse_children(lines, parent_node_names)
{
// preprocess the lines (filter out comments, blank lines, etc)
lines = filter_lines_for_parsing(lines)
// return empty object if there are no lines to parse
if (lines.length === 0)
{
return {}
}
// parse each child node's lines
return split_lines_by_child_nodes(lines).map(function(lines)
{
// the first line is this child node's name (or names)
const declaration_line = lines.shift()
// check for excessive indentation of the first child style class
if (declaration_line.tabs !== 0)
{
throw new Error(`Excessive indentation (${declaration_line.tabs} more "tabs" than needed) at line ${declaration_line.index}: "${declaration_line.original_line}"`)
}
// style class name declaration
const declaration = declaration_line.line
// child nodes' names
const names = declaration.split(',').map(name => name.trim())
// style class nesting validation
validate_child_style_class_types(parent_node_names, names)
// parse own CSS styles and recursively parse all child nodes
const style_json = parse_style_class(lines, names)
// generate style json for this child node (or child nodes)
return names.map(function(node_declaration)
{
// parse this child node name
const { name, is_a_modifier } = parse_node_name(node_declaration)
// clone the style JSON object for this child node
const json = extend({}, style_json)
// set the modifier flag if it's the case
if (is_a_modifier)
{
json._is_a_modifier = true
}
// this child node's style JSON object
return { name, json }
})
})
// convert an array of arrays to a flat array
.reduce(function(array, child_array)
{
return array.concat(child_array);
},
[])
// combine all the child nodes into a single JSON object
.reduce(function(nodes, node)
{
// if style already exists for this child node, extend it
if (nodes[node.name])
{
extend(nodes[node.name], node.json)
}
else
{
nodes[node.name] = node.json
}
return nodes
},
{})
} | [
"function",
"parse_children",
"(",
"lines",
",",
"parent_node_names",
")",
"{",
"lines",
"=",
"filter_lines_for_parsing",
"(",
"lines",
")",
"if",
"(",
"lines",
".",
"length",
"===",
"0",
")",
"{",
"return",
"{",
"}",
"}",
"return",
"split_lines_by_child_nodes",
"(",
"lines",
")",
".",
"map",
"(",
"function",
"(",
"lines",
")",
"{",
"const",
"declaration_line",
"=",
"lines",
".",
"shift",
"(",
")",
"if",
"(",
"declaration_line",
".",
"tabs",
"!==",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"declaration_line",
".",
"tabs",
"}",
"${",
"declaration_line",
".",
"index",
"}",
"${",
"declaration_line",
".",
"original_line",
"}",
"`",
")",
"}",
"const",
"declaration",
"=",
"declaration_line",
".",
"line",
"const",
"names",
"=",
"declaration",
".",
"split",
"(",
"','",
")",
".",
"map",
"(",
"name",
"=>",
"name",
".",
"trim",
"(",
")",
")",
"validate_child_style_class_types",
"(",
"parent_node_names",
",",
"names",
")",
"const",
"style_json",
"=",
"parse_style_class",
"(",
"lines",
",",
"names",
")",
"return",
"names",
".",
"map",
"(",
"function",
"(",
"node_declaration",
")",
"{",
"const",
"{",
"name",
",",
"is_a_modifier",
"}",
"=",
"parse_node_name",
"(",
"node_declaration",
")",
"const",
"json",
"=",
"extend",
"(",
"{",
"}",
",",
"style_json",
")",
"if",
"(",
"is_a_modifier",
")",
"{",
"json",
".",
"_is_a_modifier",
"=",
"true",
"}",
"return",
"{",
"name",
",",
"json",
"}",
"}",
")",
"}",
")",
".",
"reduce",
"(",
"function",
"(",
"array",
",",
"child_array",
")",
"{",
"return",
"array",
".",
"concat",
"(",
"child_array",
")",
";",
"}",
",",
"[",
"]",
")",
".",
"reduce",
"(",
"function",
"(",
"nodes",
",",
"node",
")",
"{",
"if",
"(",
"nodes",
"[",
"node",
".",
"name",
"]",
")",
"{",
"extend",
"(",
"nodes",
"[",
"node",
".",
"name",
"]",
",",
"node",
".",
"json",
")",
"}",
"else",
"{",
"nodes",
"[",
"node",
".",
"name",
"]",
"=",
"node",
".",
"json",
"}",
"return",
"nodes",
"}",
",",
"{",
"}",
")",
"}"
] | parses child nodes' lines of text into the corresponding child node JSON objects | [
"parses",
"child",
"nodes",
"lines",
"of",
"text",
"into",
"the",
"corresponding",
"child",
"node",
"JSON",
"objects"
] | 24d6fc0de74de67ae6c08450d0542a992d388ff3 | https://github.com/catamphetamine/react-styling/blob/24d6fc0de74de67ae6c08450d0542a992d388ff3/source/index.js#L173-L249 | train |
catamphetamine/react-styling | source/index.js | filter_lines_for_parsing | function filter_lines_for_parsing(lines)
{
// filter out blank lines
lines = lines.filter(line => !is_blank(line.line))
lines.forEach(function(line)
{
// remove single line comments
line.line = line.line.replace(/^\s*\/\/.*/, '')
// remove any trailing whitespace
line.line = line.line.trim()
})
return lines
} | javascript | function filter_lines_for_parsing(lines)
{
// filter out blank lines
lines = lines.filter(line => !is_blank(line.line))
lines.forEach(function(line)
{
// remove single line comments
line.line = line.line.replace(/^\s*\/\/.*/, '')
// remove any trailing whitespace
line.line = line.line.trim()
})
return lines
} | [
"function",
"filter_lines_for_parsing",
"(",
"lines",
")",
"{",
"lines",
"=",
"lines",
".",
"filter",
"(",
"line",
"=>",
"!",
"is_blank",
"(",
"line",
".",
"line",
")",
")",
"lines",
".",
"forEach",
"(",
"function",
"(",
"line",
")",
"{",
"line",
".",
"line",
"=",
"line",
".",
"line",
".",
"replace",
"(",
"/",
"^\\s*\\/\\/.*",
"/",
",",
"''",
")",
"line",
".",
"line",
"=",
"line",
".",
"line",
".",
"trim",
"(",
")",
"}",
")",
"return",
"lines",
"}"
] | filters out comments, blank lines, etc | [
"filters",
"out",
"comments",
"blank",
"lines",
"etc"
] | 24d6fc0de74de67ae6c08450d0542a992d388ff3 | https://github.com/catamphetamine/react-styling/blob/24d6fc0de74de67ae6c08450d0542a992d388ff3/source/index.js#L252-L266 | train |
catamphetamine/react-styling | source/index.js | split_lines_by_child_nodes | function split_lines_by_child_nodes(lines)
{
// determine lines with indentation = 0 (child node entry lines)
const node_entry_lines = lines.map((line, index) =>
{
return { tabs: line.tabs, index }
})
.filter(line => line.tabs === 0)
.map(line => line.index)
// deduce corresponding child node ending lines
const node_ending_lines = node_entry_lines.map(line_index => line_index - 1)
node_ending_lines.shift()
node_ending_lines.push(lines.length - 1)
// each child node boundaries in terms of starting line index and ending line index
const from_to = zip(node_entry_lines, node_ending_lines)
// now lines are split by child nodes
return from_to.map(from_to => lines.slice(from_to[0], from_to[1] + 1))
} | javascript | function split_lines_by_child_nodes(lines)
{
// determine lines with indentation = 0 (child node entry lines)
const node_entry_lines = lines.map((line, index) =>
{
return { tabs: line.tabs, index }
})
.filter(line => line.tabs === 0)
.map(line => line.index)
// deduce corresponding child node ending lines
const node_ending_lines = node_entry_lines.map(line_index => line_index - 1)
node_ending_lines.shift()
node_ending_lines.push(lines.length - 1)
// each child node boundaries in terms of starting line index and ending line index
const from_to = zip(node_entry_lines, node_ending_lines)
// now lines are split by child nodes
return from_to.map(from_to => lines.slice(from_to[0], from_to[1] + 1))
} | [
"function",
"split_lines_by_child_nodes",
"(",
"lines",
")",
"{",
"const",
"node_entry_lines",
"=",
"lines",
".",
"map",
"(",
"(",
"line",
",",
"index",
")",
"=>",
"{",
"return",
"{",
"tabs",
":",
"line",
".",
"tabs",
",",
"index",
"}",
"}",
")",
".",
"filter",
"(",
"line",
"=>",
"line",
".",
"tabs",
"===",
"0",
")",
".",
"map",
"(",
"line",
"=>",
"line",
".",
"index",
")",
"const",
"node_ending_lines",
"=",
"node_entry_lines",
".",
"map",
"(",
"line_index",
"=>",
"line_index",
"-",
"1",
")",
"node_ending_lines",
".",
"shift",
"(",
")",
"node_ending_lines",
".",
"push",
"(",
"lines",
".",
"length",
"-",
"1",
")",
"const",
"from_to",
"=",
"zip",
"(",
"node_entry_lines",
",",
"node_ending_lines",
")",
"return",
"from_to",
".",
"map",
"(",
"from_to",
"=>",
"lines",
".",
"slice",
"(",
"from_to",
"[",
"0",
"]",
",",
"from_to",
"[",
"1",
"]",
"+",
"1",
")",
")",
"}"
] | takes the whole lines array and splits it by its top-tier child nodes | [
"takes",
"the",
"whole",
"lines",
"array",
"and",
"splits",
"it",
"by",
"its",
"top",
"-",
"tier",
"child",
"nodes"
] | 24d6fc0de74de67ae6c08450d0542a992d388ff3 | https://github.com/catamphetamine/react-styling/blob/24d6fc0de74de67ae6c08450d0542a992d388ff3/source/index.js#L269-L289 | train |
catamphetamine/react-styling | source/index.js | expand_modifier_style_classes | function expand_modifier_style_classes(node)
{
const style = get_node_style(node)
const pseudo_classes_and_media_queries_and_keyframes = get_node_pseudo_classes_and_media_queries_and_keyframes(node)
const modifiers = Object.keys(node)
// get all modifier style class nodes
.filter(name => typeof(node[name]) === 'object' && node[name]._is_a_modifier)
// for each modifier style class node
modifiers.forEach(function(name)
{
// // delete the modifier flags
// delete node[name]._is_a_modifier
// include parent node's styles and pseudo-classes into the modifier style class node
node[name] = extend({}, style, pseudo_classes_and_media_queries_and_keyframes, node[name])
// expand descendant style class nodes of this modifier
expand_modified_subtree(node, node[name])
})
// for each modifier style class node
modifiers.forEach(function(name)
{
// delete the modifier flags
delete node[name]._is_a_modifier
})
// recurse
Object.keys(node)
// get all style class nodes
.filter(name => typeof(node[name]) === 'object')
// for each style class node
.forEach(function(name)
{
// recurse
expand_modifier_style_classes(node[name])
})
return node
} | javascript | function expand_modifier_style_classes(node)
{
const style = get_node_style(node)
const pseudo_classes_and_media_queries_and_keyframes = get_node_pseudo_classes_and_media_queries_and_keyframes(node)
const modifiers = Object.keys(node)
// get all modifier style class nodes
.filter(name => typeof(node[name]) === 'object' && node[name]._is_a_modifier)
// for each modifier style class node
modifiers.forEach(function(name)
{
// // delete the modifier flags
// delete node[name]._is_a_modifier
// include parent node's styles and pseudo-classes into the modifier style class node
node[name] = extend({}, style, pseudo_classes_and_media_queries_and_keyframes, node[name])
// expand descendant style class nodes of this modifier
expand_modified_subtree(node, node[name])
})
// for each modifier style class node
modifiers.forEach(function(name)
{
// delete the modifier flags
delete node[name]._is_a_modifier
})
// recurse
Object.keys(node)
// get all style class nodes
.filter(name => typeof(node[name]) === 'object')
// for each style class node
.forEach(function(name)
{
// recurse
expand_modifier_style_classes(node[name])
})
return node
} | [
"function",
"expand_modifier_style_classes",
"(",
"node",
")",
"{",
"const",
"style",
"=",
"get_node_style",
"(",
"node",
")",
"const",
"pseudo_classes_and_media_queries_and_keyframes",
"=",
"get_node_pseudo_classes_and_media_queries_and_keyframes",
"(",
"node",
")",
"const",
"modifiers",
"=",
"Object",
".",
"keys",
"(",
"node",
")",
".",
"filter",
"(",
"name",
"=>",
"typeof",
"(",
"node",
"[",
"name",
"]",
")",
"===",
"'object'",
"&&",
"node",
"[",
"name",
"]",
".",
"_is_a_modifier",
")",
"modifiers",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"node",
"[",
"name",
"]",
"=",
"extend",
"(",
"{",
"}",
",",
"style",
",",
"pseudo_classes_and_media_queries_and_keyframes",
",",
"node",
"[",
"name",
"]",
")",
"expand_modified_subtree",
"(",
"node",
",",
"node",
"[",
"name",
"]",
")",
"}",
")",
"modifiers",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"delete",
"node",
"[",
"name",
"]",
".",
"_is_a_modifier",
"}",
")",
"Object",
".",
"keys",
"(",
"node",
")",
".",
"filter",
"(",
"name",
"=>",
"typeof",
"(",
"node",
"[",
"name",
"]",
")",
"===",
"'object'",
")",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"expand_modifier_style_classes",
"(",
"node",
"[",
"name",
"]",
")",
"}",
")",
"return",
"node",
"}"
] | expand modifier style classes | [
"expand",
"modifier",
"style",
"classes"
] | 24d6fc0de74de67ae6c08450d0542a992d388ff3 | https://github.com/catamphetamine/react-styling/blob/24d6fc0de74de67ae6c08450d0542a992d388ff3/source/index.js#L292-L333 | train |
catamphetamine/react-styling | source/index.js | get_node_style | function get_node_style(node)
{
return Object.keys(node)
// get all CSS styles of this style class node
.filter(property => typeof(node[property]) !== 'object')
// for each CSS style of this style class node
.reduce(function(style, style_property)
{
style[style_property] = node[style_property]
return style
},
{})
} | javascript | function get_node_style(node)
{
return Object.keys(node)
// get all CSS styles of this style class node
.filter(property => typeof(node[property]) !== 'object')
// for each CSS style of this style class node
.reduce(function(style, style_property)
{
style[style_property] = node[style_property]
return style
},
{})
} | [
"function",
"get_node_style",
"(",
"node",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"node",
")",
".",
"filter",
"(",
"property",
"=>",
"typeof",
"(",
"node",
"[",
"property",
"]",
")",
"!==",
"'object'",
")",
".",
"reduce",
"(",
"function",
"(",
"style",
",",
"style_property",
")",
"{",
"style",
"[",
"style_property",
"]",
"=",
"node",
"[",
"style_property",
"]",
"return",
"style",
"}",
",",
"{",
"}",
")",
"}"
] | extracts root css styles of this style class node | [
"extracts",
"root",
"css",
"styles",
"of",
"this",
"style",
"class",
"node"
] | 24d6fc0de74de67ae6c08450d0542a992d388ff3 | https://github.com/catamphetamine/react-styling/blob/24d6fc0de74de67ae6c08450d0542a992d388ff3/source/index.js#L336-L348 | train |
catamphetamine/react-styling | source/index.js | get_node_pseudo_classes_and_media_queries_and_keyframes | function get_node_pseudo_classes_and_media_queries_and_keyframes(node)
{
return Object.keys(node)
// get all child style classes this style class node,
// which aren't modifiers and are a pseudoclass or a media query or keyframes
.filter(property => typeof(node[property]) === 'object'
&& (is_pseudo_class(property) || is_media_query(property) || is_keyframes(property))
&& !node[property]._is_a_modifier)
// for each child style class of this style class node
.reduce(function(pseudo_classes_and_media_queries_and_keyframes, name)
{
pseudo_classes_and_media_queries_and_keyframes[name] = node[name]
return pseudo_classes_and_media_queries_and_keyframes
},
{})
} | javascript | function get_node_pseudo_classes_and_media_queries_and_keyframes(node)
{
return Object.keys(node)
// get all child style classes this style class node,
// which aren't modifiers and are a pseudoclass or a media query or keyframes
.filter(property => typeof(node[property]) === 'object'
&& (is_pseudo_class(property) || is_media_query(property) || is_keyframes(property))
&& !node[property]._is_a_modifier)
// for each child style class of this style class node
.reduce(function(pseudo_classes_and_media_queries_and_keyframes, name)
{
pseudo_classes_and_media_queries_and_keyframes[name] = node[name]
return pseudo_classes_and_media_queries_and_keyframes
},
{})
} | [
"function",
"get_node_pseudo_classes_and_media_queries_and_keyframes",
"(",
"node",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"node",
")",
".",
"filter",
"(",
"property",
"=>",
"typeof",
"(",
"node",
"[",
"property",
"]",
")",
"===",
"'object'",
"&&",
"(",
"is_pseudo_class",
"(",
"property",
")",
"||",
"is_media_query",
"(",
"property",
")",
"||",
"is_keyframes",
"(",
"property",
")",
")",
"&&",
"!",
"node",
"[",
"property",
"]",
".",
"_is_a_modifier",
")",
".",
"reduce",
"(",
"function",
"(",
"pseudo_classes_and_media_queries_and_keyframes",
",",
"name",
")",
"{",
"pseudo_classes_and_media_queries_and_keyframes",
"[",
"name",
"]",
"=",
"node",
"[",
"name",
"]",
"return",
"pseudo_classes_and_media_queries_and_keyframes",
"}",
",",
"{",
"}",
")",
"}"
] | extracts root pseudo-classes and media queries of this style class node | [
"extracts",
"root",
"pseudo",
"-",
"classes",
"and",
"media",
"queries",
"of",
"this",
"style",
"class",
"node"
] | 24d6fc0de74de67ae6c08450d0542a992d388ff3 | https://github.com/catamphetamine/react-styling/blob/24d6fc0de74de67ae6c08450d0542a992d388ff3/source/index.js#L351-L366 | train |
catamphetamine/react-styling | source/index.js | validate_child_style_class_types | function validate_child_style_class_types(parent_node_names, names)
{
for (let parent of parent_node_names)
{
// if it's a pseudoclass, it can't contain any style classes
if (is_pseudo_class(parent) && not_empty(names))
{
throw new Error(`A style class declaration "${names[0]}" found inside a pseudoclass "${parent}". Pseudoclasses (:hover, etc) can't contain child style classes.`)
}
// if it's a media query style class, it must contain only pseudoclasses
if (is_media_query(parent))
{
const non_pseudoclass = names.filter(x => !is_pseudo_class(x))[0]
if (non_pseudoclass)
{
throw new Error(`A non-pseudoclass "${non_pseudoclass}" found inside a media query style class "${parent}". Media query style classes can only contain pseudoclasses (:hover, etc).`)
}
}
// if it's a keyframes style class, it must contain only keyframe selectors
if (is_keyframes(parent)) {
const non_keyframe_selector = names.filter(x => !is_keyframe_selector(x))[0]
if (non_keyframe_selector)
{
throw new Error(`A non-keyframe-selector "${non_keyframe_selector}" found inside a keyframes style class "${parent}". Keyframes style classes can only contain keyframe selectors (from, 100%, etc).`);
}
}
}
} | javascript | function validate_child_style_class_types(parent_node_names, names)
{
for (let parent of parent_node_names)
{
// if it's a pseudoclass, it can't contain any style classes
if (is_pseudo_class(parent) && not_empty(names))
{
throw new Error(`A style class declaration "${names[0]}" found inside a pseudoclass "${parent}". Pseudoclasses (:hover, etc) can't contain child style classes.`)
}
// if it's a media query style class, it must contain only pseudoclasses
if (is_media_query(parent))
{
const non_pseudoclass = names.filter(x => !is_pseudo_class(x))[0]
if (non_pseudoclass)
{
throw new Error(`A non-pseudoclass "${non_pseudoclass}" found inside a media query style class "${parent}". Media query style classes can only contain pseudoclasses (:hover, etc).`)
}
}
// if it's a keyframes style class, it must contain only keyframe selectors
if (is_keyframes(parent)) {
const non_keyframe_selector = names.filter(x => !is_keyframe_selector(x))[0]
if (non_keyframe_selector)
{
throw new Error(`A non-keyframe-selector "${non_keyframe_selector}" found inside a keyframes style class "${parent}". Keyframes style classes can only contain keyframe selectors (from, 100%, etc).`);
}
}
}
} | [
"function",
"validate_child_style_class_types",
"(",
"parent_node_names",
",",
"names",
")",
"{",
"for",
"(",
"let",
"parent",
"of",
"parent_node_names",
")",
"{",
"if",
"(",
"is_pseudo_class",
"(",
"parent",
")",
"&&",
"not_empty",
"(",
"names",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"names",
"[",
"0",
"]",
"}",
"${",
"parent",
"}",
"`",
")",
"}",
"if",
"(",
"is_media_query",
"(",
"parent",
")",
")",
"{",
"const",
"non_pseudoclass",
"=",
"names",
".",
"filter",
"(",
"x",
"=>",
"!",
"is_pseudo_class",
"(",
"x",
")",
")",
"[",
"0",
"]",
"if",
"(",
"non_pseudoclass",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"non_pseudoclass",
"}",
"${",
"parent",
"}",
"`",
")",
"}",
"}",
"if",
"(",
"is_keyframes",
"(",
"parent",
")",
")",
"{",
"const",
"non_keyframe_selector",
"=",
"names",
".",
"filter",
"(",
"x",
"=>",
"!",
"is_keyframe_selector",
"(",
"x",
")",
")",
"[",
"0",
"]",
"if",
"(",
"non_keyframe_selector",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"non_keyframe_selector",
"}",
"${",
"parent",
"}",
"`",
")",
";",
"}",
"}",
"}",
"}"
] | style class nesting validation | [
"style",
"class",
"nesting",
"validation"
] | 24d6fc0de74de67ae6c08450d0542a992d388ff3 | https://github.com/catamphetamine/react-styling/blob/24d6fc0de74de67ae6c08450d0542a992d388ff3/source/index.js#L428-L459 | train |
catamphetamine/react-styling | source/index.js | parse_style_class | function parse_style_class(lines, node_names)
{
// separate style lines from children lines
const { style_lines, children_lines } = split_into_style_lines_and_children_lines(lines)
// convert style lines info to just text lines
const styles = style_lines.map(line => line.line)
// using this child node's (or these child nodes') style lines
// and this child node's (or these child nodes') child nodes' lines,
// generate this child node's (or these child nodes') style JSON object
// (this is gonna be a recursion)
return parse_node_json(styles, children_lines, node_names)
} | javascript | function parse_style_class(lines, node_names)
{
// separate style lines from children lines
const { style_lines, children_lines } = split_into_style_lines_and_children_lines(lines)
// convert style lines info to just text lines
const styles = style_lines.map(line => line.line)
// using this child node's (or these child nodes') style lines
// and this child node's (or these child nodes') child nodes' lines,
// generate this child node's (or these child nodes') style JSON object
// (this is gonna be a recursion)
return parse_node_json(styles, children_lines, node_names)
} | [
"function",
"parse_style_class",
"(",
"lines",
",",
"node_names",
")",
"{",
"const",
"{",
"style_lines",
",",
"children_lines",
"}",
"=",
"split_into_style_lines_and_children_lines",
"(",
"lines",
")",
"const",
"styles",
"=",
"style_lines",
".",
"map",
"(",
"line",
"=>",
"line",
".",
"line",
")",
"return",
"parse_node_json",
"(",
"styles",
",",
"children_lines",
",",
"node_names",
")",
"}"
] | parse CSS style class | [
"parse",
"CSS",
"style",
"class"
] | 24d6fc0de74de67ae6c08450d0542a992d388ff3 | https://github.com/catamphetamine/react-styling/blob/24d6fc0de74de67ae6c08450d0542a992d388ff3/source/index.js#L462-L475 | train |
catamphetamine/react-styling | source/flat.js | move_up | function move_up(object, upside, new_name)
{
let prefix
if (upside)
{
upside[new_name] = object
prefix = `${new_name}_`
}
else
{
upside = object
prefix = ''
}
for (let key of Object.keys(object))
{
const child_object = object[key]
if (is_object(child_object) && !is_pseudo_class(key) && !is_media_query(key))
{
delete object[key]
move_up(child_object, upside, `${prefix}${key}`)
}
}
} | javascript | function move_up(object, upside, new_name)
{
let prefix
if (upside)
{
upside[new_name] = object
prefix = `${new_name}_`
}
else
{
upside = object
prefix = ''
}
for (let key of Object.keys(object))
{
const child_object = object[key]
if (is_object(child_object) && !is_pseudo_class(key) && !is_media_query(key))
{
delete object[key]
move_up(child_object, upside, `${prefix}${key}`)
}
}
} | [
"function",
"move_up",
"(",
"object",
",",
"upside",
",",
"new_name",
")",
"{",
"let",
"prefix",
"if",
"(",
"upside",
")",
"{",
"upside",
"[",
"new_name",
"]",
"=",
"object",
"prefix",
"=",
"`",
"${",
"new_name",
"}",
"`",
"}",
"else",
"{",
"upside",
"=",
"object",
"prefix",
"=",
"''",
"}",
"for",
"(",
"let",
"key",
"of",
"Object",
".",
"keys",
"(",
"object",
")",
")",
"{",
"const",
"child_object",
"=",
"object",
"[",
"key",
"]",
"if",
"(",
"is_object",
"(",
"child_object",
")",
"&&",
"!",
"is_pseudo_class",
"(",
"key",
")",
"&&",
"!",
"is_media_query",
"(",
"key",
")",
")",
"{",
"delete",
"object",
"[",
"key",
"]",
"move_up",
"(",
"child_object",
",",
"upside",
",",
"`",
"${",
"prefix",
"}",
"${",
"key",
"}",
"`",
")",
"}",
"}",
"}"
] | moves child style classes to the surface of the style class tree prefixing them accordingly | [
"moves",
"child",
"style",
"classes",
"to",
"the",
"surface",
"of",
"the",
"style",
"class",
"tree",
"prefixing",
"them",
"accordingly"
] | 24d6fc0de74de67ae6c08450d0542a992d388ff3 | https://github.com/catamphetamine/react-styling/blob/24d6fc0de74de67ae6c08450d0542a992d388ff3/source/flat.js#L19-L44 | train |
joyent/node-sdc-clients | lib/imgapi.js | SigningError | function SigningError(cause) {
this.code = 'SigningError';
assert.optionalObject(cause);
var msg = 'error signing request';
var args = (cause ? [cause, msg] : [msg]);
WError.apply(this, args);
} | javascript | function SigningError(cause) {
this.code = 'SigningError';
assert.optionalObject(cause);
var msg = 'error signing request';
var args = (cause ? [cause, msg] : [msg]);
WError.apply(this, args);
} | [
"function",
"SigningError",
"(",
"cause",
")",
"{",
"this",
".",
"code",
"=",
"'SigningError'",
";",
"assert",
".",
"optionalObject",
"(",
"cause",
")",
";",
"var",
"msg",
"=",
"'error signing request'",
";",
"var",
"args",
"=",
"(",
"cause",
"?",
"[",
"cause",
",",
"msg",
"]",
":",
"[",
"msg",
"]",
")",
";",
"WError",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}"
] | An error signing a request. | [
"An",
"error",
"signing",
"a",
"request",
"."
] | 5dd2d17e8ab8e2eccb49b3fa3384cbf2f25562eb | https://github.com/joyent/node-sdc-clients/blob/5dd2d17e8ab8e2eccb49b3fa3384cbf2f25562eb/lib/imgapi.js#L108-L114 | train |
joyent/node-sdc-clients | lib/vmapi.js | listAllVms | function listAllVms(cb) {
var limit = undefined;
var offset = params.offset;
var vms = [];
var stop = false;
async.whilst(
function testAllVmsFetched() {
return !stop;
},
listVms,
function doneFetching(fetchErr) {
return cb(fetchErr, vms);
});
function listVms(whilstNext) {
// These options are passed once they are set for the first time
// or they are passed by the client calling listImages()
if (offset) {
params.offset += offset;
} else {
params.offset = 0;
}
if (limit) {
params.limit = limit;
}
self.get(reqOpts, function (listErr, someVms) {
if (listErr) {
stop = true;
return whilstNext(listErr);
}
if (!limit) {
limit = someVms.length;
}
if (!offset) {
offset = someVms.length;
}
if (someVms.length < limit) {
stop = true;
}
// We hit this when we either reached an empty page of
// results or an empty first result
if (!someVms.length) {
stop = true;
return whilstNext();
}
vms = vms.concat(someVms);
return whilstNext();
});
}
} | javascript | function listAllVms(cb) {
var limit = undefined;
var offset = params.offset;
var vms = [];
var stop = false;
async.whilst(
function testAllVmsFetched() {
return !stop;
},
listVms,
function doneFetching(fetchErr) {
return cb(fetchErr, vms);
});
function listVms(whilstNext) {
// These options are passed once they are set for the first time
// or they are passed by the client calling listImages()
if (offset) {
params.offset += offset;
} else {
params.offset = 0;
}
if (limit) {
params.limit = limit;
}
self.get(reqOpts, function (listErr, someVms) {
if (listErr) {
stop = true;
return whilstNext(listErr);
}
if (!limit) {
limit = someVms.length;
}
if (!offset) {
offset = someVms.length;
}
if (someVms.length < limit) {
stop = true;
}
// We hit this when we either reached an empty page of
// results or an empty first result
if (!someVms.length) {
stop = true;
return whilstNext();
}
vms = vms.concat(someVms);
return whilstNext();
});
}
} | [
"function",
"listAllVms",
"(",
"cb",
")",
"{",
"var",
"limit",
"=",
"undefined",
";",
"var",
"offset",
"=",
"params",
".",
"offset",
";",
"var",
"vms",
"=",
"[",
"]",
";",
"var",
"stop",
"=",
"false",
";",
"async",
".",
"whilst",
"(",
"function",
"testAllVmsFetched",
"(",
")",
"{",
"return",
"!",
"stop",
";",
"}",
",",
"listVms",
",",
"function",
"doneFetching",
"(",
"fetchErr",
")",
"{",
"return",
"cb",
"(",
"fetchErr",
",",
"vms",
")",
";",
"}",
")",
";",
"function",
"listVms",
"(",
"whilstNext",
")",
"{",
"if",
"(",
"offset",
")",
"{",
"params",
".",
"offset",
"+=",
"offset",
";",
"}",
"else",
"{",
"params",
".",
"offset",
"=",
"0",
";",
"}",
"if",
"(",
"limit",
")",
"{",
"params",
".",
"limit",
"=",
"limit",
";",
"}",
"self",
".",
"get",
"(",
"reqOpts",
",",
"function",
"(",
"listErr",
",",
"someVms",
")",
"{",
"if",
"(",
"listErr",
")",
"{",
"stop",
"=",
"true",
";",
"return",
"whilstNext",
"(",
"listErr",
")",
";",
"}",
"if",
"(",
"!",
"limit",
")",
"{",
"limit",
"=",
"someVms",
".",
"length",
";",
"}",
"if",
"(",
"!",
"offset",
")",
"{",
"offset",
"=",
"someVms",
".",
"length",
";",
"}",
"if",
"(",
"someVms",
".",
"length",
"<",
"limit",
")",
"{",
"stop",
"=",
"true",
";",
"}",
"if",
"(",
"!",
"someVms",
".",
"length",
")",
"{",
"stop",
"=",
"true",
";",
"return",
"whilstNext",
"(",
")",
";",
"}",
"vms",
"=",
"vms",
".",
"concat",
"(",
"someVms",
")",
";",
"return",
"whilstNext",
"(",
")",
";",
"}",
")",
";",
"}",
"}"
] | This function will execute at least 2 queries when it is not known how the remote VMAPI is returning the collection. If no limit is set, then listVms would receive all VMs on the first call and then perform a second one to discover that all items have been returned. When limit is undefined, listVms will get someVms.length VMs at a time | [
"This",
"function",
"will",
"execute",
"at",
"least",
"2",
"queries",
"when",
"it",
"is",
"not",
"known",
"how",
"the",
"remote",
"VMAPI",
"is",
"returning",
"the",
"collection",
".",
"If",
"no",
"limit",
"is",
"set",
"then",
"listVms",
"would",
"receive",
"all",
"VMs",
"on",
"the",
"first",
"call",
"and",
"then",
"perform",
"a",
"second",
"one",
"to",
"discover",
"that",
"all",
"items",
"have",
"been",
"returned",
".",
"When",
"limit",
"is",
"undefined",
"listVms",
"will",
"get",
"someVms",
".",
"length",
"VMs",
"at",
"a",
"time"
] | 5dd2d17e8ab8e2eccb49b3fa3384cbf2f25562eb | https://github.com/joyent/node-sdc-clients/blob/5dd2d17e8ab8e2eccb49b3fa3384cbf2f25562eb/lib/vmapi.js#L193-L248 | train |
joyent/node-sdc-clients | lib/sapi.js | updateApplication | function updateApplication(uuid, opts, callback) {
assert.string(uuid, 'uuid');
assert.object(opts, 'opts');
return (this.put(sprintf('/applications/%s', uuid), opts, callback));
} | javascript | function updateApplication(uuid, opts, callback) {
assert.string(uuid, 'uuid');
assert.object(opts, 'opts');
return (this.put(sprintf('/applications/%s', uuid), opts, callback));
} | [
"function",
"updateApplication",
"(",
"uuid",
",",
"opts",
",",
"callback",
")",
"{",
"assert",
".",
"string",
"(",
"uuid",
",",
"'uuid'",
")",
";",
"assert",
".",
"object",
"(",
"opts",
",",
"'opts'",
")",
";",
"return",
"(",
"this",
".",
"put",
"(",
"sprintf",
"(",
"'/applications/%s'",
",",
"uuid",
")",
",",
"opts",
",",
"callback",
")",
")",
";",
"}"
] | Updates an application
@param {String} uuid: the UUID of the applications.
@param {String} opts: new attributes
@param {Function} callback: of the form f(err, app). | [
"Updates",
"an",
"application"
] | 5dd2d17e8ab8e2eccb49b3fa3384cbf2f25562eb | https://github.com/joyent/node-sdc-clients/blob/5dd2d17e8ab8e2eccb49b3fa3384cbf2f25562eb/lib/sapi.js#L127-L132 | train |
joyent/node-sdc-clients | lib/sapi.js | createInstanceAsync | function createInstanceAsync(service_uuid, opts, callback) {
assert.string(service_uuid, 'service_uuid');
if (typeof (opts) === 'function') {
callback = opts;
opts = {};
}
assert.object(opts, 'opts');
assert.func(callback, 'callback');
opts.service_uuid = service_uuid;
return (this.post('/instances?async=true', opts, callback));
} | javascript | function createInstanceAsync(service_uuid, opts, callback) {
assert.string(service_uuid, 'service_uuid');
if (typeof (opts) === 'function') {
callback = opts;
opts = {};
}
assert.object(opts, 'opts');
assert.func(callback, 'callback');
opts.service_uuid = service_uuid;
return (this.post('/instances?async=true', opts, callback));
} | [
"function",
"createInstanceAsync",
"(",
"service_uuid",
",",
"opts",
",",
"callback",
")",
"{",
"assert",
".",
"string",
"(",
"service_uuid",
",",
"'service_uuid'",
")",
";",
"if",
"(",
"typeof",
"(",
"opts",
")",
"===",
"'function'",
")",
"{",
"callback",
"=",
"opts",
";",
"opts",
"=",
"{",
"}",
";",
"}",
"assert",
".",
"object",
"(",
"opts",
",",
"'opts'",
")",
";",
"assert",
".",
"func",
"(",
"callback",
",",
"'callback'",
")",
";",
"opts",
".",
"service_uuid",
"=",
"service_uuid",
";",
"return",
"(",
"this",
".",
"post",
"(",
"'/instances?async=true'",
",",
"opts",
",",
"callback",
")",
")",
";",
"}"
] | Create an instance asynchronously
@param {String} service_uuid: The UUID of the service for which to create
an instance.
@param {String} opts: Optional attributes per
<https://mo.joyent.com/docs/sapi/master/#CreateInstance>
@param {Function} callback: of the form f(err, instance). | [
"Create",
"an",
"instance",
"asynchronously"
] | 5dd2d17e8ab8e2eccb49b3fa3384cbf2f25562eb | https://github.com/joyent/node-sdc-clients/blob/5dd2d17e8ab8e2eccb49b3fa3384cbf2f25562eb/lib/sapi.js#L277-L289 | train |
joyent/node-sdc-clients | lib/sapi.js | listInstances | function listInstances(search_opts, callback) {
if (arguments.length === 1) {
callback = search_opts;
search_opts = {};
}
var uri = '/instances?' + qs.stringify(search_opts);
return (this.get(uri, callback));
} | javascript | function listInstances(search_opts, callback) {
if (arguments.length === 1) {
callback = search_opts;
search_opts = {};
}
var uri = '/instances?' + qs.stringify(search_opts);
return (this.get(uri, callback));
} | [
"function",
"listInstances",
"(",
"search_opts",
",",
"callback",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
")",
"{",
"callback",
"=",
"search_opts",
";",
"search_opts",
"=",
"{",
"}",
";",
"}",
"var",
"uri",
"=",
"'/instances?'",
"+",
"qs",
".",
"stringify",
"(",
"search_opts",
")",
";",
"return",
"(",
"this",
".",
"get",
"(",
"uri",
",",
"callback",
")",
")",
";",
"}"
] | Lists all instances
@param {Function} callback: of the form f(err, instances). | [
"Lists",
"all",
"instances"
] | 5dd2d17e8ab8e2eccb49b3fa3384cbf2f25562eb | https://github.com/joyent/node-sdc-clients/blob/5dd2d17e8ab8e2eccb49b3fa3384cbf2f25562eb/lib/sapi.js#L299-L307 | train |
joyent/node-sdc-clients | lib/sapi.js | reprovisionInstance | function reprovisionInstance(uuid, image_uuid, callback) {
assert.string(uuid, 'uuid');
assert.string(image_uuid, 'image_uuid');
var opts = {};
opts.image_uuid = image_uuid;
return (this.put(sprintf('/instances/%s/upgrade', uuid), opts, callback));
} | javascript | function reprovisionInstance(uuid, image_uuid, callback) {
assert.string(uuid, 'uuid');
assert.string(image_uuid, 'image_uuid');
var opts = {};
opts.image_uuid = image_uuid;
return (this.put(sprintf('/instances/%s/upgrade', uuid), opts, callback));
} | [
"function",
"reprovisionInstance",
"(",
"uuid",
",",
"image_uuid",
",",
"callback",
")",
"{",
"assert",
".",
"string",
"(",
"uuid",
",",
"'uuid'",
")",
";",
"assert",
".",
"string",
"(",
"image_uuid",
",",
"'image_uuid'",
")",
";",
"var",
"opts",
"=",
"{",
"}",
";",
"opts",
".",
"image_uuid",
"=",
"image_uuid",
";",
"return",
"(",
"this",
".",
"put",
"(",
"sprintf",
"(",
"'/instances/%s/upgrade'",
",",
"uuid",
")",
",",
"opts",
",",
"callback",
")",
")",
";",
"}"
] | Reprovision an instance
@param {String} uuid: the UUID of the instances.
@param {String} image_uuid: new attributes
@param {Function} callback: of the form f(err, app). | [
"Reprovision",
"an",
"instance"
] | 5dd2d17e8ab8e2eccb49b3fa3384cbf2f25562eb | https://github.com/joyent/node-sdc-clients/blob/5dd2d17e8ab8e2eccb49b3fa3384cbf2f25562eb/lib/sapi.js#L331-L339 | train |
AgronKabashi/jspicl | lib/jspicl.js | prettify | function prettify (luaCode) {
const lines = luaCode
.split("\n")
.map(line => line.trim());
const { code } = lines.reduce((result, line) => {
const { code, indentation } = result;
let currentIndentation = indentation;
let nextLineIndentation = indentation;
if (indentIncrease.some(entry => entry(line))) {
nextLineIndentation++;
}
if (indentDecrease.some(entry => entry(line))) {
currentIndentation--;
nextLineIndentation--;
}
code.push(line && line.padStart(line.length + currentIndentation * 2) || line);
return {
code,
indentation: Math.max(0, nextLineIndentation)
};
}, {
code: [],
indentation: 0
});
return code.join("\n");
} | javascript | function prettify (luaCode) {
const lines = luaCode
.split("\n")
.map(line => line.trim());
const { code } = lines.reduce((result, line) => {
const { code, indentation } = result;
let currentIndentation = indentation;
let nextLineIndentation = indentation;
if (indentIncrease.some(entry => entry(line))) {
nextLineIndentation++;
}
if (indentDecrease.some(entry => entry(line))) {
currentIndentation--;
nextLineIndentation--;
}
code.push(line && line.padStart(line.length + currentIndentation * 2) || line);
return {
code,
indentation: Math.max(0, nextLineIndentation)
};
}, {
code: [],
indentation: 0
});
return code.join("\n");
} | [
"function",
"prettify",
"(",
"luaCode",
")",
"{",
"const",
"lines",
"=",
"luaCode",
".",
"split",
"(",
"\"\\n\"",
")",
".",
"\\n",
"map",
";",
"(",
"line",
"=>",
"line",
".",
"trim",
"(",
")",
")",
"const",
"{",
"code",
"}",
"=",
"lines",
".",
"reduce",
"(",
"(",
"result",
",",
"line",
")",
"=>",
"{",
"const",
"{",
"code",
",",
"indentation",
"}",
"=",
"result",
";",
"let",
"currentIndentation",
"=",
"indentation",
";",
"let",
"nextLineIndentation",
"=",
"indentation",
";",
"if",
"(",
"indentIncrease",
".",
"some",
"(",
"entry",
"=>",
"entry",
"(",
"line",
")",
")",
")",
"{",
"nextLineIndentation",
"++",
";",
"}",
"if",
"(",
"indentDecrease",
".",
"some",
"(",
"entry",
"=>",
"entry",
"(",
"line",
")",
")",
")",
"{",
"currentIndentation",
"--",
";",
"nextLineIndentation",
"--",
";",
"}",
"code",
".",
"push",
"(",
"line",
"&&",
"line",
".",
"padStart",
"(",
"line",
".",
"length",
"+",
"currentIndentation",
"*",
"2",
")",
"||",
"line",
")",
";",
"return",
"{",
"code",
",",
"indentation",
":",
"Math",
".",
"max",
"(",
"0",
",",
"nextLineIndentation",
")",
"}",
";",
"}",
",",
"{",
"code",
":",
"[",
"]",
",",
"indentation",
":",
"0",
"}",
")",
";",
"}"
] | Fixes code indentation
@param {string} luaCode Original lua code
@returns {string} Formatted code | [
"Fixes",
"code",
"indentation"
] | 13380add182b0189597d2ec318403f81129b676b | https://github.com/AgronKabashi/jspicl/blob/13380add182b0189597d2ec318403f81129b676b/lib/jspicl.js#L308-L339 | train |
lmgonzalves/jelly | js/jellyfish.js | buildOptions | function buildOptions(i) {
var index = (i + 1);
var isCurrent = i === current;
// Options for each text, arrow and image, using the base options and the index
var text = extend({}, optionsText, {paths: '#jelly-text-' + index + ' path'});
var arrow = extend({}, optionsArrow, {paths: '#jelly-arrow-' + index});
var image = extend({}, isCurrent ? optionsImage : optionsCircle, {image: 'img/image-' + index + '.jpg'});
// If not the current item, set circle in the position defined, hide text, and hide arrow
if (!isCurrent) {
extend(image, circlePositions[i]);
extend(text, {hidden: true});
extend(arrow, {hidden: true});
}
// Push all of these to the options array
options.push(text);
options.push(arrow);
options.push(image);
} | javascript | function buildOptions(i) {
var index = (i + 1);
var isCurrent = i === current;
// Options for each text, arrow and image, using the base options and the index
var text = extend({}, optionsText, {paths: '#jelly-text-' + index + ' path'});
var arrow = extend({}, optionsArrow, {paths: '#jelly-arrow-' + index});
var image = extend({}, isCurrent ? optionsImage : optionsCircle, {image: 'img/image-' + index + '.jpg'});
// If not the current item, set circle in the position defined, hide text, and hide arrow
if (!isCurrent) {
extend(image, circlePositions[i]);
extend(text, {hidden: true});
extend(arrow, {hidden: true});
}
// Push all of these to the options array
options.push(text);
options.push(arrow);
options.push(image);
} | [
"function",
"buildOptions",
"(",
"i",
")",
"{",
"var",
"index",
"=",
"(",
"i",
"+",
"1",
")",
";",
"var",
"isCurrent",
"=",
"i",
"===",
"current",
";",
"var",
"text",
"=",
"extend",
"(",
"{",
"}",
",",
"optionsText",
",",
"{",
"paths",
":",
"'#jelly-text-'",
"+",
"index",
"+",
"' path'",
"}",
")",
";",
"var",
"arrow",
"=",
"extend",
"(",
"{",
"}",
",",
"optionsArrow",
",",
"{",
"paths",
":",
"'#jelly-arrow-'",
"+",
"index",
"}",
")",
";",
"var",
"image",
"=",
"extend",
"(",
"{",
"}",
",",
"isCurrent",
"?",
"optionsImage",
":",
"optionsCircle",
",",
"{",
"image",
":",
"'img/image-'",
"+",
"index",
"+",
"'.jpg'",
"}",
")",
";",
"if",
"(",
"!",
"isCurrent",
")",
"{",
"extend",
"(",
"image",
",",
"circlePositions",
"[",
"i",
"]",
")",
";",
"extend",
"(",
"text",
",",
"{",
"hidden",
":",
"true",
"}",
")",
";",
"extend",
"(",
"arrow",
",",
"{",
"hidden",
":",
"true",
"}",
")",
";",
"}",
"options",
".",
"push",
"(",
"text",
")",
";",
"options",
".",
"push",
"(",
"arrow",
")",
";",
"options",
".",
"push",
"(",
"image",
")",
";",
"}"
] | Function to build the options for an specific item | [
"Function",
"to",
"build",
"the",
"options",
"for",
"an",
"specific",
"item"
] | cca6a02ed8365f30c8d1be82e7e8fbef6e257c35 | https://github.com/lmgonzalves/jelly/blob/cca6a02ed8365f30c8d1be82e7e8fbef6e257c35/js/jellyfish.js#L78-L98 | train |
IndigoUnited/js-dejavu | dist/node/loose/Class.js | applyBinds | function applyBinds(fns, instance) {
var i,
current;
for (i = fns.length - 1; i >= 0; i -= 1) {
current = instance[fns[i]];
instance[fns[i]] = bind(current, instance);
}
} | javascript | function applyBinds(fns, instance) {
var i,
current;
for (i = fns.length - 1; i >= 0; i -= 1) {
current = instance[fns[i]];
instance[fns[i]] = bind(current, instance);
}
} | [
"function",
"applyBinds",
"(",
"fns",
",",
"instance",
")",
"{",
"var",
"i",
",",
"current",
";",
"for",
"(",
"i",
"=",
"fns",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"-=",
"1",
")",
"{",
"current",
"=",
"instance",
"[",
"fns",
"[",
"i",
"]",
"]",
";",
"instance",
"[",
"fns",
"[",
"i",
"]",
"]",
"=",
"bind",
"(",
"current",
",",
"instance",
")",
";",
"}",
"}"
] | Applies the context of given methods in the target.
@param {Array} fns The array of functions to be bound
@param {Object} instance The target instance | [
"Applies",
"the",
"context",
"of",
"given",
"methods",
"in",
"the",
"target",
"."
] | b251d5e8508bb05854081968528e6a3b2ec68d33 | https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/node/loose/Class.js#L357-L365 | train |
IndigoUnited/js-dejavu | dist/node/loose/Class.js | doBind | function doBind(func) {
/*jshint validthis:true*/
var args = toArray(arguments),
bound;
if (this && !func[$wrapped] && this.$static && this.$static[$class]) {
func = wrapMethod(null, func, this.$self || this.$static);
}
args.splice(1, 0, this);
bound = bind.apply(func, args);
return bound;
} | javascript | function doBind(func) {
/*jshint validthis:true*/
var args = toArray(arguments),
bound;
if (this && !func[$wrapped] && this.$static && this.$static[$class]) {
func = wrapMethod(null, func, this.$self || this.$static);
}
args.splice(1, 0, this);
bound = bind.apply(func, args);
return bound;
} | [
"function",
"doBind",
"(",
"func",
")",
"{",
"var",
"args",
"=",
"toArray",
"(",
"arguments",
")",
",",
"bound",
";",
"if",
"(",
"this",
"&&",
"!",
"func",
"[",
"$wrapped",
"]",
"&&",
"this",
".",
"$static",
"&&",
"this",
".",
"$static",
"[",
"$class",
"]",
")",
"{",
"func",
"=",
"wrapMethod",
"(",
"null",
",",
"func",
",",
"this",
".",
"$self",
"||",
"this",
".",
"$static",
")",
";",
"}",
"args",
".",
"splice",
"(",
"1",
",",
"0",
",",
"this",
")",
";",
"bound",
"=",
"bind",
".",
"apply",
"(",
"func",
",",
"args",
")",
";",
"return",
"bound",
";",
"}"
] | Bind.
Works for anonymous functions also.
@param {Function} func The function to be bound
@param {...mixed} [args] The arguments to also be bound
@return {Function} The bound function | [
"Bind",
".",
"Works",
"for",
"anonymous",
"functions",
"also",
"."
] | b251d5e8508bb05854081968528e6a3b2ec68d33 | https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/node/loose/Class.js#L430-L443 | train |
IndigoUnited/js-dejavu | dist/node/loose/Class.js | optimizeConstructor | function optimizeConstructor(constructor) {
var tmp = constructor[$class],
canOptimizeConst,
newConstructor,
parentInitialize;
// Check if we can optimize the constructor
if (tmp.efficient) {
canOptimizeConst = constructor.$canOptimizeConst;
delete constructor.$canOptimizeConst;
if (canOptimizeConst && !tmp.properties.length && !tmp.binds.length) {
if (hasOwn(constructor.prototype, 'initialize')) {
newConstructor = constructor.prototype.initialize;
} else {
parentInitialize = constructor.prototype.initialize;
// Optimize common use cases
// Default to the slower apply..
switch (parentInitialize.length) {
case 0:
newConstructor = function () { parentInitialize.call(this); };
break;
case 1:
newConstructor = function (a) { parentInitialize.call(this, a); };
break;
case 2:
newConstructor = function (a, b) { parentInitialize.call(this, a, b); };
break;
case 3:
newConstructor = function (a, b, c) { parentInitialize.call(this, a, b, c); };
break;
case 4:
newConstructor = function (a, b, c, d) { parentInitialize.call(this, a, b, c, d); };
break;
default:
newConstructor = function () { parentInitialize.apply(this, arguments); };
}
}
if (constructor.$parent) {
inheritPrototype(newConstructor, constructor);
newConstructor.$parent = constructor.$parent;
}
mixIn(newConstructor.prototype, constructor.prototype);
mixIn(newConstructor, constructor);
obfuscateProperty(newConstructor, $class, constructor[$class]);
return newConstructor;
}
}
return constructor;
} | javascript | function optimizeConstructor(constructor) {
var tmp = constructor[$class],
canOptimizeConst,
newConstructor,
parentInitialize;
// Check if we can optimize the constructor
if (tmp.efficient) {
canOptimizeConst = constructor.$canOptimizeConst;
delete constructor.$canOptimizeConst;
if (canOptimizeConst && !tmp.properties.length && !tmp.binds.length) {
if (hasOwn(constructor.prototype, 'initialize')) {
newConstructor = constructor.prototype.initialize;
} else {
parentInitialize = constructor.prototype.initialize;
// Optimize common use cases
// Default to the slower apply..
switch (parentInitialize.length) {
case 0:
newConstructor = function () { parentInitialize.call(this); };
break;
case 1:
newConstructor = function (a) { parentInitialize.call(this, a); };
break;
case 2:
newConstructor = function (a, b) { parentInitialize.call(this, a, b); };
break;
case 3:
newConstructor = function (a, b, c) { parentInitialize.call(this, a, b, c); };
break;
case 4:
newConstructor = function (a, b, c, d) { parentInitialize.call(this, a, b, c, d); };
break;
default:
newConstructor = function () { parentInitialize.apply(this, arguments); };
}
}
if (constructor.$parent) {
inheritPrototype(newConstructor, constructor);
newConstructor.$parent = constructor.$parent;
}
mixIn(newConstructor.prototype, constructor.prototype);
mixIn(newConstructor, constructor);
obfuscateProperty(newConstructor, $class, constructor[$class]);
return newConstructor;
}
}
return constructor;
} | [
"function",
"optimizeConstructor",
"(",
"constructor",
")",
"{",
"var",
"tmp",
"=",
"constructor",
"[",
"$class",
"]",
",",
"canOptimizeConst",
",",
"newConstructor",
",",
"parentInitialize",
";",
"if",
"(",
"tmp",
".",
"efficient",
")",
"{",
"canOptimizeConst",
"=",
"constructor",
".",
"$canOptimizeConst",
";",
"delete",
"constructor",
".",
"$canOptimizeConst",
";",
"if",
"(",
"canOptimizeConst",
"&&",
"!",
"tmp",
".",
"properties",
".",
"length",
"&&",
"!",
"tmp",
".",
"binds",
".",
"length",
")",
"{",
"if",
"(",
"hasOwn",
"(",
"constructor",
".",
"prototype",
",",
"'initialize'",
")",
")",
"{",
"newConstructor",
"=",
"constructor",
".",
"prototype",
".",
"initialize",
";",
"}",
"else",
"{",
"parentInitialize",
"=",
"constructor",
".",
"prototype",
".",
"initialize",
";",
"switch",
"(",
"parentInitialize",
".",
"length",
")",
"{",
"case",
"0",
":",
"newConstructor",
"=",
"function",
"(",
")",
"{",
"parentInitialize",
".",
"call",
"(",
"this",
")",
";",
"}",
";",
"break",
";",
"case",
"1",
":",
"newConstructor",
"=",
"function",
"(",
"a",
")",
"{",
"parentInitialize",
".",
"call",
"(",
"this",
",",
"a",
")",
";",
"}",
";",
"break",
";",
"case",
"2",
":",
"newConstructor",
"=",
"function",
"(",
"a",
",",
"b",
")",
"{",
"parentInitialize",
".",
"call",
"(",
"this",
",",
"a",
",",
"b",
")",
";",
"}",
";",
"break",
";",
"case",
"3",
":",
"newConstructor",
"=",
"function",
"(",
"a",
",",
"b",
",",
"c",
")",
"{",
"parentInitialize",
".",
"call",
"(",
"this",
",",
"a",
",",
"b",
",",
"c",
")",
";",
"}",
";",
"break",
";",
"case",
"4",
":",
"newConstructor",
"=",
"function",
"(",
"a",
",",
"b",
",",
"c",
",",
"d",
")",
"{",
"parentInitialize",
".",
"call",
"(",
"this",
",",
"a",
",",
"b",
",",
"c",
",",
"d",
")",
";",
"}",
";",
"break",
";",
"default",
":",
"newConstructor",
"=",
"function",
"(",
")",
"{",
"parentInitialize",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
";",
"}",
"}",
"if",
"(",
"constructor",
".",
"$parent",
")",
"{",
"inheritPrototype",
"(",
"newConstructor",
",",
"constructor",
")",
";",
"newConstructor",
".",
"$parent",
"=",
"constructor",
".",
"$parent",
";",
"}",
"mixIn",
"(",
"newConstructor",
".",
"prototype",
",",
"constructor",
".",
"prototype",
")",
";",
"mixIn",
"(",
"newConstructor",
",",
"constructor",
")",
";",
"obfuscateProperty",
"(",
"newConstructor",
",",
"$class",
",",
"constructor",
"[",
"$class",
"]",
")",
";",
"return",
"newConstructor",
";",
"}",
"}",
"return",
"constructor",
";",
"}"
] | Attempts to optimize the constructor function.
@param {Function} constructor The constructor
@param {Function} The old or the new constructor | [
"Attempts",
"to",
"optimize",
"the",
"constructor",
"function",
"."
] | b251d5e8508bb05854081968528e6a3b2ec68d33 | https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/node/loose/Class.js#L522-L576 | train |
GoogleCloudPlatform/cloud-errors-nodejs | lib/request-extractors/hapi.js | attemptToExtractStatusCode | function attemptToExtractStatusCode(req) {
if (has(req, 'response') && isObject(req.response) &&
has(req.response, 'statusCode')) {
return req.response.statusCode;
} else if (has(req, 'response') && isObject(req.response) &&
isObject(req.response.output)) {
return req.response.output.statusCode;
}
return 0;
} | javascript | function attemptToExtractStatusCode(req) {
if (has(req, 'response') && isObject(req.response) &&
has(req.response, 'statusCode')) {
return req.response.statusCode;
} else if (has(req, 'response') && isObject(req.response) &&
isObject(req.response.output)) {
return req.response.output.statusCode;
}
return 0;
} | [
"function",
"attemptToExtractStatusCode",
"(",
"req",
")",
"{",
"if",
"(",
"has",
"(",
"req",
",",
"'response'",
")",
"&&",
"isObject",
"(",
"req",
".",
"response",
")",
"&&",
"has",
"(",
"req",
".",
"response",
",",
"'statusCode'",
")",
")",
"{",
"return",
"req",
".",
"response",
".",
"statusCode",
";",
"}",
"else",
"if",
"(",
"has",
"(",
"req",
",",
"'response'",
")",
"&&",
"isObject",
"(",
"req",
".",
"response",
")",
"&&",
"isObject",
"(",
"req",
".",
"response",
".",
"output",
")",
")",
"{",
"return",
"req",
".",
"response",
".",
"output",
".",
"statusCode",
";",
"}",
"return",
"0",
";",
"}"
] | This function is used to check for a pending status code on the response
or a set status code on the response.output object property. If neither of
these properties can be found then -1 will be returned as the output.
@function attemptToExtractStatusCode
@param {Object} req - the request information object to extract from
@returns {Number} - Either an HTTP status code or -1 in absence of an
extractable status code. | [
"This",
"function",
"is",
"used",
"to",
"check",
"for",
"a",
"pending",
"status",
"code",
"on",
"the",
"response",
"or",
"a",
"set",
"status",
"code",
"on",
"the",
"response",
".",
"output",
"object",
"property",
".",
"If",
"neither",
"of",
"these",
"properties",
"can",
"be",
"found",
"then",
"-",
"1",
"will",
"be",
"returned",
"as",
"the",
"output",
"."
] | fda2218759cd8754a096dbe437e8a668321f5ba6 | https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/request-extractors/hapi.js#L34-L47 | train |
GoogleCloudPlatform/cloud-errors-nodejs | lib/request-extractors/hapi.js | extractRemoteAddressFromRequest | function extractRemoteAddressFromRequest(req) {
if (has(req.headers, 'x-forwarded-for')) {
return req.headers['x-forwarded-for'];
} else if (isObject(req.info)) {
return req.info.remoteAddress;
}
return '';
} | javascript | function extractRemoteAddressFromRequest(req) {
if (has(req.headers, 'x-forwarded-for')) {
return req.headers['x-forwarded-for'];
} else if (isObject(req.info)) {
return req.info.remoteAddress;
}
return '';
} | [
"function",
"extractRemoteAddressFromRequest",
"(",
"req",
")",
"{",
"if",
"(",
"has",
"(",
"req",
".",
"headers",
",",
"'x-forwarded-for'",
")",
")",
"{",
"return",
"req",
".",
"headers",
"[",
"'x-forwarded-for'",
"]",
";",
"}",
"else",
"if",
"(",
"isObject",
"(",
"req",
".",
"info",
")",
")",
"{",
"return",
"req",
".",
"info",
".",
"remoteAddress",
";",
"}",
"return",
"''",
";",
"}"
] | This function is used to check for the x-forwarded-for header first to
identify source IP connnections. If this header is not present, then the
function will attempt to extract the remoteAddress from the request.info
object property. If neither of these properties can be found then an empty
string will be returned.
@function extractRemoteAddressFromRequest
@param {Object} req - the request information object to extract from
@returns {String} - Either an empty string if the IP cannot be extracted or
a string that represents the remote IP address | [
"This",
"function",
"is",
"used",
"to",
"check",
"for",
"the",
"x",
"-",
"forwarded",
"-",
"for",
"header",
"first",
"to",
"identify",
"source",
"IP",
"connnections",
".",
"If",
"this",
"header",
"is",
"not",
"present",
"then",
"the",
"function",
"will",
"attempt",
"to",
"extract",
"the",
"remoteAddress",
"from",
"the",
"request",
".",
"info",
"object",
"property",
".",
"If",
"neither",
"of",
"these",
"properties",
"can",
"be",
"found",
"then",
"an",
"empty",
"string",
"will",
"be",
"returned",
"."
] | fda2218759cd8754a096dbe437e8a668321f5ba6 | https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/request-extractors/hapi.js#L60-L71 | train |
GoogleCloudPlatform/cloud-errors-nodejs | lib/request-extractors/hapi.js | hapiRequestInformationExtractor | function hapiRequestInformationExtractor(req) {
var returnObject = new RequestInformationContainer();
if (!isObject(req) || !isObject(req.headers) || isFunction(req) ||
isArray(req)) {
return returnObject;
}
returnObject.setMethod(req.method)
.setUrl(req.url)
.setUserAgent(req.headers['user-agent'])
.setReferrer(req.headers.referrer)
.setStatusCode(attemptToExtractStatusCode(req))
.setRemoteAddress(extractRemoteAddressFromRequest(req));
return returnObject;
} | javascript | function hapiRequestInformationExtractor(req) {
var returnObject = new RequestInformationContainer();
if (!isObject(req) || !isObject(req.headers) || isFunction(req) ||
isArray(req)) {
return returnObject;
}
returnObject.setMethod(req.method)
.setUrl(req.url)
.setUserAgent(req.headers['user-agent'])
.setReferrer(req.headers.referrer)
.setStatusCode(attemptToExtractStatusCode(req))
.setRemoteAddress(extractRemoteAddressFromRequest(req));
return returnObject;
} | [
"function",
"hapiRequestInformationExtractor",
"(",
"req",
")",
"{",
"var",
"returnObject",
"=",
"new",
"RequestInformationContainer",
"(",
")",
";",
"if",
"(",
"!",
"isObject",
"(",
"req",
")",
"||",
"!",
"isObject",
"(",
"req",
".",
"headers",
")",
"||",
"isFunction",
"(",
"req",
")",
"||",
"isArray",
"(",
"req",
")",
")",
"{",
"return",
"returnObject",
";",
"}",
"returnObject",
".",
"setMethod",
"(",
"req",
".",
"method",
")",
".",
"setUrl",
"(",
"req",
".",
"url",
")",
".",
"setUserAgent",
"(",
"req",
".",
"headers",
"[",
"'user-agent'",
"]",
")",
".",
"setReferrer",
"(",
"req",
".",
"headers",
".",
"referrer",
")",
".",
"setStatusCode",
"(",
"attemptToExtractStatusCode",
"(",
"req",
")",
")",
".",
"setRemoteAddress",
"(",
"extractRemoteAddressFromRequest",
"(",
"req",
")",
")",
";",
"return",
"returnObject",
";",
"}"
] | This function is used to extract request information from a hapi request
object. This function will not check for the presence of properties on the
request object.
@function hapiRequestInformationExtractor
@param {Object} req - the hapi request object to extract from
@returns {RequestInformationContainer} - an object containing the request
information in a standardized format | [
"This",
"function",
"is",
"used",
"to",
"extract",
"request",
"information",
"from",
"a",
"hapi",
"request",
"object",
".",
"This",
"function",
"will",
"not",
"check",
"for",
"the",
"presence",
"of",
"properties",
"on",
"the",
"request",
"object",
"."
] | fda2218759cd8754a096dbe437e8a668321f5ba6 | https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/request-extractors/hapi.js#L82-L100 | train |
anvilresearch/connect-nodejs | index.js | addScope | function addScope (scope) {
if (!scope) {
return
}
var oldScope = new Set(this.scope.split(' '))
var newScope
// Convert the incoming new scopes to a Set
if (typeof scope === 'string') {
newScope = new Set(scope.split(' '))
} else if (Array.isArray(scope)) {
newScope = new Set(scope)
} else {
throw new RangeError('Trying to add an invalid scope object')
}
oldScope.forEach(function (item) {
newScope.add(item)
})
// Convert back to string
this.scope = Array.from(newScope).join(' ')
} | javascript | function addScope (scope) {
if (!scope) {
return
}
var oldScope = new Set(this.scope.split(' '))
var newScope
// Convert the incoming new scopes to a Set
if (typeof scope === 'string') {
newScope = new Set(scope.split(' '))
} else if (Array.isArray(scope)) {
newScope = new Set(scope)
} else {
throw new RangeError('Trying to add an invalid scope object')
}
oldScope.forEach(function (item) {
newScope.add(item)
})
// Convert back to string
this.scope = Array.from(newScope).join(' ')
} | [
"function",
"addScope",
"(",
"scope",
")",
"{",
"if",
"(",
"!",
"scope",
")",
"{",
"return",
"}",
"var",
"oldScope",
"=",
"new",
"Set",
"(",
"this",
".",
"scope",
".",
"split",
"(",
"' '",
")",
")",
"var",
"newScope",
"if",
"(",
"typeof",
"scope",
"===",
"'string'",
")",
"{",
"newScope",
"=",
"new",
"Set",
"(",
"scope",
".",
"split",
"(",
"' '",
")",
")",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"scope",
")",
")",
"{",
"newScope",
"=",
"new",
"Set",
"(",
"scope",
")",
"}",
"else",
"{",
"throw",
"new",
"RangeError",
"(",
"'Trying to add an invalid scope object'",
")",
"}",
"oldScope",
".",
"forEach",
"(",
"function",
"(",
"item",
")",
"{",
"newScope",
".",
"add",
"(",
"item",
")",
"}",
")",
"this",
".",
"scope",
"=",
"Array",
".",
"from",
"(",
"newScope",
")",
".",
"join",
"(",
"' '",
")",
"}"
] | Adds the passed in list of scopes to the current one via a Set union
operation.
@param scope {Array|String} Either an array or a space-separated
string list of scopes.
@method addScope | [
"Adds",
"the",
"passed",
"in",
"list",
"of",
"scopes",
"to",
"the",
"current",
"one",
"via",
"a",
"Set",
"union",
"operation",
"."
] | fa630d5bd447bac630c33f9259d65a1483c0ff11 | https://github.com/anvilresearch/connect-nodejs/blob/fa630d5bd447bac630c33f9259d65a1483c0ff11/index.js#L77-L96 | train |
anvilresearch/connect-nodejs | index.js | discover | function discover () {
var self = this
// construct the uri
var uri = url.parse(this.issuer)
uri.pathname = '.well-known/openid-configuration'
uri = url.format(uri)
var requestOptions = {
url: uri,
method: 'GET',
json: true,
agentOptions: self.agentOptions
}
if (self.proxy) {
requestOptions.proxy = self.proxy
}
// return a promise
return new Promise(function (resolve, reject) {
request(requestOptions)
.then(function (data) {
// data will be an object if the server returned JSON
if (typeof data === 'object') {
self.configuration = data
resolve(data)
// If data is not an object, the server is not serving
// .well-known/openid-configuration as expected
} else {
reject(new Error('Unable to retrieve OpenID Connect configuration'))
}
})
.catch(function (err) {
reject(err)
})
})
} | javascript | function discover () {
var self = this
// construct the uri
var uri = url.parse(this.issuer)
uri.pathname = '.well-known/openid-configuration'
uri = url.format(uri)
var requestOptions = {
url: uri,
method: 'GET',
json: true,
agentOptions: self.agentOptions
}
if (self.proxy) {
requestOptions.proxy = self.proxy
}
// return a promise
return new Promise(function (resolve, reject) {
request(requestOptions)
.then(function (data) {
// data will be an object if the server returned JSON
if (typeof data === 'object') {
self.configuration = data
resolve(data)
// If data is not an object, the server is not serving
// .well-known/openid-configuration as expected
} else {
reject(new Error('Unable to retrieve OpenID Connect configuration'))
}
})
.catch(function (err) {
reject(err)
})
})
} | [
"function",
"discover",
"(",
")",
"{",
"var",
"self",
"=",
"this",
"var",
"uri",
"=",
"url",
".",
"parse",
"(",
"this",
".",
"issuer",
")",
"uri",
".",
"pathname",
"=",
"'.well-known/openid-configuration'",
"uri",
"=",
"url",
".",
"format",
"(",
"uri",
")",
"var",
"requestOptions",
"=",
"{",
"url",
":",
"uri",
",",
"method",
":",
"'GET'",
",",
"json",
":",
"true",
",",
"agentOptions",
":",
"self",
".",
"agentOptions",
"}",
"if",
"(",
"self",
".",
"proxy",
")",
"{",
"requestOptions",
".",
"proxy",
"=",
"self",
".",
"proxy",
"}",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"request",
"(",
"requestOptions",
")",
".",
"then",
"(",
"function",
"(",
"data",
")",
"{",
"if",
"(",
"typeof",
"data",
"===",
"'object'",
")",
"{",
"self",
".",
"configuration",
"=",
"data",
"resolve",
"(",
"data",
")",
"}",
"else",
"{",
"reject",
"(",
"new",
"Error",
"(",
"'Unable to retrieve OpenID Connect configuration'",
")",
")",
"}",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
"}",
")",
"}",
")",
"}"
] | Requests OIDC configuration from the AnvilConnect instance's provider.
Requires issuer to be set.
@method discover
@return {Promise} | [
"Requests",
"OIDC",
"configuration",
"from",
"the",
"AnvilConnect",
"instance",
"s",
"provider",
".",
"Requires",
"issuer",
"to",
"be",
"set",
"."
] | fa630d5bd447bac630c33f9259d65a1483c0ff11 | https://github.com/anvilresearch/connect-nodejs/blob/fa630d5bd447bac630c33f9259d65a1483c0ff11/index.js#L110-L145 | train |
anvilresearch/connect-nodejs | index.js | initAdminAPI | function initAdminAPI () {
this.clients = {
list: clients.list.bind(this),
get: clients.get.bind(this),
create: clients.create.bind(this),
update: clients.update.bind(this),
delete: clients.delete.bind(this),
roles: {
list: clientRoles.listRoles.bind(this),
add: clientRoles.addRole.bind(this),
delete: clientRoles.deleteRole.bind(this)
}
}
this.roles = {
list: roles.list.bind(this),
get: roles.get.bind(this),
create: roles.create.bind(this),
update: roles.update.bind(this),
delete: roles.delete.bind(this),
scopes: {
list: roleScopes.listScopes.bind(this),
add: roleScopes.addScope.bind(this),
delete: roleScopes.deleteScope.bind(this)
}
}
this.scopes = {
list: scopes.list.bind(this),
get: scopes.get.bind(this),
create: scopes.create.bind(this),
update: scopes.update.bind(this),
delete: scopes.delete.bind(this)
}
this.users = {
list: users.list.bind(this),
get: users.get.bind(this),
create: users.create.bind(this),
update: users.update.bind(this),
delete: users.delete.bind(this),
roles: {
list: userRoles.listRoles.bind(this),
add: userRoles.addRole.bind(this),
delete: userRoles.deleteRole.bind(this)
}
}
} | javascript | function initAdminAPI () {
this.clients = {
list: clients.list.bind(this),
get: clients.get.bind(this),
create: clients.create.bind(this),
update: clients.update.bind(this),
delete: clients.delete.bind(this),
roles: {
list: clientRoles.listRoles.bind(this),
add: clientRoles.addRole.bind(this),
delete: clientRoles.deleteRole.bind(this)
}
}
this.roles = {
list: roles.list.bind(this),
get: roles.get.bind(this),
create: roles.create.bind(this),
update: roles.update.bind(this),
delete: roles.delete.bind(this),
scopes: {
list: roleScopes.listScopes.bind(this),
add: roleScopes.addScope.bind(this),
delete: roleScopes.deleteScope.bind(this)
}
}
this.scopes = {
list: scopes.list.bind(this),
get: scopes.get.bind(this),
create: scopes.create.bind(this),
update: scopes.update.bind(this),
delete: scopes.delete.bind(this)
}
this.users = {
list: users.list.bind(this),
get: users.get.bind(this),
create: users.create.bind(this),
update: users.update.bind(this),
delete: users.delete.bind(this),
roles: {
list: userRoles.listRoles.bind(this),
add: userRoles.addRole.bind(this),
delete: userRoles.deleteRole.bind(this)
}
}
} | [
"function",
"initAdminAPI",
"(",
")",
"{",
"this",
".",
"clients",
"=",
"{",
"list",
":",
"clients",
".",
"list",
".",
"bind",
"(",
"this",
")",
",",
"get",
":",
"clients",
".",
"get",
".",
"bind",
"(",
"this",
")",
",",
"create",
":",
"clients",
".",
"create",
".",
"bind",
"(",
"this",
")",
",",
"update",
":",
"clients",
".",
"update",
".",
"bind",
"(",
"this",
")",
",",
"delete",
":",
"clients",
".",
"delete",
".",
"bind",
"(",
"this",
")",
",",
"roles",
":",
"{",
"list",
":",
"clientRoles",
".",
"listRoles",
".",
"bind",
"(",
"this",
")",
",",
"add",
":",
"clientRoles",
".",
"addRole",
".",
"bind",
"(",
"this",
")",
",",
"delete",
":",
"clientRoles",
".",
"deleteRole",
".",
"bind",
"(",
"this",
")",
"}",
"}",
"this",
".",
"roles",
"=",
"{",
"list",
":",
"roles",
".",
"list",
".",
"bind",
"(",
"this",
")",
",",
"get",
":",
"roles",
".",
"get",
".",
"bind",
"(",
"this",
")",
",",
"create",
":",
"roles",
".",
"create",
".",
"bind",
"(",
"this",
")",
",",
"update",
":",
"roles",
".",
"update",
".",
"bind",
"(",
"this",
")",
",",
"delete",
":",
"roles",
".",
"delete",
".",
"bind",
"(",
"this",
")",
",",
"scopes",
":",
"{",
"list",
":",
"roleScopes",
".",
"listScopes",
".",
"bind",
"(",
"this",
")",
",",
"add",
":",
"roleScopes",
".",
"addScope",
".",
"bind",
"(",
"this",
")",
",",
"delete",
":",
"roleScopes",
".",
"deleteScope",
".",
"bind",
"(",
"this",
")",
"}",
"}",
"this",
".",
"scopes",
"=",
"{",
"list",
":",
"scopes",
".",
"list",
".",
"bind",
"(",
"this",
")",
",",
"get",
":",
"scopes",
".",
"get",
".",
"bind",
"(",
"this",
")",
",",
"create",
":",
"scopes",
".",
"create",
".",
"bind",
"(",
"this",
")",
",",
"update",
":",
"scopes",
".",
"update",
".",
"bind",
"(",
"this",
")",
",",
"delete",
":",
"scopes",
".",
"delete",
".",
"bind",
"(",
"this",
")",
"}",
"this",
".",
"users",
"=",
"{",
"list",
":",
"users",
".",
"list",
".",
"bind",
"(",
"this",
")",
",",
"get",
":",
"users",
".",
"get",
".",
"bind",
"(",
"this",
")",
",",
"create",
":",
"users",
".",
"create",
".",
"bind",
"(",
"this",
")",
",",
"update",
":",
"users",
".",
"update",
".",
"bind",
"(",
"this",
")",
",",
"delete",
":",
"users",
".",
"delete",
".",
"bind",
"(",
"this",
")",
",",
"roles",
":",
"{",
"list",
":",
"userRoles",
".",
"listRoles",
".",
"bind",
"(",
"this",
")",
",",
"add",
":",
"userRoles",
".",
"addRole",
".",
"bind",
"(",
"this",
")",
",",
"delete",
":",
"userRoles",
".",
"deleteRole",
".",
"bind",
"(",
"this",
")",
"}",
"}",
"}"
] | Initializes the Anvil Connect admin API functions. Called by constructor.
@private
@method initAdminAPI | [
"Initializes",
"the",
"Anvil",
"Connect",
"admin",
"API",
"functions",
".",
"Called",
"by",
"constructor",
"."
] | fa630d5bd447bac630c33f9259d65a1483c0ff11 | https://github.com/anvilresearch/connect-nodejs/blob/fa630d5bd447bac630c33f9259d65a1483c0ff11/index.js#L242-L289 | train |
anvilresearch/connect-nodejs | index.js | authorizationUri | function authorizationUri (options) {
var u = url.parse(this.configuration.authorization_endpoint)
// assign endpoint and ensure options
var endpoint = 'authorize'
if (typeof options === 'string') {
endpoint = options
options = {}
} else if (typeof options === 'object') {
endpoint = options.endpoint
} else {
options = {}
}
// pathname
u.pathname = endpoint
// request params
u.query = this.authorizationParams(options)
return url.format(u)
} | javascript | function authorizationUri (options) {
var u = url.parse(this.configuration.authorization_endpoint)
// assign endpoint and ensure options
var endpoint = 'authorize'
if (typeof options === 'string') {
endpoint = options
options = {}
} else if (typeof options === 'object') {
endpoint = options.endpoint
} else {
options = {}
}
// pathname
u.pathname = endpoint
// request params
u.query = this.authorizationParams(options)
return url.format(u)
} | [
"function",
"authorizationUri",
"(",
"options",
")",
"{",
"var",
"u",
"=",
"url",
".",
"parse",
"(",
"this",
".",
"configuration",
".",
"authorization_endpoint",
")",
"var",
"endpoint",
"=",
"'authorize'",
"if",
"(",
"typeof",
"options",
"===",
"'string'",
")",
"{",
"endpoint",
"=",
"options",
"options",
"=",
"{",
"}",
"}",
"else",
"if",
"(",
"typeof",
"options",
"===",
"'object'",
")",
"{",
"endpoint",
"=",
"options",
".",
"endpoint",
"}",
"else",
"{",
"options",
"=",
"{",
"}",
"}",
"u",
".",
"pathname",
"=",
"endpoint",
"u",
".",
"query",
"=",
"this",
".",
"authorizationParams",
"(",
"options",
")",
"return",
"url",
".",
"format",
"(",
"u",
")",
"}"
] | Returns the url for an OIDC authorization call, for a given set of options.
@method authorizationUri
@param [options={}] {String|Object} Either a string representing an endpoint
(such as 'authorize'), or an options hashmap.
For a full list of options, see the docstring of `authorizationParams()`.
@param [options.endpoint='authorize'] Endpoint for which you're building the
uri.
@return {String} Authorization uri | [
"Returns",
"the",
"url",
"for",
"an",
"OIDC",
"authorization",
"call",
"for",
"a",
"given",
"set",
"of",
"options",
"."
] | fa630d5bd447bac630c33f9259d65a1483c0ff11 | https://github.com/anvilresearch/connect-nodejs/blob/fa630d5bd447bac630c33f9259d65a1483c0ff11/index.js#L414-L435 | train |
anvilresearch/connect-nodejs | index.js | verify | function verify (token, options) {
options = options || {}
options.issuer = options.issuer || this.issuer
options.client_id = options.client_id || this.client_id
options.client_secret = options.client_secret || this.client_secret
options.scope = options.scope || this.scope
options.key = options.key || this.jwks.sig
return new Promise(function (resolve, reject) {
AccessToken.verify(token, options, function (err, claims) {
if (err) { return reject(err) }
resolve(claims)
})
})
} | javascript | function verify (token, options) {
options = options || {}
options.issuer = options.issuer || this.issuer
options.client_id = options.client_id || this.client_id
options.client_secret = options.client_secret || this.client_secret
options.scope = options.scope || this.scope
options.key = options.key || this.jwks.sig
return new Promise(function (resolve, reject) {
AccessToken.verify(token, options, function (err, claims) {
if (err) { return reject(err) }
resolve(claims)
})
})
} | [
"function",
"verify",
"(",
"token",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
"options",
".",
"issuer",
"=",
"options",
".",
"issuer",
"||",
"this",
".",
"issuer",
"options",
".",
"client_id",
"=",
"options",
".",
"client_id",
"||",
"this",
".",
"client_id",
"options",
".",
"client_secret",
"=",
"options",
".",
"client_secret",
"||",
"this",
".",
"client_secret",
"options",
".",
"scope",
"=",
"options",
".",
"scope",
"||",
"this",
".",
"scope",
"options",
".",
"key",
"=",
"options",
".",
"key",
"||",
"this",
".",
"jwks",
".",
"sig",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"AccessToken",
".",
"verify",
"(",
"token",
",",
"options",
",",
"function",
"(",
"err",
",",
"claims",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"reject",
"(",
"err",
")",
"}",
"resolve",
"(",
"claims",
")",
"}",
")",
"}",
")",
"}"
] | Verifies a given OIDC token
@method verify
@param token {String} JWT AccessToken for OpenID Connect (base64 encoded)
@param [options={}] {Object} Options hashmap
@param [options.issuer] {String} OIDC Provider/Issuer URL
@param [options.key] {Object} Issuer's public key for signatures (jwks.sig)
@param [options.client_id] {String}
@param [options.client_secret {String}
@param [options.scope] {String}
@throws {UnauthorizedError} HTTP 401 or 403 errors (invalid tokens etc)
@return {Promise} | [
"Verifies",
"a",
"given",
"OIDC",
"token"
] | fa630d5bd447bac630c33f9259d65a1483c0ff11 | https://github.com/anvilresearch/connect-nodejs/blob/fa630d5bd447bac630c33f9259d65a1483c0ff11/index.js#L794-L808 | train |
GoogleCloudPlatform/cloud-errors-nodejs | lib/error-extractors/object.js | extractFromObject | function extractFromObject(err, errorMessage) {
if (has(err, 'message')) {
errorMessage.setMessage(err.message);
}
if (has(err, 'user')) {
errorMessage.setUser(err.user);
}
if (has(err, 'filePath')) {
errorMessage.setFilePath(err.filePath);
}
if (has(err, 'lineNumber')) {
errorMessage.setLineNumber(err.lineNumber);
}
if (has(err, 'functionName')) {
errorMessage.setFunctionName(err.functionName);
}
if (has(err, 'serviceContext') && isObject(err.serviceContext)) {
errorMessage.setServiceContext(err.serviceContext.service,
err.serviceContext.version);
}
} | javascript | function extractFromObject(err, errorMessage) {
if (has(err, 'message')) {
errorMessage.setMessage(err.message);
}
if (has(err, 'user')) {
errorMessage.setUser(err.user);
}
if (has(err, 'filePath')) {
errorMessage.setFilePath(err.filePath);
}
if (has(err, 'lineNumber')) {
errorMessage.setLineNumber(err.lineNumber);
}
if (has(err, 'functionName')) {
errorMessage.setFunctionName(err.functionName);
}
if (has(err, 'serviceContext') && isObject(err.serviceContext)) {
errorMessage.setServiceContext(err.serviceContext.service,
err.serviceContext.version);
}
} | [
"function",
"extractFromObject",
"(",
"err",
",",
"errorMessage",
")",
"{",
"if",
"(",
"has",
"(",
"err",
",",
"'message'",
")",
")",
"{",
"errorMessage",
".",
"setMessage",
"(",
"err",
".",
"message",
")",
";",
"}",
"if",
"(",
"has",
"(",
"err",
",",
"'user'",
")",
")",
"{",
"errorMessage",
".",
"setUser",
"(",
"err",
".",
"user",
")",
";",
"}",
"if",
"(",
"has",
"(",
"err",
",",
"'filePath'",
")",
")",
"{",
"errorMessage",
".",
"setFilePath",
"(",
"err",
".",
"filePath",
")",
";",
"}",
"if",
"(",
"has",
"(",
"err",
",",
"'lineNumber'",
")",
")",
"{",
"errorMessage",
".",
"setLineNumber",
"(",
"err",
".",
"lineNumber",
")",
";",
"}",
"if",
"(",
"has",
"(",
"err",
",",
"'functionName'",
")",
")",
"{",
"errorMessage",
".",
"setFunctionName",
"(",
"err",
".",
"functionName",
")",
";",
"}",
"if",
"(",
"has",
"(",
"err",
",",
"'serviceContext'",
")",
"&&",
"isObject",
"(",
"err",
".",
"serviceContext",
")",
")",
"{",
"errorMessage",
".",
"setServiceContext",
"(",
"err",
".",
"serviceContext",
".",
"service",
",",
"err",
".",
"serviceContext",
".",
"version",
")",
";",
"}",
"}"
] | Attempts to extract error information given an object as the input for the
error. This function will check presence of each property before attempting
to access the given property on the object but will not check for type
compliance as that is allocated to the instance of the error message itself.
@function extractFromObject
@param {Object} err - the Object given as the content of the error
@param {String} [err.message] - the error message
@param {String} [err.user] - the user the error occurred for
@param {String} [err.filePath] - the file path and file where the error
occurred at
@param {Number} [err.lineNumber] - the line number where the error occurred
at
@param {String} [err.functionName] - the function where the error occurred at
@param {Object} [err.serviceContext] - the service context object of the
error
@param {String} [err.serviceContext.service] - the service the error occurred
on
@param {String} [err.serviceContext.version] - the version of the application
that the error occurred on
@param {ErrorMessage} errorMessage - the error message instance to marshal
error information into
@returns {Undefined} - does not return anything | [
"Attempts",
"to",
"extract",
"error",
"information",
"given",
"an",
"object",
"as",
"the",
"input",
"for",
"the",
"error",
".",
"This",
"function",
"will",
"check",
"presence",
"of",
"each",
"property",
"before",
"attempting",
"to",
"access",
"the",
"given",
"property",
"on",
"the",
"object",
"but",
"will",
"not",
"check",
"for",
"type",
"compliance",
"as",
"that",
"is",
"allocated",
"to",
"the",
"instance",
"of",
"the",
"error",
"message",
"itself",
"."
] | fda2218759cd8754a096dbe437e8a668321f5ba6 | https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/error-extractors/object.js#L46-L78 | train |
Subsets and Splits