repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
michaelkrone/generator-material-app | generators/app/templates/server/lib/controllers/crud.controller.js | function (req, res) {
var query = req.query;
if (this.omit.length) {
query = _.omit(query, this.omit);
}
query = this.model.find(query);
if (this.lean) {
query.lean();
}
if (this.select.length) {
query.select(this.select.join(' '));
}
this.populateQuery(query, this.filterPopulations('index'));
query.exec(function (err, documents) {
if (err) {
return res.handleError(err);
}
return res.ok(documents);
});
} | javascript | function (req, res) {
var query = req.query;
if (this.omit.length) {
query = _.omit(query, this.omit);
}
query = this.model.find(query);
if (this.lean) {
query.lean();
}
if (this.select.length) {
query.select(this.select.join(' '));
}
this.populateQuery(query, this.filterPopulations('index'));
query.exec(function (err, documents) {
if (err) {
return res.handleError(err);
}
return res.ok(documents);
});
} | [
"function",
"(",
"req",
",",
"res",
")",
"{",
"var",
"query",
"=",
"req",
".",
"query",
";",
"if",
"(",
"this",
".",
"omit",
".",
"length",
")",
"{",
"query",
"=",
"_",
".",
"omit",
"(",
"query",
",",
"this",
".",
"omit",
")",
";",
"}",
"query",
"=",
"this",
".",
"model",
".",
"find",
"(",
"query",
")",
";",
"if",
"(",
"this",
".",
"lean",
")",
"{",
"query",
".",
"lean",
"(",
")",
";",
"}",
"if",
"(",
"this",
".",
"select",
".",
"length",
")",
"{",
"query",
".",
"select",
"(",
"this",
".",
"select",
".",
"join",
"(",
"' '",
")",
")",
";",
"}",
"this",
".",
"populateQuery",
"(",
"query",
",",
"this",
".",
"filterPopulations",
"(",
"'index'",
")",
")",
";",
"query",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"documents",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"res",
".",
"handleError",
"(",
"err",
")",
";",
"}",
"return",
"res",
".",
"ok",
"(",
"documents",
")",
";",
"}",
")",
";",
"}"
]
| Get a list of documents. If a request query is passed it is used as the
query object for the find method.
@param {IncomingMessage} req - The request message object
@param {ServerResponse} res - The outgoing response object the result is set to
@returns {ServerResponse} Array of all documents for the {@link CrudController#model} model
or the empty Array if no documents have been found | [
"Get",
"a",
"list",
"of",
"documents",
".",
"If",
"a",
"request",
"query",
"is",
"passed",
"it",
"is",
"used",
"as",
"the",
"query",
"object",
"for",
"the",
"find",
"method",
"."
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/controllers/crud.controller.js#L106-L131 | train |
|
michaelkrone/generator-material-app | generators/app/templates/server/lib/controllers/crud.controller.js | function (req, res) {
var self = this;
var populations = self.filterPopulations('create');
this.model.populate(req.body, populations, function (err, populated) {
if (err) {
return res.handleError(err);
}
self.model.create(populated, function (err, document) {
if (err) {
return res.handleError(err);
}
populated._id = document._id;
return res.created(self.getResponseObject(populated));
})
});
} | javascript | function (req, res) {
var self = this;
var populations = self.filterPopulations('create');
this.model.populate(req.body, populations, function (err, populated) {
if (err) {
return res.handleError(err);
}
self.model.create(populated, function (err, document) {
if (err) {
return res.handleError(err);
}
populated._id = document._id;
return res.created(self.getResponseObject(populated));
})
});
} | [
"function",
"(",
"req",
",",
"res",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"populations",
"=",
"self",
".",
"filterPopulations",
"(",
"'create'",
")",
";",
"this",
".",
"model",
".",
"populate",
"(",
"req",
".",
"body",
",",
"populations",
",",
"function",
"(",
"err",
",",
"populated",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"res",
".",
"handleError",
"(",
"err",
")",
";",
"}",
"self",
".",
"model",
".",
"create",
"(",
"populated",
",",
"function",
"(",
"err",
",",
"document",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"res",
".",
"handleError",
"(",
"err",
")",
";",
"}",
"populated",
".",
"_id",
"=",
"document",
".",
"_id",
";",
"return",
"res",
".",
"created",
"(",
"self",
".",
"getResponseObject",
"(",
"populated",
")",
")",
";",
"}",
")",
"}",
")",
";",
"}"
]
| Creates a new document in the DB.
@param {IncomingMessage} req - The request message object containing the json document data
@param {ServerResponse} res - The outgoing response object
@returns {ServerResponse} The response status 201 CREATED or an error response | [
"Creates",
"a",
"new",
"document",
"in",
"the",
"DB",
"."
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/controllers/crud.controller.js#L166-L185 | train |
|
michaelkrone/generator-material-app | generators/app/templates/client/app/components/mongoose-error/mongoose-error.directive.js | setResponseErrors | function setResponseErrors(err, obj) {
/* jshint validthis: true */
var self = this;
obj = obj || {};
if (err.data && err.data.errors) {
err = err.data.errors;
}
if (err.errors) {
err = err.errors;
}
angular.forEach(err, function (error, field) {
if (self[field]) {
self[field].$setValidity('mongoose', false);
}
obj[field] = error.type;
});
} | javascript | function setResponseErrors(err, obj) {
/* jshint validthis: true */
var self = this;
obj = obj || {};
if (err.data && err.data.errors) {
err = err.data.errors;
}
if (err.errors) {
err = err.errors;
}
angular.forEach(err, function (error, field) {
if (self[field]) {
self[field].$setValidity('mongoose', false);
}
obj[field] = error.type;
});
} | [
"function",
"setResponseErrors",
"(",
"err",
",",
"obj",
")",
"{",
"var",
"self",
"=",
"this",
";",
"obj",
"=",
"obj",
"||",
"{",
"}",
";",
"if",
"(",
"err",
".",
"data",
"&&",
"err",
".",
"data",
".",
"errors",
")",
"{",
"err",
"=",
"err",
".",
"data",
".",
"errors",
";",
"}",
"if",
"(",
"err",
".",
"errors",
")",
"{",
"err",
"=",
"err",
".",
"errors",
";",
"}",
"angular",
".",
"forEach",
"(",
"err",
",",
"function",
"(",
"error",
",",
"field",
")",
"{",
"if",
"(",
"self",
"[",
"field",
"]",
")",
"{",
"self",
"[",
"field",
"]",
".",
"$setValidity",
"(",
"'mongoose'",
",",
"false",
")",
";",
"}",
"obj",
"[",
"field",
"]",
"=",
"error",
".",
"type",
";",
"}",
")",
";",
"}"
]
| Update validity of form fields that match the mongoose errors
@param {Object} errors - The errors object to look for property names on
@param {Object} [obj] - Object to attach all errors to
@return {Object} An object with all fields mapped to the corresponding error | [
"Update",
"validity",
"of",
"form",
"fields",
"that",
"match",
"the",
"mongoose",
"errors"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/components/mongoose-error/mongoose-error.directive.js#L123-L142 | train |
jillix/medium-editor-custom-html | src/custom-html.js | CustomHtml | function CustomHtml(options) {
this.button = document.createElement('button');
this.button.className = 'medium-editor-action';
if (this.button.innerText) {
this.button.innerText = options.buttonText || "</>";
} else {
this.button.textContent = options.buttonText || "</>";
}
this.button.onclick = this.onClick.bind(this);
this.options = options;
} | javascript | function CustomHtml(options) {
this.button = document.createElement('button');
this.button.className = 'medium-editor-action';
if (this.button.innerText) {
this.button.innerText = options.buttonText || "</>";
} else {
this.button.textContent = options.buttonText || "</>";
}
this.button.onclick = this.onClick.bind(this);
this.options = options;
} | [
"function",
"CustomHtml",
"(",
"options",
")",
"{",
"this",
".",
"button",
"=",
"document",
".",
"createElement",
"(",
"'button'",
")",
";",
"this",
".",
"button",
".",
"className",
"=",
"'medium-editor-action'",
";",
"if",
"(",
"this",
".",
"button",
".",
"innerText",
")",
"{",
"this",
".",
"button",
".",
"innerText",
"=",
"options",
".",
"buttonText",
"||",
"\"</>\"",
";",
"}",
"else",
"{",
"this",
".",
"button",
".",
"textContent",
"=",
"options",
".",
"buttonText",
"||",
"\"</>\"",
";",
"}",
"this",
".",
"button",
".",
"onclick",
"=",
"this",
".",
"onClick",
".",
"bind",
"(",
"this",
")",
";",
"this",
".",
"options",
"=",
"options",
";",
"}"
]
| CustomHtml
Creates a new instance of CustomHtml extension.
Licensed under the MIT license.
Copyright (c) 2014 jillix
@name CustomHtml
@function
@param {Object} options An object containing the extension configuration. The
following fields should be provided:
- buttonText: the text of the button (default: `</>`)
- htmlToInsert: the HTML code that should be inserted | [
"CustomHtml",
"Creates",
"a",
"new",
"instance",
"of",
"CustomHtml",
"extension",
"."
]
| d49a40979c2b5fb0fa58c8b6a0d1875dbf4da6ca | https://github.com/jillix/medium-editor-custom-html/blob/d49a40979c2b5fb0fa58c8b6a0d1875dbf4da6ca/src/custom-html.js#L16-L26 | train |
michaelkrone/generator-material-app | generators/app/templates/server/api/clientModelDoc(demo)/clientModelDoc.socket.js | registerClientModelDocSockets | function registerClientModelDocSockets(socket) {
ClientModelDoc.schema.post('save', function (doc) {
onSave(socket, doc);
});
ClientModelDoc.schema.post('remove', function (doc) {
onRemove(socket, doc);
});
} | javascript | function registerClientModelDocSockets(socket) {
ClientModelDoc.schema.post('save', function (doc) {
onSave(socket, doc);
});
ClientModelDoc.schema.post('remove', function (doc) {
onRemove(socket, doc);
});
} | [
"function",
"registerClientModelDocSockets",
"(",
"socket",
")",
"{",
"ClientModelDoc",
".",
"schema",
".",
"post",
"(",
"'save'",
",",
"function",
"(",
"doc",
")",
"{",
"onSave",
"(",
"socket",
",",
"doc",
")",
";",
"}",
")",
";",
"ClientModelDoc",
".",
"schema",
".",
"post",
"(",
"'remove'",
",",
"function",
"(",
"doc",
")",
"{",
"onRemove",
"(",
"socket",
",",
"doc",
")",
";",
"}",
")",
";",
"}"
]
| Register ClientModelDoc model change events on the passed socket
@param {socket.io} socket - The socket object to register the ClientModelDoc model events on | [
"Register",
"ClientModelDoc",
"model",
"change",
"events",
"on",
"the",
"passed",
"socket"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/api/clientModelDoc(demo)/clientModelDoc.socket.js#L24-L32 | train |
michaelkrone/generator-material-app | generators/app/templates/client/app/clientModelDoc(demo)/list/edit/edit.controller.js | update | function update(form) {
// refuse to work with invalid data
if (!vm.clientModelDoc._id || form && !form.$valid) {
return;
}
ClientModelDocService.update(vm.clientModelDoc)
.then(updateClientModelDocSuccess)
.catch(updateClientModelDocCatch);
function updateClientModelDocSuccess(updatedClientModelDoc) {
// update the display name after successful save
vm.displayName = updatedClientModelDoc.name;
Toast.show({text: 'ClientModelDoc ' + vm.displayName + ' updated'});
if (form) {
form.$setPristine();
}
}
function updateClientModelDocCatch(err) {
Toast.show({
type: 'warn',
text: 'Error while updating ClientModelDoc ' + vm.displayName,
link: {state: $state.$current, params: $stateParams}
});
if (form && err) {
form.setResponseErrors(err.data);
}
}
} | javascript | function update(form) {
// refuse to work with invalid data
if (!vm.clientModelDoc._id || form && !form.$valid) {
return;
}
ClientModelDocService.update(vm.clientModelDoc)
.then(updateClientModelDocSuccess)
.catch(updateClientModelDocCatch);
function updateClientModelDocSuccess(updatedClientModelDoc) {
// update the display name after successful save
vm.displayName = updatedClientModelDoc.name;
Toast.show({text: 'ClientModelDoc ' + vm.displayName + ' updated'});
if (form) {
form.$setPristine();
}
}
function updateClientModelDocCatch(err) {
Toast.show({
type: 'warn',
text: 'Error while updating ClientModelDoc ' + vm.displayName,
link: {state: $state.$current, params: $stateParams}
});
if (form && err) {
form.setResponseErrors(err.data);
}
}
} | [
"function",
"update",
"(",
"form",
")",
"{",
"if",
"(",
"!",
"vm",
".",
"clientModelDoc",
".",
"_id",
"||",
"form",
"&&",
"!",
"form",
".",
"$valid",
")",
"{",
"return",
";",
"}",
"ClientModelDocService",
".",
"update",
"(",
"vm",
".",
"clientModelDoc",
")",
".",
"then",
"(",
"updateClientModelDocSuccess",
")",
".",
"catch",
"(",
"updateClientModelDocCatch",
")",
";",
"function",
"updateClientModelDocSuccess",
"(",
"updatedClientModelDoc",
")",
"{",
"vm",
".",
"displayName",
"=",
"updatedClientModelDoc",
".",
"name",
";",
"Toast",
".",
"show",
"(",
"{",
"text",
":",
"'ClientModelDoc '",
"+",
"vm",
".",
"displayName",
"+",
"' updated'",
"}",
")",
";",
"if",
"(",
"form",
")",
"{",
"form",
".",
"$setPristine",
"(",
")",
";",
"}",
"}",
"function",
"updateClientModelDocCatch",
"(",
"err",
")",
"{",
"Toast",
".",
"show",
"(",
"{",
"type",
":",
"'warn'",
",",
"text",
":",
"'Error while updating ClientModelDoc '",
"+",
"vm",
".",
"displayName",
",",
"link",
":",
"{",
"state",
":",
"$state",
".",
"$current",
",",
"params",
":",
"$stateParams",
"}",
"}",
")",
";",
"if",
"(",
"form",
"&&",
"err",
")",
"{",
"form",
".",
"setResponseErrors",
"(",
"err",
".",
"data",
")",
";",
"}",
"}",
"}"
]
| Updates a clientModelDoc by using the ClientModelDocService save method
@param {Form} [form] | [
"Updates",
"a",
"clientModelDoc",
"by",
"using",
"the",
"ClientModelDocService",
"save",
"method"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/clientModelDoc(demo)/list/edit/edit.controller.js#L66-L96 | train |
michaelkrone/generator-material-app | generators/app/templates/client/app/clientModelDoc(demo)/list/edit/edit.controller.js | remove | function remove(form, ev) {
var confirm = $mdDialog.confirm()
.title('Delete clientModelDoc ' + vm.displayName + '?')
.content('Do you really want to delete clientModelDoc ' + vm.displayName + '?')
.ariaLabel('Delete clientModelDoc')
.ok('Delete clientModelDoc')
.cancel('Cancel')
.targetEvent(ev);
$mdDialog.show(confirm)
.then(performRemove);
/**
* Removes a clientModelDoc by using the ClientModelDocService remove method
* @api private
*/
function performRemove() {
ClientModelDocService.remove(vm.clientModelDoc)
.then(deleteClientModelDocSuccess)
.catch(deleteClientModelDocCatch);
function deleteClientModelDocSuccess() {
Toast.show({type: 'success', text: 'ClientModelDoc ' + vm.displayName + ' deleted'});
vm.showList();
}
function deleteClientModelDocCatch(err) {
Toast.show({
type: 'warn',
text: 'Error while deleting clientModelDoc ' + vm.displayName,
link: {state: $state.$current, params: $stateParams}
});
if (form && err) {
form.setResponseErrors(err, vm.errors);
}
}
}
} | javascript | function remove(form, ev) {
var confirm = $mdDialog.confirm()
.title('Delete clientModelDoc ' + vm.displayName + '?')
.content('Do you really want to delete clientModelDoc ' + vm.displayName + '?')
.ariaLabel('Delete clientModelDoc')
.ok('Delete clientModelDoc')
.cancel('Cancel')
.targetEvent(ev);
$mdDialog.show(confirm)
.then(performRemove);
/**
* Removes a clientModelDoc by using the ClientModelDocService remove method
* @api private
*/
function performRemove() {
ClientModelDocService.remove(vm.clientModelDoc)
.then(deleteClientModelDocSuccess)
.catch(deleteClientModelDocCatch);
function deleteClientModelDocSuccess() {
Toast.show({type: 'success', text: 'ClientModelDoc ' + vm.displayName + ' deleted'});
vm.showList();
}
function deleteClientModelDocCatch(err) {
Toast.show({
type: 'warn',
text: 'Error while deleting clientModelDoc ' + vm.displayName,
link: {state: $state.$current, params: $stateParams}
});
if (form && err) {
form.setResponseErrors(err, vm.errors);
}
}
}
} | [
"function",
"remove",
"(",
"form",
",",
"ev",
")",
"{",
"var",
"confirm",
"=",
"$mdDialog",
".",
"confirm",
"(",
")",
".",
"title",
"(",
"'Delete clientModelDoc '",
"+",
"vm",
".",
"displayName",
"+",
"'?'",
")",
".",
"content",
"(",
"'Do you really want to delete clientModelDoc '",
"+",
"vm",
".",
"displayName",
"+",
"'?'",
")",
".",
"ariaLabel",
"(",
"'Delete clientModelDoc'",
")",
".",
"ok",
"(",
"'Delete clientModelDoc'",
")",
".",
"cancel",
"(",
"'Cancel'",
")",
".",
"targetEvent",
"(",
"ev",
")",
";",
"$mdDialog",
".",
"show",
"(",
"confirm",
")",
".",
"then",
"(",
"performRemove",
")",
";",
"function",
"performRemove",
"(",
")",
"{",
"ClientModelDocService",
".",
"remove",
"(",
"vm",
".",
"clientModelDoc",
")",
".",
"then",
"(",
"deleteClientModelDocSuccess",
")",
".",
"catch",
"(",
"deleteClientModelDocCatch",
")",
";",
"function",
"deleteClientModelDocSuccess",
"(",
")",
"{",
"Toast",
".",
"show",
"(",
"{",
"type",
":",
"'success'",
",",
"text",
":",
"'ClientModelDoc '",
"+",
"vm",
".",
"displayName",
"+",
"' deleted'",
"}",
")",
";",
"vm",
".",
"showList",
"(",
")",
";",
"}",
"function",
"deleteClientModelDocCatch",
"(",
"err",
")",
"{",
"Toast",
".",
"show",
"(",
"{",
"type",
":",
"'warn'",
",",
"text",
":",
"'Error while deleting clientModelDoc '",
"+",
"vm",
".",
"displayName",
",",
"link",
":",
"{",
"state",
":",
"$state",
".",
"$current",
",",
"params",
":",
"$stateParams",
"}",
"}",
")",
";",
"if",
"(",
"form",
"&&",
"err",
")",
"{",
"form",
".",
"setResponseErrors",
"(",
"err",
",",
"vm",
".",
"errors",
")",
";",
"}",
"}",
"}",
"}"
]
| Show a dialog to ask the clientModelDoc if she wants to delete the current selected clientModelDoc.
@param {AngularForm} form - The form to pass to the remove handler
@param {$event} ev - The event to pass to the dialog service | [
"Show",
"a",
"dialog",
"to",
"ask",
"the",
"clientModelDoc",
"if",
"she",
"wants",
"to",
"delete",
"the",
"current",
"selected",
"clientModelDoc",
"."
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/clientModelDoc(demo)/list/edit/edit.controller.js#L103-L141 | train |
michaelkrone/generator-material-app | generators/app/templates/client/app/clientModelDoc(demo)/list/edit/edit.controller.js | performRemove | function performRemove() {
ClientModelDocService.remove(vm.clientModelDoc)
.then(deleteClientModelDocSuccess)
.catch(deleteClientModelDocCatch);
function deleteClientModelDocSuccess() {
Toast.show({type: 'success', text: 'ClientModelDoc ' + vm.displayName + ' deleted'});
vm.showList();
}
function deleteClientModelDocCatch(err) {
Toast.show({
type: 'warn',
text: 'Error while deleting clientModelDoc ' + vm.displayName,
link: {state: $state.$current, params: $stateParams}
});
if (form && err) {
form.setResponseErrors(err, vm.errors);
}
}
} | javascript | function performRemove() {
ClientModelDocService.remove(vm.clientModelDoc)
.then(deleteClientModelDocSuccess)
.catch(deleteClientModelDocCatch);
function deleteClientModelDocSuccess() {
Toast.show({type: 'success', text: 'ClientModelDoc ' + vm.displayName + ' deleted'});
vm.showList();
}
function deleteClientModelDocCatch(err) {
Toast.show({
type: 'warn',
text: 'Error while deleting clientModelDoc ' + vm.displayName,
link: {state: $state.$current, params: $stateParams}
});
if (form && err) {
form.setResponseErrors(err, vm.errors);
}
}
} | [
"function",
"performRemove",
"(",
")",
"{",
"ClientModelDocService",
".",
"remove",
"(",
"vm",
".",
"clientModelDoc",
")",
".",
"then",
"(",
"deleteClientModelDocSuccess",
")",
".",
"catch",
"(",
"deleteClientModelDocCatch",
")",
";",
"function",
"deleteClientModelDocSuccess",
"(",
")",
"{",
"Toast",
".",
"show",
"(",
"{",
"type",
":",
"'success'",
",",
"text",
":",
"'ClientModelDoc '",
"+",
"vm",
".",
"displayName",
"+",
"' deleted'",
"}",
")",
";",
"vm",
".",
"showList",
"(",
")",
";",
"}",
"function",
"deleteClientModelDocCatch",
"(",
"err",
")",
"{",
"Toast",
".",
"show",
"(",
"{",
"type",
":",
"'warn'",
",",
"text",
":",
"'Error while deleting clientModelDoc '",
"+",
"vm",
".",
"displayName",
",",
"link",
":",
"{",
"state",
":",
"$state",
".",
"$current",
",",
"params",
":",
"$stateParams",
"}",
"}",
")",
";",
"if",
"(",
"form",
"&&",
"err",
")",
"{",
"form",
".",
"setResponseErrors",
"(",
"err",
",",
"vm",
".",
"errors",
")",
";",
"}",
"}",
"}"
]
| Removes a clientModelDoc by using the ClientModelDocService remove method
@api private | [
"Removes",
"a",
"clientModelDoc",
"by",
"using",
"the",
"ClientModelDocService",
"remove",
"method"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/clientModelDoc(demo)/list/edit/edit.controller.js#L119-L140 | train |
michaelkrone/generator-material-app | generators/app/templates/server/lib/controllers/param.controller.js | ParamController | function ParamController(model, idName, paramName, router) {
var modelName = model.modelName.toLowerCase();
// make idName and paramName arguments optional (v0.1.1)
if (typeof idName === 'function') {
router = idName;
idName = modelName + 'Id';
}
if (typeof paramName === 'function') {
router = paramName;
paramName = modelName + 'Param';
}
// call super constructor
CrudController.call(this, model, idName);
// only set param if it is set, will default to 'id'
if (!paramName) {
paramName = modelName + 'Param';
}
this.paramName = String(paramName);
this.paramString = ':' + this.paramName;
// register param name route parameter
router.param(this.paramName, this.registerRequestParameter);
} | javascript | function ParamController(model, idName, paramName, router) {
var modelName = model.modelName.toLowerCase();
// make idName and paramName arguments optional (v0.1.1)
if (typeof idName === 'function') {
router = idName;
idName = modelName + 'Id';
}
if (typeof paramName === 'function') {
router = paramName;
paramName = modelName + 'Param';
}
// call super constructor
CrudController.call(this, model, idName);
// only set param if it is set, will default to 'id'
if (!paramName) {
paramName = modelName + 'Param';
}
this.paramName = String(paramName);
this.paramString = ':' + this.paramName;
// register param name route parameter
router.param(this.paramName, this.registerRequestParameter);
} | [
"function",
"ParamController",
"(",
"model",
",",
"idName",
",",
"paramName",
",",
"router",
")",
"{",
"var",
"modelName",
"=",
"model",
".",
"modelName",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"typeof",
"idName",
"===",
"'function'",
")",
"{",
"router",
"=",
"idName",
";",
"idName",
"=",
"modelName",
"+",
"'Id'",
";",
"}",
"if",
"(",
"typeof",
"paramName",
"===",
"'function'",
")",
"{",
"router",
"=",
"paramName",
";",
"paramName",
"=",
"modelName",
"+",
"'Param'",
";",
"}",
"CrudController",
".",
"call",
"(",
"this",
",",
"model",
",",
"idName",
")",
";",
"if",
"(",
"!",
"paramName",
")",
"{",
"paramName",
"=",
"modelName",
"+",
"'Param'",
";",
"}",
"this",
".",
"paramName",
"=",
"String",
"(",
"paramName",
")",
";",
"this",
".",
"paramString",
"=",
"':'",
"+",
"this",
".",
"paramName",
";",
"router",
".",
"param",
"(",
"this",
".",
"paramName",
",",
"this",
".",
"registerRequestParameter",
")",
";",
"}"
]
| Constructor function for ParamController.
@classdesc Controller for basic CRUD operations on mongoose models.
Using a route parameter object (request property) if possible.
The parameter name is passed as the third argument.
@constructor
@inherits CrudController
@param {Object} model - The mongoose model to operate on
@param {String} [idName] - The name of the id request parameter to use,
defaults to the lowercase model name with 'Id' appended.
@param {String} [paramName] - The name of the request property to use,
defaults to the lowercase model name with 'Param' appended.
@param {Object} router - The express router to attach the param function to | [
"Constructor",
"function",
"for",
"ParamController",
"."
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/controllers/param.controller.js#L28-L55 | train |
michaelkrone/generator-material-app | generators/app/templates/server/lib/controllers/param.controller.js | function (req, res, next, id) {
var self = this;
// check if a custom id is used, when not only process a valid object id
if (this.mongoId && !ObjectID.isValid(id)) {
res.badRequest();
return next();
}
// attach the document as this.paramName to the request
this.model.findOne({'_id': id}, function (err, doc) {
if (err) {
return next(err);
}
if (!doc) {
res.notFound();
return next('route');
}
req[self.paramName] = doc;
return next();
});
} | javascript | function (req, res, next, id) {
var self = this;
// check if a custom id is used, when not only process a valid object id
if (this.mongoId && !ObjectID.isValid(id)) {
res.badRequest();
return next();
}
// attach the document as this.paramName to the request
this.model.findOne({'_id': id}, function (err, doc) {
if (err) {
return next(err);
}
if (!doc) {
res.notFound();
return next('route');
}
req[self.paramName] = doc;
return next();
});
} | [
"function",
"(",
"req",
",",
"res",
",",
"next",
",",
"id",
")",
"{",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"this",
".",
"mongoId",
"&&",
"!",
"ObjectID",
".",
"isValid",
"(",
"id",
")",
")",
"{",
"res",
".",
"badRequest",
"(",
")",
";",
"return",
"next",
"(",
")",
";",
"}",
"this",
".",
"model",
".",
"findOne",
"(",
"{",
"'_id'",
":",
"id",
"}",
",",
"function",
"(",
"err",
",",
"doc",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"err",
")",
";",
"}",
"if",
"(",
"!",
"doc",
")",
"{",
"res",
".",
"notFound",
"(",
")",
";",
"return",
"next",
"(",
"'route'",
")",
";",
"}",
"req",
"[",
"self",
".",
"paramName",
"]",
"=",
"doc",
";",
"return",
"next",
"(",
")",
";",
"}",
")",
";",
"}"
]
| Register the default id parameter for route requests.
Add a property to the current request which is the
document returned by the controller Model for the param configures
paramter name available in the processed request.
@param {http.IncomingMessage} req - The request message object
@param {http.ServerResponse} res - The outgoing response object
@param next {function} - The next handler function to call when done
@param id {String} - The id parameter parsed from the current request
@returns {function} This function sets a status of 400 for malformed MongoDB
id's and a status of 404 if no document has been found for the passed
parameter value. Calls the passed next function when done. | [
"Register",
"the",
"default",
"id",
"parameter",
"for",
"route",
"requests",
".",
"Add",
"a",
"property",
"to",
"the",
"current",
"request",
"which",
"is",
"the",
"document",
"returned",
"by",
"the",
"controller",
"Model",
"for",
"the",
"param",
"configures",
"paramter",
"name",
"available",
"in",
"the",
"processed",
"request",
"."
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/controllers/param.controller.js#L173-L196 | train |
|
michaelkrone/generator-material-app | generators/app/templates/client/app/components/toggle-component/toggle-component.service.js | ToggleComponentService | function ToggleComponentService($mdComponentRegistry, $log, $q) {
return function (contentHandle) {
var errorMsg = "ToggleComponent '" + contentHandle + "' is not available!";
var instance = $mdComponentRegistry.get(contentHandle);
if (!instance) {
$log.error('No content-switch found for handle ' + contentHandle);
}
return {
isOpen: isOpen,
toggle: toggle,
open: open,
close: close
};
function isOpen() {
return instance && instance.isOpen();
}
function toggle() {
return instance ? instance.toggle() : $q.reject(errorMsg);
}
function open() {
return instance ? instance.open() : $q.reject(errorMsg);
}
function close() {
return instance ? instance.close() : $q.reject(errorMsg);
}
};
} | javascript | function ToggleComponentService($mdComponentRegistry, $log, $q) {
return function (contentHandle) {
var errorMsg = "ToggleComponent '" + contentHandle + "' is not available!";
var instance = $mdComponentRegistry.get(contentHandle);
if (!instance) {
$log.error('No content-switch found for handle ' + contentHandle);
}
return {
isOpen: isOpen,
toggle: toggle,
open: open,
close: close
};
function isOpen() {
return instance && instance.isOpen();
}
function toggle() {
return instance ? instance.toggle() : $q.reject(errorMsg);
}
function open() {
return instance ? instance.open() : $q.reject(errorMsg);
}
function close() {
return instance ? instance.close() : $q.reject(errorMsg);
}
};
} | [
"function",
"ToggleComponentService",
"(",
"$mdComponentRegistry",
",",
"$log",
",",
"$q",
")",
"{",
"return",
"function",
"(",
"contentHandle",
")",
"{",
"var",
"errorMsg",
"=",
"\"ToggleComponent '\"",
"+",
"contentHandle",
"+",
"\"' is not available!\"",
";",
"var",
"instance",
"=",
"$mdComponentRegistry",
".",
"get",
"(",
"contentHandle",
")",
";",
"if",
"(",
"!",
"instance",
")",
"{",
"$log",
".",
"error",
"(",
"'No content-switch found for handle '",
"+",
"contentHandle",
")",
";",
"}",
"return",
"{",
"isOpen",
":",
"isOpen",
",",
"toggle",
":",
"toggle",
",",
"open",
":",
"open",
",",
"close",
":",
"close",
"}",
";",
"function",
"isOpen",
"(",
")",
"{",
"return",
"instance",
"&&",
"instance",
".",
"isOpen",
"(",
")",
";",
"}",
"function",
"toggle",
"(",
")",
"{",
"return",
"instance",
"?",
"instance",
".",
"toggle",
"(",
")",
":",
"$q",
".",
"reject",
"(",
"errorMsg",
")",
";",
"}",
"function",
"open",
"(",
")",
"{",
"return",
"instance",
"?",
"instance",
".",
"open",
"(",
")",
":",
"$q",
".",
"reject",
"(",
"errorMsg",
")",
";",
"}",
"function",
"close",
"(",
")",
"{",
"return",
"instance",
"?",
"instance",
".",
"close",
"(",
")",
":",
"$q",
".",
"reject",
"(",
"errorMsg",
")",
";",
"}",
"}",
";",
"}"
]
| ToggleComponent constructor
AngularJS will instantiate a singleton by calling "new" on this function
@ngdoc controller
@name ToggleComponentService
@module <%= scriptAppName %>.toggleComponent
@returns {Object} The service definition for the ToggleComponent Service | [
"ToggleComponent",
"constructor",
"AngularJS",
"will",
"instantiate",
"a",
"singleton",
"by",
"calling",
"new",
"on",
"this",
"function"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/components/toggle-component/toggle-component.service.js#L26-L58 | train |
michaelkrone/generator-material-app | generators/app/templates/server/lib/auth(auth)/auth.service.js | isAuthenticated | function isAuthenticated() {
return compose()
// Validate jwt
.use(function (req, res, next) {
// allow access_token to be passed through query parameter as well
if (req.query && req.query.hasOwnProperty('access_token')) {
req.headers.authorization = 'Bearer ' + req.query.access_token;
}
validateJwt(req, res, next);
})
.use(function (req, res, next) { // Attach userInfo to request
// return if this request has already been authorized
if (req.hasOwnProperty('userInfo')) {
return next();
}
// load user model on demand
var User = require('../../api/user/user.model').model;
// read the user id from the token information provided in req.user
User.findOne({_id: req.user._id, active: true}, function (err, user) {
if (err) {
return next(err);
}
if (!user) {
res.unauthorized();
return next();
}
// set the requests userInfo object as the authenticated user
req.userInfo = user;
next();
});
});
} | javascript | function isAuthenticated() {
return compose()
// Validate jwt
.use(function (req, res, next) {
// allow access_token to be passed through query parameter as well
if (req.query && req.query.hasOwnProperty('access_token')) {
req.headers.authorization = 'Bearer ' + req.query.access_token;
}
validateJwt(req, res, next);
})
.use(function (req, res, next) { // Attach userInfo to request
// return if this request has already been authorized
if (req.hasOwnProperty('userInfo')) {
return next();
}
// load user model on demand
var User = require('../../api/user/user.model').model;
// read the user id from the token information provided in req.user
User.findOne({_id: req.user._id, active: true}, function (err, user) {
if (err) {
return next(err);
}
if (!user) {
res.unauthorized();
return next();
}
// set the requests userInfo object as the authenticated user
req.userInfo = user;
next();
});
});
} | [
"function",
"isAuthenticated",
"(",
")",
"{",
"return",
"compose",
"(",
")",
".",
"use",
"(",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"req",
".",
"query",
"&&",
"req",
".",
"query",
".",
"hasOwnProperty",
"(",
"'access_token'",
")",
")",
"{",
"req",
".",
"headers",
".",
"authorization",
"=",
"'Bearer '",
"+",
"req",
".",
"query",
".",
"access_token",
";",
"}",
"validateJwt",
"(",
"req",
",",
"res",
",",
"next",
")",
";",
"}",
")",
".",
"use",
"(",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"req",
".",
"hasOwnProperty",
"(",
"'userInfo'",
")",
")",
"{",
"return",
"next",
"(",
")",
";",
"}",
"var",
"User",
"=",
"require",
"(",
"'../../api/user/user.model'",
")",
".",
"model",
";",
"User",
".",
"findOne",
"(",
"{",
"_id",
":",
"req",
".",
"user",
".",
"_id",
",",
"active",
":",
"true",
"}",
",",
"function",
"(",
"err",
",",
"user",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"err",
")",
";",
"}",
"if",
"(",
"!",
"user",
")",
"{",
"res",
".",
"unauthorized",
"(",
")",
";",
"return",
"next",
"(",
")",
";",
"}",
"req",
".",
"userInfo",
"=",
"user",
";",
"next",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Attaches the user object to the request if authenticated otherwise returns 403
@return {express.middleware} | [
"Attaches",
"the",
"user",
"object",
"to",
"the",
"request",
"if",
"authenticated",
"otherwise",
"returns",
"403"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/auth(auth)/auth.service.js#L64-L101 | train |
michaelkrone/generator-material-app | generators/app/templates/server/lib/auth(auth)/auth.service.js | hasRole | function hasRole(roleRequired) {
if (!roleRequired) {
throw new Error('Required role needs to be set');
}
return compose()
.use(isAuthenticated())
.use(function meetsRequirements(req, res, next) {
if (roles.hasRole(req.userInfo.role, roleRequired)) {
next();
} else {
res.forbidden();
}
});
} | javascript | function hasRole(roleRequired) {
if (!roleRequired) {
throw new Error('Required role needs to be set');
}
return compose()
.use(isAuthenticated())
.use(function meetsRequirements(req, res, next) {
if (roles.hasRole(req.userInfo.role, roleRequired)) {
next();
} else {
res.forbidden();
}
});
} | [
"function",
"hasRole",
"(",
"roleRequired",
")",
"{",
"if",
"(",
"!",
"roleRequired",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Required role needs to be set'",
")",
";",
"}",
"return",
"compose",
"(",
")",
".",
"use",
"(",
"isAuthenticated",
"(",
")",
")",
".",
"use",
"(",
"function",
"meetsRequirements",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"roles",
".",
"hasRole",
"(",
"req",
".",
"userInfo",
".",
"role",
",",
"roleRequired",
")",
")",
"{",
"next",
"(",
")",
";",
"}",
"else",
"{",
"res",
".",
"forbidden",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Checks if the user role meets the minimum requirements of the route, sets
the response status to FORBIDDEN if the requirements do not match.
@param {String} roleRequired - Name of the required role
@return {ServerResponse} | [
"Checks",
"if",
"the",
"user",
"role",
"meets",
"the",
"minimum",
"requirements",
"of",
"the",
"route",
"sets",
"the",
"response",
"status",
"to",
"FORBIDDEN",
"if",
"the",
"requirements",
"do",
"not",
"match",
"."
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/auth(auth)/auth.service.js#L109-L123 | train |
michaelkrone/generator-material-app | generators/app/templates/server/lib/auth(auth)/auth.service.js | signToken | function signToken(id, role) {
return jwt.sign({_id: id, role: role}, config.secrets.session, {expiresInMinutes: 60 * 5});
} | javascript | function signToken(id, role) {
return jwt.sign({_id: id, role: role}, config.secrets.session, {expiresInMinutes: 60 * 5});
} | [
"function",
"signToken",
"(",
"id",
",",
"role",
")",
"{",
"return",
"jwt",
".",
"sign",
"(",
"{",
"_id",
":",
"id",
",",
"role",
":",
"role",
"}",
",",
"config",
".",
"secrets",
".",
"session",
",",
"{",
"expiresInMinutes",
":",
"60",
"*",
"5",
"}",
")",
";",
"}"
]
| Returns a jwt token signed by the app secret
@param {String} id - Id used to sign a token
@return {String} | [
"Returns",
"a",
"jwt",
"token",
"signed",
"by",
"the",
"app",
"secret"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/auth(auth)/auth.service.js#L130-L132 | train |
michaelkrone/generator-material-app | generators/app/templates/server/lib/auth(auth)/auth.service.js | addAuthContext | function addAuthContext(namespace) {
if (!namespace) {
throw new Error('No context namespace specified!');
}
return function addAuthContextMiddleWare(req, res, next) {
contextService.setContext(namespace, req.userInfo);
next();
};
} | javascript | function addAuthContext(namespace) {
if (!namespace) {
throw new Error('No context namespace specified!');
}
return function addAuthContextMiddleWare(req, res, next) {
contextService.setContext(namespace, req.userInfo);
next();
};
} | [
"function",
"addAuthContext",
"(",
"namespace",
")",
"{",
"if",
"(",
"!",
"namespace",
")",
"{",
"throw",
"new",
"Error",
"(",
"'No context namespace specified!'",
")",
";",
"}",
"return",
"function",
"addAuthContextMiddleWare",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"contextService",
".",
"setContext",
"(",
"namespace",
",",
"req",
".",
"userInfo",
")",
";",
"next",
"(",
")",
";",
"}",
";",
"}"
]
| Add the current user object to the request context as the given name
@param {http.IncomingMessage} req - The request message object
@param {ServerResponse} res - The outgoing response object
@param {function} next - The next handler callback | [
"Add",
"the",
"current",
"user",
"object",
"to",
"the",
"request",
"context",
"as",
"the",
"given",
"name"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/auth(auth)/auth.service.js#L158-L167 | train |
michaelkrone/generator-material-app | generators/app/templates/client/app/components/auth(auth)/authinterceptor.service.js | request | function request(config) {
config.headers = config.headers || {};
if ($cookieStore.get('token')) {
config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
}
return config;
} | javascript | function request(config) {
config.headers = config.headers || {};
if ($cookieStore.get('token')) {
config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
}
return config;
} | [
"function",
"request",
"(",
"config",
")",
"{",
"config",
".",
"headers",
"=",
"config",
".",
"headers",
"||",
"{",
"}",
";",
"if",
"(",
"$cookieStore",
".",
"get",
"(",
"'token'",
")",
")",
"{",
"config",
".",
"headers",
".",
"Authorization",
"=",
"'Bearer '",
"+",
"$cookieStore",
".",
"get",
"(",
"'token'",
")",
";",
"}",
"return",
"config",
";",
"}"
]
| Add authorization token to headers | [
"Add",
"authorization",
"token",
"to",
"headers"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/components/auth(auth)/authinterceptor.service.js#L68-L74 | train |
michaelkrone/generator-material-app | generators/app/templates/client/app/components/auth(auth)/authinterceptor.service.js | responseError | function responseError(response) {
if (response.status === 401) {
// remove any stale tokens
$cookieStore.remove('token');
// use timeout to perform location change
// in the next digest cycle
$timeout(function () {
$location.path('/login');
}, 0);
return $q.reject(response);
}
return $q.reject(response);
} | javascript | function responseError(response) {
if (response.status === 401) {
// remove any stale tokens
$cookieStore.remove('token');
// use timeout to perform location change
// in the next digest cycle
$timeout(function () {
$location.path('/login');
}, 0);
return $q.reject(response);
}
return $q.reject(response);
} | [
"function",
"responseError",
"(",
"response",
")",
"{",
"if",
"(",
"response",
".",
"status",
"===",
"401",
")",
"{",
"$cookieStore",
".",
"remove",
"(",
"'token'",
")",
";",
"$timeout",
"(",
"function",
"(",
")",
"{",
"$location",
".",
"path",
"(",
"'/login'",
")",
";",
"}",
",",
"0",
")",
";",
"return",
"$q",
".",
"reject",
"(",
"response",
")",
";",
"}",
"return",
"$q",
".",
"reject",
"(",
"response",
")",
";",
"}"
]
| Intercept 401s and redirect you to login | [
"Intercept",
"401s",
"and",
"redirect",
"you",
"to",
"login"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/components/auth(auth)/authinterceptor.service.js#L77-L91 | train |
michaelkrone/generator-material-app | generators/app/templates/server/config/express.js | initExpress | function initExpress(app) {
var env = app.get('env');
var publicDir = path.join(config.root, config.publicDir);
app.set('ip', config.ip);
app.set('port', config.port);
app.set('views', config.root + '/server/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(compression());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(cookieParser());
app.use(passport.initialize());
app.use(favicon(path.join(publicDir, 'favicon.ico')));
if ('production' === env) {
app.use(express.static(publicDir));
app.set('appPath', publicDir);
app.use(morgan('tiny'));
}
if ('development' === env || 'test' === env) {
app.use(express.static(path.join(config.root, '.tmp')));
app.use(express.static(publicDir));
app.set('appPath', publicDir);
app.use(morgan('dev'));
// Error handler - has to be last
app.use(errorHandler());
}
} | javascript | function initExpress(app) {
var env = app.get('env');
var publicDir = path.join(config.root, config.publicDir);
app.set('ip', config.ip);
app.set('port', config.port);
app.set('views', config.root + '/server/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(compression());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(cookieParser());
app.use(passport.initialize());
app.use(favicon(path.join(publicDir, 'favicon.ico')));
if ('production' === env) {
app.use(express.static(publicDir));
app.set('appPath', publicDir);
app.use(morgan('tiny'));
}
if ('development' === env || 'test' === env) {
app.use(express.static(path.join(config.root, '.tmp')));
app.use(express.static(publicDir));
app.set('appPath', publicDir);
app.use(morgan('dev'));
// Error handler - has to be last
app.use(errorHandler());
}
} | [
"function",
"initExpress",
"(",
"app",
")",
"{",
"var",
"env",
"=",
"app",
".",
"get",
"(",
"'env'",
")",
";",
"var",
"publicDir",
"=",
"path",
".",
"join",
"(",
"config",
".",
"root",
",",
"config",
".",
"publicDir",
")",
";",
"app",
".",
"set",
"(",
"'ip'",
",",
"config",
".",
"ip",
")",
";",
"app",
".",
"set",
"(",
"'port'",
",",
"config",
".",
"port",
")",
";",
"app",
".",
"set",
"(",
"'views'",
",",
"config",
".",
"root",
"+",
"'/server/views'",
")",
";",
"app",
".",
"engine",
"(",
"'html'",
",",
"require",
"(",
"'ejs'",
")",
".",
"renderFile",
")",
";",
"app",
".",
"set",
"(",
"'view engine'",
",",
"'html'",
")",
";",
"app",
".",
"use",
"(",
"compression",
"(",
")",
")",
";",
"app",
".",
"use",
"(",
"bodyParser",
".",
"urlencoded",
"(",
"{",
"extended",
":",
"false",
"}",
")",
")",
";",
"app",
".",
"use",
"(",
"bodyParser",
".",
"json",
"(",
")",
")",
";",
"app",
".",
"use",
"(",
"methodOverride",
"(",
")",
")",
";",
"app",
".",
"use",
"(",
"cookieParser",
"(",
")",
")",
";",
"app",
".",
"use",
"(",
"passport",
".",
"initialize",
"(",
")",
")",
";",
"app",
".",
"use",
"(",
"favicon",
"(",
"path",
".",
"join",
"(",
"publicDir",
",",
"'favicon.ico'",
")",
")",
")",
";",
"if",
"(",
"'production'",
"===",
"env",
")",
"{",
"app",
".",
"use",
"(",
"express",
".",
"static",
"(",
"publicDir",
")",
")",
";",
"app",
".",
"set",
"(",
"'appPath'",
",",
"publicDir",
")",
";",
"app",
".",
"use",
"(",
"morgan",
"(",
"'tiny'",
")",
")",
";",
"}",
"if",
"(",
"'development'",
"===",
"env",
"||",
"'test'",
"===",
"env",
")",
"{",
"app",
".",
"use",
"(",
"express",
".",
"static",
"(",
"path",
".",
"join",
"(",
"config",
".",
"root",
",",
"'.tmp'",
")",
")",
")",
";",
"app",
".",
"use",
"(",
"express",
".",
"static",
"(",
"publicDir",
")",
")",
";",
"app",
".",
"set",
"(",
"'appPath'",
",",
"publicDir",
")",
";",
"app",
".",
"use",
"(",
"morgan",
"(",
"'dev'",
")",
")",
";",
"app",
".",
"use",
"(",
"errorHandler",
"(",
")",
")",
";",
"}",
"}"
]
| Configure the express application by adding middleware and setting application
variables.
@param {express.app} app - The express application instance to configure | [
"Configure",
"the",
"express",
"application",
"by",
"adding",
"middleware",
"and",
"setting",
"application",
"variables",
"."
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/config/express.js#L29-L62 | train |
michaelkrone/generator-material-app | generators/app/templates/client/app/components/socket(socketio)/socket.service.js | syncUpdates | function syncUpdates(modelName, array, cb) {
cb = cb || angular.noop;
/**
* Syncs item creation/updates on 'model:save'
*/
socket.on(modelName + ':save', function (item) {
var index = _.findIndex(array, {_id: item._id});
var event = 'created';
// replace oldItem if it exists
// otherwise just add item to the collection
if (index !== -1) {
array.splice(index, 1, item);
event = 'updated';
} else {
array.push(item);
}
cb(event, item, array);
});
/**
* Syncs removed items on 'model:remove'
*/
socket.on(modelName + ':remove', function (item) {
var event = 'deleted';
_.remove(array, {_id: item._id});
cb(event, item, array);
});
} | javascript | function syncUpdates(modelName, array, cb) {
cb = cb || angular.noop;
/**
* Syncs item creation/updates on 'model:save'
*/
socket.on(modelName + ':save', function (item) {
var index = _.findIndex(array, {_id: item._id});
var event = 'created';
// replace oldItem if it exists
// otherwise just add item to the collection
if (index !== -1) {
array.splice(index, 1, item);
event = 'updated';
} else {
array.push(item);
}
cb(event, item, array);
});
/**
* Syncs removed items on 'model:remove'
*/
socket.on(modelName + ':remove', function (item) {
var event = 'deleted';
_.remove(array, {_id: item._id});
cb(event, item, array);
});
} | [
"function",
"syncUpdates",
"(",
"modelName",
",",
"array",
",",
"cb",
")",
"{",
"cb",
"=",
"cb",
"||",
"angular",
".",
"noop",
";",
"socket",
".",
"on",
"(",
"modelName",
"+",
"':save'",
",",
"function",
"(",
"item",
")",
"{",
"var",
"index",
"=",
"_",
".",
"findIndex",
"(",
"array",
",",
"{",
"_id",
":",
"item",
".",
"_id",
"}",
")",
";",
"var",
"event",
"=",
"'created'",
";",
"if",
"(",
"index",
"!==",
"-",
"1",
")",
"{",
"array",
".",
"splice",
"(",
"index",
",",
"1",
",",
"item",
")",
";",
"event",
"=",
"'updated'",
";",
"}",
"else",
"{",
"array",
".",
"push",
"(",
"item",
")",
";",
"}",
"cb",
"(",
"event",
",",
"item",
",",
"array",
")",
";",
"}",
")",
";",
"socket",
".",
"on",
"(",
"modelName",
"+",
"':remove'",
",",
"function",
"(",
"item",
")",
"{",
"var",
"event",
"=",
"'deleted'",
";",
"_",
".",
"remove",
"(",
"array",
",",
"{",
"_id",
":",
"item",
".",
"_id",
"}",
")",
";",
"cb",
"(",
"event",
",",
"item",
",",
"array",
")",
";",
"}",
")",
";",
"}"
]
| Register listeners to sync an array with updates on a model
Takes the array we want to sync, the model name that socket updates are sent from,
and an optional callback function after new items are updated.
@param {String} modelName
@param {Array} array
@param {Function} cb | [
"Register",
"listeners",
"to",
"sync",
"an",
"array",
"with",
"updates",
"on",
"a",
"model"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/components/socket(socketio)/socket.service.js#L46-L76 | train |
michaelkrone/generator-material-app | generators/app/templates/server/api/user(auth)/user.socket(socketio).js | registerUserSockets | function registerUserSockets(socket) {
User.schema.post('save', function (doc) {
onSave(socket, doc);
});
User.schema.post('remove', function (doc) {
onRemove(socket, doc);
});
} | javascript | function registerUserSockets(socket) {
User.schema.post('save', function (doc) {
onSave(socket, doc);
});
User.schema.post('remove', function (doc) {
onRemove(socket, doc);
});
} | [
"function",
"registerUserSockets",
"(",
"socket",
")",
"{",
"User",
".",
"schema",
".",
"post",
"(",
"'save'",
",",
"function",
"(",
"doc",
")",
"{",
"onSave",
"(",
"socket",
",",
"doc",
")",
";",
"}",
")",
";",
"User",
".",
"schema",
".",
"post",
"(",
"'remove'",
",",
"function",
"(",
"doc",
")",
"{",
"onRemove",
"(",
"socket",
",",
"doc",
")",
";",
"}",
")",
";",
"}"
]
| Register User model change events on the passed socket
@param {socket.io} socket - The socket object to register the User model events on | [
"Register",
"User",
"model",
"change",
"events",
"on",
"the",
"passed",
"socket"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/api/user(auth)/user.socket(socketio).js#L24-L32 | train |
michaelkrone/generator-material-app | generators/app/templates/client/app/admin(auth)/user/list/edit/edit.controller.js | update | function update(form) {
// refuse to work with invalid data
if (!vm.user._id || form && !form.$valid) {
return;
}
UserService.update(vm.user)
.then(updateUserSuccess)
.catch(updateUserCatch);
function updateUserSuccess(updatedUser) {
// update the display name after successful save
vm.displayName = updatedUser.name;
Toast.show({text: 'User ' + updatedUser.name + ' updated'});
if (form) {
form.$setPristine();
}
}
function updateUserCatch(err) {
Toast.show({
type: 'warn',
text: 'Error while updating user ' + vm.displayName,
link: {state: $state.$current, params: $stateParams}
});
if (form && err) {
form.setResponseErrors(err.data);
}
}
} | javascript | function update(form) {
// refuse to work with invalid data
if (!vm.user._id || form && !form.$valid) {
return;
}
UserService.update(vm.user)
.then(updateUserSuccess)
.catch(updateUserCatch);
function updateUserSuccess(updatedUser) {
// update the display name after successful save
vm.displayName = updatedUser.name;
Toast.show({text: 'User ' + updatedUser.name + ' updated'});
if (form) {
form.$setPristine();
}
}
function updateUserCatch(err) {
Toast.show({
type: 'warn',
text: 'Error while updating user ' + vm.displayName,
link: {state: $state.$current, params: $stateParams}
});
if (form && err) {
form.setResponseErrors(err.data);
}
}
} | [
"function",
"update",
"(",
"form",
")",
"{",
"if",
"(",
"!",
"vm",
".",
"user",
".",
"_id",
"||",
"form",
"&&",
"!",
"form",
".",
"$valid",
")",
"{",
"return",
";",
"}",
"UserService",
".",
"update",
"(",
"vm",
".",
"user",
")",
".",
"then",
"(",
"updateUserSuccess",
")",
".",
"catch",
"(",
"updateUserCatch",
")",
";",
"function",
"updateUserSuccess",
"(",
"updatedUser",
")",
"{",
"vm",
".",
"displayName",
"=",
"updatedUser",
".",
"name",
";",
"Toast",
".",
"show",
"(",
"{",
"text",
":",
"'User '",
"+",
"updatedUser",
".",
"name",
"+",
"' updated'",
"}",
")",
";",
"if",
"(",
"form",
")",
"{",
"form",
".",
"$setPristine",
"(",
")",
";",
"}",
"}",
"function",
"updateUserCatch",
"(",
"err",
")",
"{",
"Toast",
".",
"show",
"(",
"{",
"type",
":",
"'warn'",
",",
"text",
":",
"'Error while updating user '",
"+",
"vm",
".",
"displayName",
",",
"link",
":",
"{",
"state",
":",
"$state",
".",
"$current",
",",
"params",
":",
"$stateParams",
"}",
"}",
")",
";",
"if",
"(",
"form",
"&&",
"err",
")",
"{",
"form",
".",
"setResponseErrors",
"(",
"err",
".",
"data",
")",
";",
"}",
"}",
"}"
]
| Updates a user by using the UserService save method
@param {Form} [form] | [
"Updates",
"a",
"user",
"by",
"using",
"the",
"UserService",
"save",
"method"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/admin(auth)/user/list/edit/edit.controller.js#L72-L102 | train |
michaelkrone/generator-material-app | generators/app/templates/client/app/admin(auth)/user/list/edit/edit.controller.js | remove | function remove(form, ev) {
var confirm = $mdDialog.confirm()
.title('Delete user ' + vm.displayName + '?')
.content('Do you really want to delete user ' + vm.displayName + '?')
.ariaLabel('Delete user')
.ok('Delete user')
.cancel('Cancel')
.targetEvent(ev);
$mdDialog.show(confirm)
.then(performRemove);
/**
* Removes a user by using the UserService remove method
* @api private
*/
function performRemove() {
UserService.remove(vm.user)
.then(deleteUserSuccess)
.catch(deleteUserCatch);
function deleteUserSuccess() {
Toast.show({type: 'success', text: 'User ' + vm.displayName + ' deleted'});
vm.showList();
}
function deleteUserCatch(err) {
Toast.show({
type: 'warn',
text: 'Error while deleting user ' + vm.displayName,
link: {state: $state.$current, params: $stateParams}
});
if (form && err) {
form.setResponseErrors(err, vm.errors);
}
}
}
} | javascript | function remove(form, ev) {
var confirm = $mdDialog.confirm()
.title('Delete user ' + vm.displayName + '?')
.content('Do you really want to delete user ' + vm.displayName + '?')
.ariaLabel('Delete user')
.ok('Delete user')
.cancel('Cancel')
.targetEvent(ev);
$mdDialog.show(confirm)
.then(performRemove);
/**
* Removes a user by using the UserService remove method
* @api private
*/
function performRemove() {
UserService.remove(vm.user)
.then(deleteUserSuccess)
.catch(deleteUserCatch);
function deleteUserSuccess() {
Toast.show({type: 'success', text: 'User ' + vm.displayName + ' deleted'});
vm.showList();
}
function deleteUserCatch(err) {
Toast.show({
type: 'warn',
text: 'Error while deleting user ' + vm.displayName,
link: {state: $state.$current, params: $stateParams}
});
if (form && err) {
form.setResponseErrors(err, vm.errors);
}
}
}
} | [
"function",
"remove",
"(",
"form",
",",
"ev",
")",
"{",
"var",
"confirm",
"=",
"$mdDialog",
".",
"confirm",
"(",
")",
".",
"title",
"(",
"'Delete user '",
"+",
"vm",
".",
"displayName",
"+",
"'?'",
")",
".",
"content",
"(",
"'Do you really want to delete user '",
"+",
"vm",
".",
"displayName",
"+",
"'?'",
")",
".",
"ariaLabel",
"(",
"'Delete user'",
")",
".",
"ok",
"(",
"'Delete user'",
")",
".",
"cancel",
"(",
"'Cancel'",
")",
".",
"targetEvent",
"(",
"ev",
")",
";",
"$mdDialog",
".",
"show",
"(",
"confirm",
")",
".",
"then",
"(",
"performRemove",
")",
";",
"function",
"performRemove",
"(",
")",
"{",
"UserService",
".",
"remove",
"(",
"vm",
".",
"user",
")",
".",
"then",
"(",
"deleteUserSuccess",
")",
".",
"catch",
"(",
"deleteUserCatch",
")",
";",
"function",
"deleteUserSuccess",
"(",
")",
"{",
"Toast",
".",
"show",
"(",
"{",
"type",
":",
"'success'",
",",
"text",
":",
"'User '",
"+",
"vm",
".",
"displayName",
"+",
"' deleted'",
"}",
")",
";",
"vm",
".",
"showList",
"(",
")",
";",
"}",
"function",
"deleteUserCatch",
"(",
"err",
")",
"{",
"Toast",
".",
"show",
"(",
"{",
"type",
":",
"'warn'",
",",
"text",
":",
"'Error while deleting user '",
"+",
"vm",
".",
"displayName",
",",
"link",
":",
"{",
"state",
":",
"$state",
".",
"$current",
",",
"params",
":",
"$stateParams",
"}",
"}",
")",
";",
"if",
"(",
"form",
"&&",
"err",
")",
"{",
"form",
".",
"setResponseErrors",
"(",
"err",
",",
"vm",
".",
"errors",
")",
";",
"}",
"}",
"}",
"}"
]
| Show a dialog to ask the user if she wants to delete the current selected user.
@param {AngularForm} form - The form to pass to the remove handler
@param {$event} ev - The event to pass to the dialog service | [
"Show",
"a",
"dialog",
"to",
"ask",
"the",
"user",
"if",
"she",
"wants",
"to",
"delete",
"the",
"current",
"selected",
"user",
"."
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/admin(auth)/user/list/edit/edit.controller.js#L109-L147 | train |
michaelkrone/generator-material-app | generators/app/templates/client/app/admin(auth)/user/list/edit/edit.controller.js | performRemove | function performRemove() {
UserService.remove(vm.user)
.then(deleteUserSuccess)
.catch(deleteUserCatch);
function deleteUserSuccess() {
Toast.show({type: 'success', text: 'User ' + vm.displayName + ' deleted'});
vm.showList();
}
function deleteUserCatch(err) {
Toast.show({
type: 'warn',
text: 'Error while deleting user ' + vm.displayName,
link: {state: $state.$current, params: $stateParams}
});
if (form && err) {
form.setResponseErrors(err, vm.errors);
}
}
} | javascript | function performRemove() {
UserService.remove(vm.user)
.then(deleteUserSuccess)
.catch(deleteUserCatch);
function deleteUserSuccess() {
Toast.show({type: 'success', text: 'User ' + vm.displayName + ' deleted'});
vm.showList();
}
function deleteUserCatch(err) {
Toast.show({
type: 'warn',
text: 'Error while deleting user ' + vm.displayName,
link: {state: $state.$current, params: $stateParams}
});
if (form && err) {
form.setResponseErrors(err, vm.errors);
}
}
} | [
"function",
"performRemove",
"(",
")",
"{",
"UserService",
".",
"remove",
"(",
"vm",
".",
"user",
")",
".",
"then",
"(",
"deleteUserSuccess",
")",
".",
"catch",
"(",
"deleteUserCatch",
")",
";",
"function",
"deleteUserSuccess",
"(",
")",
"{",
"Toast",
".",
"show",
"(",
"{",
"type",
":",
"'success'",
",",
"text",
":",
"'User '",
"+",
"vm",
".",
"displayName",
"+",
"' deleted'",
"}",
")",
";",
"vm",
".",
"showList",
"(",
")",
";",
"}",
"function",
"deleteUserCatch",
"(",
"err",
")",
"{",
"Toast",
".",
"show",
"(",
"{",
"type",
":",
"'warn'",
",",
"text",
":",
"'Error while deleting user '",
"+",
"vm",
".",
"displayName",
",",
"link",
":",
"{",
"state",
":",
"$state",
".",
"$current",
",",
"params",
":",
"$stateParams",
"}",
"}",
")",
";",
"if",
"(",
"form",
"&&",
"err",
")",
"{",
"form",
".",
"setResponseErrors",
"(",
"err",
",",
"vm",
".",
"errors",
")",
";",
"}",
"}",
"}"
]
| Removes a user by using the UserService remove method
@api private | [
"Removes",
"a",
"user",
"by",
"using",
"the",
"UserService",
"remove",
"method"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/admin(auth)/user/list/edit/edit.controller.js#L125-L146 | train |
michaelkrone/generator-material-app | generators/app/templates/client/app/admin(auth)/user/list/edit/edit.controller.js | showChangePasswordDialog | function showChangePasswordDialog(event) {
$mdDialog.show({
controller: 'EditPasswordController',
controllerAs: 'password',
templateUrl: 'app/admin/user/list/edit/edit-password/edit-password.html',
targetEvent: event,
locals: {user: vm.user},
bindToController: true,
clickOutsideToClose: false
});
} | javascript | function showChangePasswordDialog(event) {
$mdDialog.show({
controller: 'EditPasswordController',
controllerAs: 'password',
templateUrl: 'app/admin/user/list/edit/edit-password/edit-password.html',
targetEvent: event,
locals: {user: vm.user},
bindToController: true,
clickOutsideToClose: false
});
} | [
"function",
"showChangePasswordDialog",
"(",
"event",
")",
"{",
"$mdDialog",
".",
"show",
"(",
"{",
"controller",
":",
"'EditPasswordController'",
",",
"controllerAs",
":",
"'password'",
",",
"templateUrl",
":",
"'app/admin/user/list/edit/edit-password/edit-password.html'",
",",
"targetEvent",
":",
"event",
",",
"locals",
":",
"{",
"user",
":",
"vm",
".",
"user",
"}",
",",
"bindToController",
":",
"true",
",",
"clickOutsideToClose",
":",
"false",
"}",
")",
";",
"}"
]
| Show the dialog for changing the user password
@param event | [
"Show",
"the",
"dialog",
"for",
"changing",
"the",
"user",
"password"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/admin(auth)/user/list/edit/edit.controller.js#L153-L163 | train |
michaelkrone/generator-material-app | generators/app/templates/server/lib/responses/index.js | sendData | function sendData(data, options) {
// jshint validthis: true
var req = this.req;
var res = this.res;
// headers already sent, nothing to do here
if (res.headersSent) {
return;
}
// If appropriate, serve data as JSON
if (req.xhr || req.accepts('application/json')) {
return res.json(data);
}
// if a template string is given as the options param
// use it to render a view
var viewFilePath = (typeof options === 'string') ? options : options.view;
// try to render the given template, fall back to json
// if an error occurs while rendering the view file
if (viewFilePath && req.accepts('html')) {
res.render(viewFilePath, data, function (err, result) {
if (err) {
return res.json(data);
}
return res.send(result);
});
}
return res.json(data);
} | javascript | function sendData(data, options) {
// jshint validthis: true
var req = this.req;
var res = this.res;
// headers already sent, nothing to do here
if (res.headersSent) {
return;
}
// If appropriate, serve data as JSON
if (req.xhr || req.accepts('application/json')) {
return res.json(data);
}
// if a template string is given as the options param
// use it to render a view
var viewFilePath = (typeof options === 'string') ? options : options.view;
// try to render the given template, fall back to json
// if an error occurs while rendering the view file
if (viewFilePath && req.accepts('html')) {
res.render(viewFilePath, data, function (err, result) {
if (err) {
return res.json(data);
}
return res.send(result);
});
}
return res.json(data);
} | [
"function",
"sendData",
"(",
"data",
",",
"options",
")",
"{",
"var",
"req",
"=",
"this",
".",
"req",
";",
"var",
"res",
"=",
"this",
".",
"res",
";",
"if",
"(",
"res",
".",
"headersSent",
")",
"{",
"return",
";",
"}",
"if",
"(",
"req",
".",
"xhr",
"||",
"req",
".",
"accepts",
"(",
"'application/json'",
")",
")",
"{",
"return",
"res",
".",
"json",
"(",
"data",
")",
";",
"}",
"var",
"viewFilePath",
"=",
"(",
"typeof",
"options",
"===",
"'string'",
")",
"?",
"options",
":",
"options",
".",
"view",
";",
"if",
"(",
"viewFilePath",
"&&",
"req",
".",
"accepts",
"(",
"'html'",
")",
")",
"{",
"res",
".",
"render",
"(",
"viewFilePath",
",",
"data",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"res",
".",
"json",
"(",
"data",
")",
";",
"}",
"return",
"res",
".",
"send",
"(",
"result",
")",
";",
"}",
")",
";",
"}",
"return",
"res",
".",
"json",
"(",
"data",
")",
";",
"}"
]
| Default response output handler
@param {mixed} data - The data that should be send to the client
@param {Object|String} options - Response configuration object or view template name
@return A Response with the given status set, a rendered view if a view template has
been provided in the options paramter. | [
"Default",
"response",
"output",
"handler"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/responses/index.js#L26-L57 | train |
michaelkrone/generator-material-app | generators/app/templates/client/app/components/toggle-component/toggle-component.directive.js | toggleOpen | function toggleOpen(isOpen) {
if (scope.isOpen === isOpen) {
return $q.when(true);
}
var deferred = $q.defer();
// Toggle value to force an async `updateIsOpen()` to run
scope.isOpen = isOpen;
$timeout(setElementFocus, 0, false);
return deferred.promise;
function setElementFocus() {
// When the current `updateIsOpen()` animation finishes
promise.then(function (result) {
if (!scope.isOpen) {
// reset focus to originating element (if available) upon close
triggeringElement && triggeringElement.focus();
triggeringElement = null;
}
deferred.resolve(result);
});
}
} | javascript | function toggleOpen(isOpen) {
if (scope.isOpen === isOpen) {
return $q.when(true);
}
var deferred = $q.defer();
// Toggle value to force an async `updateIsOpen()` to run
scope.isOpen = isOpen;
$timeout(setElementFocus, 0, false);
return deferred.promise;
function setElementFocus() {
// When the current `updateIsOpen()` animation finishes
promise.then(function (result) {
if (!scope.isOpen) {
// reset focus to originating element (if available) upon close
triggeringElement && triggeringElement.focus();
triggeringElement = null;
}
deferred.resolve(result);
});
}
} | [
"function",
"toggleOpen",
"(",
"isOpen",
")",
"{",
"if",
"(",
"scope",
".",
"isOpen",
"===",
"isOpen",
")",
"{",
"return",
"$q",
".",
"when",
"(",
"true",
")",
";",
"}",
"var",
"deferred",
"=",
"$q",
".",
"defer",
"(",
")",
";",
"scope",
".",
"isOpen",
"=",
"isOpen",
";",
"$timeout",
"(",
"setElementFocus",
",",
"0",
",",
"false",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"function",
"setElementFocus",
"(",
")",
"{",
"promise",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"if",
"(",
"!",
"scope",
".",
"isOpen",
")",
"{",
"triggeringElement",
"&&",
"triggeringElement",
".",
"focus",
"(",
")",
";",
"triggeringElement",
"=",
"null",
";",
"}",
"deferred",
".",
"resolve",
"(",
"result",
")",
";",
"}",
")",
";",
"}",
"}"
]
| Toggle the toggleComponent view and publish a promise to be resolved when
the view animation finishes.
@param isOpen
@returns {*} | [
"Toggle",
"the",
"toggleComponent",
"view",
"and",
"publish",
"a",
"promise",
"to",
"be",
"resolved",
"when",
"the",
"view",
"animation",
"finishes",
"."
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/components/toggle-component/toggle-component.directive.js#L116-L139 | train |
michaelkrone/generator-material-app | generators/app/templates/client/app/clientModelDoc(demo)/clientModelDoc.service.js | ClientModelDocService | function ClientModelDocService(ClientModelDoc) {
return {
create: create,
update: update,
remove: remove
};
/**
* Save a new clientModelDoc
*
* @param {Object} clientModelDoc - clientModelDocData
* @param {Function} callback - optional
* @return {Promise}
*/
function create(clientModelDoc, callback) {
var cb = callback || angular.noop;
return ClientModelDoc.create(clientModelDoc,
function (clientModelDoc) {
return cb(clientModelDoc);
},
function (err) {
return cb(err);
}).$promise;
}
/**
* Remove a clientModelDoc
*
* @param {Object} clientModelDoc - clientModelDocData
* @param {Function} callback - optional
* @return {Promise}
*/
function remove(clientModelDoc, callback) {
var cb = callback || angular.noop;
return ClientModelDoc.remove({id: clientModelDoc._id},
function (clientModelDoc) {
return cb(clientModelDoc);
},
function (err) {
return cb(err);
}).$promise;
}
/**
* Create a new clientModelDoc
*
* @param {Object} clientModelDoc - clientModelDocData
* @param {Function} callback - optional
* @return {Promise}
*/
function update(clientModelDoc, callback) {
var cb = callback || angular.noop;
return ClientModelDoc.update(clientModelDoc,
function (clientModelDoc) {
return cb(clientModelDoc);
},
function (err) {
return cb(err);
}).$promise;
}
} | javascript | function ClientModelDocService(ClientModelDoc) {
return {
create: create,
update: update,
remove: remove
};
/**
* Save a new clientModelDoc
*
* @param {Object} clientModelDoc - clientModelDocData
* @param {Function} callback - optional
* @return {Promise}
*/
function create(clientModelDoc, callback) {
var cb = callback || angular.noop;
return ClientModelDoc.create(clientModelDoc,
function (clientModelDoc) {
return cb(clientModelDoc);
},
function (err) {
return cb(err);
}).$promise;
}
/**
* Remove a clientModelDoc
*
* @param {Object} clientModelDoc - clientModelDocData
* @param {Function} callback - optional
* @return {Promise}
*/
function remove(clientModelDoc, callback) {
var cb = callback || angular.noop;
return ClientModelDoc.remove({id: clientModelDoc._id},
function (clientModelDoc) {
return cb(clientModelDoc);
},
function (err) {
return cb(err);
}).$promise;
}
/**
* Create a new clientModelDoc
*
* @param {Object} clientModelDoc - clientModelDocData
* @param {Function} callback - optional
* @return {Promise}
*/
function update(clientModelDoc, callback) {
var cb = callback || angular.noop;
return ClientModelDoc.update(clientModelDoc,
function (clientModelDoc) {
return cb(clientModelDoc);
},
function (err) {
return cb(err);
}).$promise;
}
} | [
"function",
"ClientModelDocService",
"(",
"ClientModelDoc",
")",
"{",
"return",
"{",
"create",
":",
"create",
",",
"update",
":",
"update",
",",
"remove",
":",
"remove",
"}",
";",
"function",
"create",
"(",
"clientModelDoc",
",",
"callback",
")",
"{",
"var",
"cb",
"=",
"callback",
"||",
"angular",
".",
"noop",
";",
"return",
"ClientModelDoc",
".",
"create",
"(",
"clientModelDoc",
",",
"function",
"(",
"clientModelDoc",
")",
"{",
"return",
"cb",
"(",
"clientModelDoc",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
")",
".",
"$promise",
";",
"}",
"function",
"remove",
"(",
"clientModelDoc",
",",
"callback",
")",
"{",
"var",
"cb",
"=",
"callback",
"||",
"angular",
".",
"noop",
";",
"return",
"ClientModelDoc",
".",
"remove",
"(",
"{",
"id",
":",
"clientModelDoc",
".",
"_id",
"}",
",",
"function",
"(",
"clientModelDoc",
")",
"{",
"return",
"cb",
"(",
"clientModelDoc",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
")",
".",
"$promise",
";",
"}",
"function",
"update",
"(",
"clientModelDoc",
",",
"callback",
")",
"{",
"var",
"cb",
"=",
"callback",
"||",
"angular",
".",
"noop",
";",
"return",
"ClientModelDoc",
".",
"update",
"(",
"clientModelDoc",
",",
"function",
"(",
"clientModelDoc",
")",
"{",
"return",
"cb",
"(",
"clientModelDoc",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
")",
".",
"$promise",
";",
"}",
"}"
]
| ClientModelDocService constructor
AngularJS will instantiate a singleton by calling "new" on this function
@param {$resource} ClientModelDoc The resource provided by <%= scriptAppName %>.clientModelDoc.resource
@returns {Object} The service definition for the ClientModelDocService service | [
"ClientModelDocService",
"constructor",
"AngularJS",
"will",
"instantiate",
"a",
"singleton",
"by",
"calling",
"new",
"on",
"this",
"function"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/clientModelDoc(demo)/clientModelDoc.service.js#L40-L104 | train |
michaelkrone/generator-material-app | generators/app/templates/client/app/clientModelDoc(demo)/clientModelDoc.service.js | create | function create(clientModelDoc, callback) {
var cb = callback || angular.noop;
return ClientModelDoc.create(clientModelDoc,
function (clientModelDoc) {
return cb(clientModelDoc);
},
function (err) {
return cb(err);
}).$promise;
} | javascript | function create(clientModelDoc, callback) {
var cb = callback || angular.noop;
return ClientModelDoc.create(clientModelDoc,
function (clientModelDoc) {
return cb(clientModelDoc);
},
function (err) {
return cb(err);
}).$promise;
} | [
"function",
"create",
"(",
"clientModelDoc",
",",
"callback",
")",
"{",
"var",
"cb",
"=",
"callback",
"||",
"angular",
".",
"noop",
";",
"return",
"ClientModelDoc",
".",
"create",
"(",
"clientModelDoc",
",",
"function",
"(",
"clientModelDoc",
")",
"{",
"return",
"cb",
"(",
"clientModelDoc",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
")",
".",
"$promise",
";",
"}"
]
| Save a new clientModelDoc
@param {Object} clientModelDoc - clientModelDocData
@param {Function} callback - optional
@return {Promise} | [
"Save",
"a",
"new",
"clientModelDoc"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/clientModelDoc(demo)/clientModelDoc.service.js#L55-L65 | train |
michaelkrone/generator-material-app | generators/app/templates/client/app/clientModelDoc(demo)/clientModelDoc.service.js | remove | function remove(clientModelDoc, callback) {
var cb = callback || angular.noop;
return ClientModelDoc.remove({id: clientModelDoc._id},
function (clientModelDoc) {
return cb(clientModelDoc);
},
function (err) {
return cb(err);
}).$promise;
} | javascript | function remove(clientModelDoc, callback) {
var cb = callback || angular.noop;
return ClientModelDoc.remove({id: clientModelDoc._id},
function (clientModelDoc) {
return cb(clientModelDoc);
},
function (err) {
return cb(err);
}).$promise;
} | [
"function",
"remove",
"(",
"clientModelDoc",
",",
"callback",
")",
"{",
"var",
"cb",
"=",
"callback",
"||",
"angular",
".",
"noop",
";",
"return",
"ClientModelDoc",
".",
"remove",
"(",
"{",
"id",
":",
"clientModelDoc",
".",
"_id",
"}",
",",
"function",
"(",
"clientModelDoc",
")",
"{",
"return",
"cb",
"(",
"clientModelDoc",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
")",
".",
"$promise",
";",
"}"
]
| Remove a clientModelDoc
@param {Object} clientModelDoc - clientModelDocData
@param {Function} callback - optional
@return {Promise} | [
"Remove",
"a",
"clientModelDoc"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/clientModelDoc(demo)/clientModelDoc.service.js#L74-L84 | train |
michaelkrone/generator-material-app | generators/app/templates/client/app/clientModelDoc(demo)/clientModelDoc.service.js | update | function update(clientModelDoc, callback) {
var cb = callback || angular.noop;
return ClientModelDoc.update(clientModelDoc,
function (clientModelDoc) {
return cb(clientModelDoc);
},
function (err) {
return cb(err);
}).$promise;
} | javascript | function update(clientModelDoc, callback) {
var cb = callback || angular.noop;
return ClientModelDoc.update(clientModelDoc,
function (clientModelDoc) {
return cb(clientModelDoc);
},
function (err) {
return cb(err);
}).$promise;
} | [
"function",
"update",
"(",
"clientModelDoc",
",",
"callback",
")",
"{",
"var",
"cb",
"=",
"callback",
"||",
"angular",
".",
"noop",
";",
"return",
"ClientModelDoc",
".",
"update",
"(",
"clientModelDoc",
",",
"function",
"(",
"clientModelDoc",
")",
"{",
"return",
"cb",
"(",
"clientModelDoc",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
")",
".",
"$promise",
";",
"}"
]
| Create a new clientModelDoc
@param {Object} clientModelDoc - clientModelDocData
@param {Function} callback - optional
@return {Promise} | [
"Create",
"a",
"new",
"clientModelDoc"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/clientModelDoc(demo)/clientModelDoc.service.js#L93-L103 | train |
michaelkrone/generator-material-app | generators/app/templates/server/app.js | startServer | function startServer() {
var server = require('http').createServer(app);
var socket = socketio(server, {
serveClient: true,
path: '/socket.io-client'
});
// Setup SocketIO
socketConfig(socket);
return server;
} | javascript | function startServer() {
var server = require('http').createServer(app);
var socket = socketio(server, {
serveClient: true,
path: '/socket.io-client'
});
// Setup SocketIO
socketConfig(socket);
return server;
} | [
"function",
"startServer",
"(",
")",
"{",
"var",
"server",
"=",
"require",
"(",
"'http'",
")",
".",
"createServer",
"(",
"app",
")",
";",
"var",
"socket",
"=",
"socketio",
"(",
"server",
",",
"{",
"serveClient",
":",
"true",
",",
"path",
":",
"'/socket.io-client'",
"}",
")",
";",
"socketConfig",
"(",
"socket",
")",
";",
"return",
"server",
";",
"}"
]
| Create an express http server and return it
Config the socketio service to use this server
@api private
@return {} | [
"Create",
"an",
"express",
"http",
"server",
"and",
"return",
"it",
"Config",
"the",
"socketio",
"service",
"to",
"use",
"this",
"server"
]
| 764465d953282f6d86349527e3d62ec97f12a4d1 | https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/app.js#L40-L49 | train |
isaacs/ssh-key-decrypt | index.js | passphraseToKey | function passphraseToKey(type, passphrase, salt)
{
debug('passphraseToKey', type, passphrase, salt);
var nkey = keyBytes[type];
if (!nkey)
{
var allowed = Object.keys(keyBytes);
throw new TypeError('Unsupported type. Allowed: ' + allowed);
}
var niv = salt.length;
var saltLen = 8;
if (salt.length !== saltLen)
salt = salt.slice(0, saltLen);
var mds = 16;
var addmd = false;
var md_buf;
var key = new Buffer(nkey);
var keyidx = 0;
while (true)
{
debug('loop nkey=%d mds=%d', nkey, mds);
var c = crypto.createHash('md5');
if (addmd)
c.update(md_buf);
else
addmd = true;
if (!Buffer.isBuffer(passphrase))
c.update(passphrase, 'ascii');
else
c.update(passphrase);
c.update(salt);
md_buf = c.digest('buffer');
var i = 0;
while (nkey && i < mds)
{
key[keyidx++] = md_buf[i];
nkey--;
i++;
}
var steps = Math.min(niv, mds - i);
niv -= steps;
i += steps;
if ((nkey == 0) && (niv == 0)) break;
}
return key
} | javascript | function passphraseToKey(type, passphrase, salt)
{
debug('passphraseToKey', type, passphrase, salt);
var nkey = keyBytes[type];
if (!nkey)
{
var allowed = Object.keys(keyBytes);
throw new TypeError('Unsupported type. Allowed: ' + allowed);
}
var niv = salt.length;
var saltLen = 8;
if (salt.length !== saltLen)
salt = salt.slice(0, saltLen);
var mds = 16;
var addmd = false;
var md_buf;
var key = new Buffer(nkey);
var keyidx = 0;
while (true)
{
debug('loop nkey=%d mds=%d', nkey, mds);
var c = crypto.createHash('md5');
if (addmd)
c.update(md_buf);
else
addmd = true;
if (!Buffer.isBuffer(passphrase))
c.update(passphrase, 'ascii');
else
c.update(passphrase);
c.update(salt);
md_buf = c.digest('buffer');
var i = 0;
while (nkey && i < mds)
{
key[keyidx++] = md_buf[i];
nkey--;
i++;
}
var steps = Math.min(niv, mds - i);
niv -= steps;
i += steps;
if ((nkey == 0) && (niv == 0)) break;
}
return key
} | [
"function",
"passphraseToKey",
"(",
"type",
",",
"passphrase",
",",
"salt",
")",
"{",
"debug",
"(",
"'passphraseToKey'",
",",
"type",
",",
"passphrase",
",",
"salt",
")",
";",
"var",
"nkey",
"=",
"keyBytes",
"[",
"type",
"]",
";",
"if",
"(",
"!",
"nkey",
")",
"{",
"var",
"allowed",
"=",
"Object",
".",
"keys",
"(",
"keyBytes",
")",
";",
"throw",
"new",
"TypeError",
"(",
"'Unsupported type. Allowed: '",
"+",
"allowed",
")",
";",
"}",
"var",
"niv",
"=",
"salt",
".",
"length",
";",
"var",
"saltLen",
"=",
"8",
";",
"if",
"(",
"salt",
".",
"length",
"!==",
"saltLen",
")",
"salt",
"=",
"salt",
".",
"slice",
"(",
"0",
",",
"saltLen",
")",
";",
"var",
"mds",
"=",
"16",
";",
"var",
"addmd",
"=",
"false",
";",
"var",
"md_buf",
";",
"var",
"key",
"=",
"new",
"Buffer",
"(",
"nkey",
")",
";",
"var",
"keyidx",
"=",
"0",
";",
"while",
"(",
"true",
")",
"{",
"debug",
"(",
"'loop nkey=%d mds=%d'",
",",
"nkey",
",",
"mds",
")",
";",
"var",
"c",
"=",
"crypto",
".",
"createHash",
"(",
"'md5'",
")",
";",
"if",
"(",
"addmd",
")",
"c",
".",
"update",
"(",
"md_buf",
")",
";",
"else",
"addmd",
"=",
"true",
";",
"if",
"(",
"!",
"Buffer",
".",
"isBuffer",
"(",
"passphrase",
")",
")",
"c",
".",
"update",
"(",
"passphrase",
",",
"'ascii'",
")",
";",
"else",
"c",
".",
"update",
"(",
"passphrase",
")",
";",
"c",
".",
"update",
"(",
"salt",
")",
";",
"md_buf",
"=",
"c",
".",
"digest",
"(",
"'buffer'",
")",
";",
"var",
"i",
"=",
"0",
";",
"while",
"(",
"nkey",
"&&",
"i",
"<",
"mds",
")",
"{",
"key",
"[",
"keyidx",
"++",
"]",
"=",
"md_buf",
"[",
"i",
"]",
";",
"nkey",
"--",
";",
"i",
"++",
";",
"}",
"var",
"steps",
"=",
"Math",
".",
"min",
"(",
"niv",
",",
"mds",
"-",
"i",
")",
";",
"niv",
"-=",
"steps",
";",
"i",
"+=",
"steps",
";",
"if",
"(",
"(",
"nkey",
"==",
"0",
")",
"&&",
"(",
"niv",
"==",
"0",
")",
")",
"break",
";",
"}",
"return",
"key",
"}"
]
| port of EVP_BytesToKey, as used when decrypting PEM keys | [
"port",
"of",
"EVP_BytesToKey",
"as",
"used",
"when",
"decrypting",
"PEM",
"keys"
]
| 36c53300549d44367979f657010948a2a3d369e0 | https://github.com/isaacs/ssh-key-decrypt/blob/36c53300549d44367979f657010948a2a3d369e0/index.js#L100-L155 | train |
marcodave/protractor-http-client | server/auth-server.js | verifyToken | function verifyToken(token) {
var decodedToken = jwt.decode(token)
return userdb.users.filter(user => user.name == decodedToken).length > 0;
} | javascript | function verifyToken(token) {
var decodedToken = jwt.decode(token)
return userdb.users.filter(user => user.name == decodedToken).length > 0;
} | [
"function",
"verifyToken",
"(",
"token",
")",
"{",
"var",
"decodedToken",
"=",
"jwt",
".",
"decode",
"(",
"token",
")",
"return",
"userdb",
".",
"users",
".",
"filter",
"(",
"user",
"=>",
"user",
".",
"name",
"==",
"decodedToken",
")",
".",
"length",
">",
"0",
";",
"}"
]
| Verify the token | [
"Verify",
"the",
"token"
]
| 232d93ae5308bd858a0546b579e15e0c947dc3e9 | https://github.com/marcodave/protractor-http-client/blob/232d93ae5308bd858a0546b579e15e0c947dc3e9/server/auth-server.js#L22-L25 | train |
Crunch/postcss-less | index.js | convertImports | function convertImports(imports) {
for (var file in imports) {
if (imports.hasOwnProperty(file)) {
postCssInputs[file] = new Input(imports[file], file !== "input" ? { from: file } : undefined);
}
}
} | javascript | function convertImports(imports) {
for (var file in imports) {
if (imports.hasOwnProperty(file)) {
postCssInputs[file] = new Input(imports[file], file !== "input" ? { from: file } : undefined);
}
}
} | [
"function",
"convertImports",
"(",
"imports",
")",
"{",
"for",
"(",
"var",
"file",
"in",
"imports",
")",
"{",
"if",
"(",
"imports",
".",
"hasOwnProperty",
"(",
"file",
")",
")",
"{",
"postCssInputs",
"[",
"file",
"]",
"=",
"new",
"Input",
"(",
"imports",
"[",
"file",
"]",
",",
"file",
"!==",
"\"input\"",
"?",
"{",
"from",
":",
"file",
"}",
":",
"undefined",
")",
";",
"}",
"}",
"}"
]
| Less's importManager is like PostCSS's Input class. We need to convert our inputs to reference them later. | [
"Less",
"s",
"importManager",
"is",
"like",
"PostCSS",
"s",
"Input",
"class",
".",
"We",
"need",
"to",
"convert",
"our",
"inputs",
"to",
"reference",
"them",
"later",
"."
]
| 69b2b81d10418c78977518330a752a17471a00c8 | https://github.com/Crunch/postcss-less/blob/69b2b81d10418c78977518330a752a17471a00c8/index.js#L47-L53 | train |
Crunch/postcss-less | index.js | function(directive) {
var filename = directive.path
? directive.path.currentFileInfo.filename
: directive.currentFileInfo.filename;
var val, node, nodeTmp = buildNodeObject(filename, directive.index);
if(!directive.path) {
if(directive.features) {
val = getObject(directive.features, true).stringValue;
}
else {
val = getObject(directive.value, true).stringValue;
}
}
else {
val = directive.path.quote + directive.path.value + directive.path.quote;
}
node = {
type: ""
};
if(directive.type === 'Media') {
node.name = 'media';
}
else if(directive.type === 'Import') {
node.name = 'import';
}
else {
// Remove "@" for PostCSS
node.name = directive.name.replace('@','');
}
node.source = nodeTmp.source;
node.params = val;
var atrule = postcss.atRule(node);
if(directive.rules) {
atrule.nodes = [];
processRules(atrule, directive.rules);
}
return atrule;
} | javascript | function(directive) {
var filename = directive.path
? directive.path.currentFileInfo.filename
: directive.currentFileInfo.filename;
var val, node, nodeTmp = buildNodeObject(filename, directive.index);
if(!directive.path) {
if(directive.features) {
val = getObject(directive.features, true).stringValue;
}
else {
val = getObject(directive.value, true).stringValue;
}
}
else {
val = directive.path.quote + directive.path.value + directive.path.quote;
}
node = {
type: ""
};
if(directive.type === 'Media') {
node.name = 'media';
}
else if(directive.type === 'Import') {
node.name = 'import';
}
else {
// Remove "@" for PostCSS
node.name = directive.name.replace('@','');
}
node.source = nodeTmp.source;
node.params = val;
var atrule = postcss.atRule(node);
if(directive.rules) {
atrule.nodes = [];
processRules(atrule, directive.rules);
}
return atrule;
} | [
"function",
"(",
"directive",
")",
"{",
"var",
"filename",
"=",
"directive",
".",
"path",
"?",
"directive",
".",
"path",
".",
"currentFileInfo",
".",
"filename",
":",
"directive",
".",
"currentFileInfo",
".",
"filename",
";",
"var",
"val",
",",
"node",
",",
"nodeTmp",
"=",
"buildNodeObject",
"(",
"filename",
",",
"directive",
".",
"index",
")",
";",
"if",
"(",
"!",
"directive",
".",
"path",
")",
"{",
"if",
"(",
"directive",
".",
"features",
")",
"{",
"val",
"=",
"getObject",
"(",
"directive",
".",
"features",
",",
"true",
")",
".",
"stringValue",
";",
"}",
"else",
"{",
"val",
"=",
"getObject",
"(",
"directive",
".",
"value",
",",
"true",
")",
".",
"stringValue",
";",
"}",
"}",
"else",
"{",
"val",
"=",
"directive",
".",
"path",
".",
"quote",
"+",
"directive",
".",
"path",
".",
"value",
"+",
"directive",
".",
"path",
".",
"quote",
";",
"}",
"node",
"=",
"{",
"type",
":",
"\"\"",
"}",
";",
"if",
"(",
"directive",
".",
"type",
"===",
"'Media'",
")",
"{",
"node",
".",
"name",
"=",
"'media'",
";",
"}",
"else",
"if",
"(",
"directive",
".",
"type",
"===",
"'Import'",
")",
"{",
"node",
".",
"name",
"=",
"'import'",
";",
"}",
"else",
"{",
"node",
".",
"name",
"=",
"directive",
".",
"name",
".",
"replace",
"(",
"'@'",
",",
"''",
")",
";",
"}",
"node",
".",
"source",
"=",
"nodeTmp",
".",
"source",
";",
"node",
".",
"params",
"=",
"val",
";",
"var",
"atrule",
"=",
"postcss",
".",
"atRule",
"(",
"node",
")",
";",
"if",
"(",
"directive",
".",
"rules",
")",
"{",
"atrule",
".",
"nodes",
"=",
"[",
"]",
";",
"processRules",
"(",
"atrule",
",",
"directive",
".",
"rules",
")",
";",
"}",
"return",
"atrule",
";",
"}"
]
| PostCSS "at-rule" | [
"PostCSS",
"at",
"-",
"rule"
]
| 69b2b81d10418c78977518330a752a17471a00c8 | https://github.com/Crunch/postcss-less/blob/69b2b81d10418c78977518330a752a17471a00c8/index.js#L96-L140 | train |
|
arqex/react-json | src/validation.js | function( methodStr ){
var parts = methodStr.split('['),
definition = {
name: parts[0],
args: []
},
args
;
if( parts.length > 1 ){
args = parts[1];
if( args[ args.length - 1 ] == ']' )
args = args.slice(0, args.length - 1);
definition.args = args.split(/\s*,\s*/);
}
return definition;
} | javascript | function( methodStr ){
var parts = methodStr.split('['),
definition = {
name: parts[0],
args: []
},
args
;
if( parts.length > 1 ){
args = parts[1];
if( args[ args.length - 1 ] == ']' )
args = args.slice(0, args.length - 1);
definition.args = args.split(/\s*,\s*/);
}
return definition;
} | [
"function",
"(",
"methodStr",
")",
"{",
"var",
"parts",
"=",
"methodStr",
".",
"split",
"(",
"'['",
")",
",",
"definition",
"=",
"{",
"name",
":",
"parts",
"[",
"0",
"]",
",",
"args",
":",
"[",
"]",
"}",
",",
"args",
";",
"if",
"(",
"parts",
".",
"length",
">",
"1",
")",
"{",
"args",
"=",
"parts",
"[",
"1",
"]",
";",
"if",
"(",
"args",
"[",
"args",
".",
"length",
"-",
"1",
"]",
"==",
"']'",
")",
"args",
"=",
"args",
".",
"slice",
"(",
"0",
",",
"args",
".",
"length",
"-",
"1",
")",
";",
"definition",
".",
"args",
"=",
"args",
".",
"split",
"(",
"/",
"\\s*,\\s*",
"/",
")",
";",
"}",
"return",
"definition",
";",
"}"
]
| Parse a method call in the data-validation attribute.
@param {String} methodStr A method call like method[arg1, arg2, ...]
@return {Object} An object like {name: 'method', args: [arg1, arg2, ...]} | [
"Parse",
"a",
"method",
"call",
"in",
"the",
"data",
"-",
"validation",
"attribute",
"."
]
| 81bbeefacf9ceadbd9a7e92b9481f43608d266cd | https://github.com/arqex/react-json/blob/81bbeefacf9ceadbd9a7e92b9481f43608d266cd/src/validation.js#L126-L145 | train |
|
arqex/react-json | src/validation.js | function( field ){
var tagName = field.tagName.toLowerCase();
if( tagName == 'input' && field.type == 'checkbox' ){
return field.checked;
}
if( tagName == 'select' ){
return field.options[field.selectedIndex].value;
}
return field.value;
} | javascript | function( field ){
var tagName = field.tagName.toLowerCase();
if( tagName == 'input' && field.type == 'checkbox' ){
return field.checked;
}
if( tagName == 'select' ){
return field.options[field.selectedIndex].value;
}
return field.value;
} | [
"function",
"(",
"field",
")",
"{",
"var",
"tagName",
"=",
"field",
".",
"tagName",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"tagName",
"==",
"'input'",
"&&",
"field",
".",
"type",
"==",
"'checkbox'",
")",
"{",
"return",
"field",
".",
"checked",
";",
"}",
"if",
"(",
"tagName",
"==",
"'select'",
")",
"{",
"return",
"field",
".",
"options",
"[",
"field",
".",
"selectedIndex",
"]",
".",
"value",
";",
"}",
"return",
"field",
".",
"value",
";",
"}"
]
| Get the value of a field node, hiding the differences among
different type of inputs.
@param {DOMElement} field The field.
@return {String} The current value of the given field. | [
"Get",
"the",
"value",
"of",
"a",
"field",
"node",
"hiding",
"the",
"differences",
"among",
"different",
"type",
"of",
"inputs",
"."
]
| 81bbeefacf9ceadbd9a7e92b9481f43608d266cd | https://github.com/arqex/react-json/blob/81bbeefacf9ceadbd9a7e92b9481f43608d266cd/src/validation.js#L154-L166 | train |
|
arqex/react-json | mixins/CompoundFieldMixin.js | function( key ){
var fields = this.state.fields;
if( fields[ key ] && fields[ key ].settings.focus === true ){
fields = assign({}, fields);
fields[key].settings.focus = false;
this.setState( {fields: fields} );
}
} | javascript | function( key ){
var fields = this.state.fields;
if( fields[ key ] && fields[ key ].settings.focus === true ){
fields = assign({}, fields);
fields[key].settings.focus = false;
this.setState( {fields: fields} );
}
} | [
"function",
"(",
"key",
")",
"{",
"var",
"fields",
"=",
"this",
".",
"state",
".",
"fields",
";",
"if",
"(",
"fields",
"[",
"key",
"]",
"&&",
"fields",
"[",
"key",
"]",
".",
"settings",
".",
"focus",
"===",
"true",
")",
"{",
"fields",
"=",
"assign",
"(",
"{",
"}",
",",
"fields",
")",
";",
"fields",
"[",
"key",
"]",
".",
"settings",
".",
"focus",
"=",
"false",
";",
"this",
".",
"setState",
"(",
"{",
"fields",
":",
"fields",
"}",
")",
";",
"}",
"}"
]
| Checks if the current key editing setting is true
and set it to false. The editing setting is set
to true when a new child is added to edit it automatically
after is edited it loses the point.
@param {String} key The child key | [
"Checks",
"if",
"the",
"current",
"key",
"editing",
"setting",
"is",
"true",
"and",
"set",
"it",
"to",
"false",
".",
"The",
"editing",
"setting",
"is",
"set",
"to",
"true",
"when",
"a",
"new",
"child",
"is",
"added",
"to",
"edit",
"it",
"automatically",
"after",
"is",
"edited",
"it",
"loses",
"the",
"point",
"."
]
| 81bbeefacf9ceadbd9a7e92b9481f43608d266cd | https://github.com/arqex/react-json/blob/81bbeefacf9ceadbd9a7e92b9481f43608d266cd/mixins/CompoundFieldMixin.js#L91-L98 | train |
|
OpenKieler/klayjs-d3 | dist/klayjs-d3-ww.js | function(kgraph) {
if (kgraph) {
zoomToFit(kgraph);
// assign coordinates to nodes
kgraph.children.forEach(function(n) {
var d3node = nodes[parseInt(n.id)];
copyProps(n, d3node);
(n.ports || []).forEach(function(p, i) {
copyProps(p, d3node.ports[i]);
});
(n.labels || []).forEach(function(l, i) {
copyProps(l, d3node.labels[i]);
});
});
// edges
kgraph.edges.forEach(function(e) {
var l = links[parseInt(e.id) - nodes.length];
copyProps(e, l);
copyProps(e.source, l.source);
copyProps(e.target, l.target);
// make sure the bendpoint array is valid
l.bendPoints = e.bendPoints || [];
});
}
function copyProps(src, tgt, copyKeys) {
var keys = kgraphKeys;
if (copyKeys) {
keys = copyKeys.reduce(function (p, c) {p[c] = 1; return p;}, {});
}
for (var k in src) {
if (keys[k]) {
tgt[k] = src[k];
}
}
}
// invoke the 'finish' event
dispatch.finish({graph: kgraph});
} | javascript | function(kgraph) {
if (kgraph) {
zoomToFit(kgraph);
// assign coordinates to nodes
kgraph.children.forEach(function(n) {
var d3node = nodes[parseInt(n.id)];
copyProps(n, d3node);
(n.ports || []).forEach(function(p, i) {
copyProps(p, d3node.ports[i]);
});
(n.labels || []).forEach(function(l, i) {
copyProps(l, d3node.labels[i]);
});
});
// edges
kgraph.edges.forEach(function(e) {
var l = links[parseInt(e.id) - nodes.length];
copyProps(e, l);
copyProps(e.source, l.source);
copyProps(e.target, l.target);
// make sure the bendpoint array is valid
l.bendPoints = e.bendPoints || [];
});
}
function copyProps(src, tgt, copyKeys) {
var keys = kgraphKeys;
if (copyKeys) {
keys = copyKeys.reduce(function (p, c) {p[c] = 1; return p;}, {});
}
for (var k in src) {
if (keys[k]) {
tgt[k] = src[k];
}
}
}
// invoke the 'finish' event
dispatch.finish({graph: kgraph});
} | [
"function",
"(",
"kgraph",
")",
"{",
"if",
"(",
"kgraph",
")",
"{",
"zoomToFit",
"(",
"kgraph",
")",
";",
"kgraph",
".",
"children",
".",
"forEach",
"(",
"function",
"(",
"n",
")",
"{",
"var",
"d3node",
"=",
"nodes",
"[",
"parseInt",
"(",
"n",
".",
"id",
")",
"]",
";",
"copyProps",
"(",
"n",
",",
"d3node",
")",
";",
"(",
"n",
".",
"ports",
"||",
"[",
"]",
")",
".",
"forEach",
"(",
"function",
"(",
"p",
",",
"i",
")",
"{",
"copyProps",
"(",
"p",
",",
"d3node",
".",
"ports",
"[",
"i",
"]",
")",
";",
"}",
")",
";",
"(",
"n",
".",
"labels",
"||",
"[",
"]",
")",
".",
"forEach",
"(",
"function",
"(",
"l",
",",
"i",
")",
"{",
"copyProps",
"(",
"l",
",",
"d3node",
".",
"labels",
"[",
"i",
"]",
")",
";",
"}",
")",
";",
"}",
")",
";",
"kgraph",
".",
"edges",
".",
"forEach",
"(",
"function",
"(",
"e",
")",
"{",
"var",
"l",
"=",
"links",
"[",
"parseInt",
"(",
"e",
".",
"id",
")",
"-",
"nodes",
".",
"length",
"]",
";",
"copyProps",
"(",
"e",
",",
"l",
")",
";",
"copyProps",
"(",
"e",
".",
"source",
",",
"l",
".",
"source",
")",
";",
"copyProps",
"(",
"e",
".",
"target",
",",
"l",
".",
"target",
")",
";",
"l",
".",
"bendPoints",
"=",
"e",
".",
"bendPoints",
"||",
"[",
"]",
";",
"}",
")",
";",
"}",
"function",
"copyProps",
"(",
"src",
",",
"tgt",
",",
"copyKeys",
")",
"{",
"var",
"keys",
"=",
"kgraphKeys",
";",
"if",
"(",
"copyKeys",
")",
"{",
"keys",
"=",
"copyKeys",
".",
"reduce",
"(",
"function",
"(",
"p",
",",
"c",
")",
"{",
"p",
"[",
"c",
"]",
"=",
"1",
";",
"return",
"p",
";",
"}",
",",
"{",
"}",
")",
";",
"}",
"for",
"(",
"var",
"k",
"in",
"src",
")",
"{",
"if",
"(",
"keys",
"[",
"k",
"]",
")",
"{",
"tgt",
"[",
"k",
"]",
"=",
"src",
"[",
"k",
"]",
";",
"}",
"}",
"}",
"dispatch",
".",
"finish",
"(",
"{",
"graph",
":",
"kgraph",
"}",
")",
";",
"}"
]
| Apply layout for d3 style.
Copies properties of the layouted graph
back to the original nodes and links. | [
"Apply",
"layout",
"for",
"d3",
"style",
".",
"Copies",
"properties",
"of",
"the",
"layouted",
"graph",
"back",
"to",
"the",
"original",
"nodes",
"and",
"links",
"."
]
| 23430feeb38be85e1c25a42f6c0e135f8455c4eb | https://github.com/OpenKieler/klayjs-d3/blob/23430feeb38be85e1c25a42f6c0e135f8455c4eb/dist/klayjs-d3-ww.js#L196-L233 | train |
|
OpenKieler/klayjs-d3 | dist/klayjs-d3-ww.js | function(kgraph) {
zoomToFit(kgraph);
var nodeMap = {};
// convert to absolute positions
toAbsolutePositions(kgraph, {x: 0, y:0}, nodeMap);
toAbsolutePositionsEdges(kgraph, nodeMap);
// invoke the 'finish' event
dispatch.finish({graph: kgraph});
} | javascript | function(kgraph) {
zoomToFit(kgraph);
var nodeMap = {};
// convert to absolute positions
toAbsolutePositions(kgraph, {x: 0, y:0}, nodeMap);
toAbsolutePositionsEdges(kgraph, nodeMap);
// invoke the 'finish' event
dispatch.finish({graph: kgraph});
} | [
"function",
"(",
"kgraph",
")",
"{",
"zoomToFit",
"(",
"kgraph",
")",
";",
"var",
"nodeMap",
"=",
"{",
"}",
";",
"toAbsolutePositions",
"(",
"kgraph",
",",
"{",
"x",
":",
"0",
",",
"y",
":",
"0",
"}",
",",
"nodeMap",
")",
";",
"toAbsolutePositionsEdges",
"(",
"kgraph",
",",
"nodeMap",
")",
";",
"dispatch",
".",
"finish",
"(",
"{",
"graph",
":",
"kgraph",
"}",
")",
";",
"}"
]
| Apply layout for the kgraph style.
Converts relative positions to absolute positions. | [
"Apply",
"layout",
"for",
"the",
"kgraph",
"style",
".",
"Converts",
"relative",
"positions",
"to",
"absolute",
"positions",
"."
]
| 23430feeb38be85e1c25a42f6c0e135f8455c4eb | https://github.com/OpenKieler/klayjs-d3/blob/23430feeb38be85e1c25a42f6c0e135f8455c4eb/dist/klayjs-d3-ww.js#L278-L286 | train |
|
OpenKieler/klayjs-d3 | dist/klayjs-d3-ww.js | zoomToFit | function zoomToFit(kgraph) {
// scale everything so that it fits the specified size
var scale = width / kgraph.width || 1;
var sh = height / kgraph.height || 1;
if (sh < scale) {
scale = sh;
}
// if a transformation group was specified we
// perform a 'zoomToFit'
if (transformGroup) {
transformGroup.attr("transform", "scale(" + scale + ")");
}
} | javascript | function zoomToFit(kgraph) {
// scale everything so that it fits the specified size
var scale = width / kgraph.width || 1;
var sh = height / kgraph.height || 1;
if (sh < scale) {
scale = sh;
}
// if a transformation group was specified we
// perform a 'zoomToFit'
if (transformGroup) {
transformGroup.attr("transform", "scale(" + scale + ")");
}
} | [
"function",
"zoomToFit",
"(",
"kgraph",
")",
"{",
"var",
"scale",
"=",
"width",
"/",
"kgraph",
".",
"width",
"||",
"1",
";",
"var",
"sh",
"=",
"height",
"/",
"kgraph",
".",
"height",
"||",
"1",
";",
"if",
"(",
"sh",
"<",
"scale",
")",
"{",
"scale",
"=",
"sh",
";",
"}",
"if",
"(",
"transformGroup",
")",
"{",
"transformGroup",
".",
"attr",
"(",
"\"transform\"",
",",
"\"scale(\"",
"+",
"scale",
"+",
"\")\"",
")",
";",
"}",
"}"
]
| If a top level transform group is specified,
we set the scale such that the available
space is used to its maximum. | [
"If",
"a",
"top",
"level",
"transform",
"group",
"is",
"specified",
"we",
"set",
"the",
"scale",
"such",
"that",
"the",
"available",
"space",
"is",
"used",
"to",
"its",
"maximum",
"."
]
| 23430feeb38be85e1c25a42f6c0e135f8455c4eb | https://github.com/OpenKieler/klayjs-d3/blob/23430feeb38be85e1c25a42f6c0e135f8455c4eb/dist/klayjs-d3-ww.js#L358-L370 | train |
ljharb/String.prototype.matchAll | helpers/RegExpStringIterator.js | RegExpStringIterator | function RegExpStringIterator(R, S, global, fullUnicode) {
if (ES.Type(S) !== 'String') {
throw new TypeError('S must be a string');
}
if (ES.Type(global) !== 'Boolean') {
throw new TypeError('global must be a boolean');
}
if (ES.Type(fullUnicode) !== 'Boolean') {
throw new TypeError('fullUnicode must be a boolean');
}
hidden.set(this, '[[IteratingRegExp]]', R);
hidden.set(this, '[[IteratedString]]', S);
hidden.set(this, '[[Global]]', global);
hidden.set(this, '[[Unicode]]', fullUnicode);
hidden.set(this, '[[Done]]', false);
} | javascript | function RegExpStringIterator(R, S, global, fullUnicode) {
if (ES.Type(S) !== 'String') {
throw new TypeError('S must be a string');
}
if (ES.Type(global) !== 'Boolean') {
throw new TypeError('global must be a boolean');
}
if (ES.Type(fullUnicode) !== 'Boolean') {
throw new TypeError('fullUnicode must be a boolean');
}
hidden.set(this, '[[IteratingRegExp]]', R);
hidden.set(this, '[[IteratedString]]', S);
hidden.set(this, '[[Global]]', global);
hidden.set(this, '[[Unicode]]', fullUnicode);
hidden.set(this, '[[Done]]', false);
} | [
"function",
"RegExpStringIterator",
"(",
"R",
",",
"S",
",",
"global",
",",
"fullUnicode",
")",
"{",
"if",
"(",
"ES",
".",
"Type",
"(",
"S",
")",
"!==",
"'String'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'S must be a string'",
")",
";",
"}",
"if",
"(",
"ES",
".",
"Type",
"(",
"global",
")",
"!==",
"'Boolean'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'global must be a boolean'",
")",
";",
"}",
"if",
"(",
"ES",
".",
"Type",
"(",
"fullUnicode",
")",
"!==",
"'Boolean'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'fullUnicode must be a boolean'",
")",
";",
"}",
"hidden",
".",
"set",
"(",
"this",
",",
"'[[IteratingRegExp]]'",
",",
"R",
")",
";",
"hidden",
".",
"set",
"(",
"this",
",",
"'[[IteratedString]]'",
",",
"S",
")",
";",
"hidden",
".",
"set",
"(",
"this",
",",
"'[[Global]]'",
",",
"global",
")",
";",
"hidden",
".",
"set",
"(",
"this",
",",
"'[[Unicode]]'",
",",
"fullUnicode",
")",
";",
"hidden",
".",
"set",
"(",
"this",
",",
"'[[Done]]'",
",",
"false",
")",
";",
"}"
]
| eslint-disable-line no-shadow-restricted-names | [
"eslint",
"-",
"disable",
"-",
"line",
"no",
"-",
"shadow",
"-",
"restricted",
"-",
"names"
]
| c645e62702342ce4839c899cd31357ea79d8d926 | https://github.com/ljharb/String.prototype.matchAll/blob/c645e62702342ce4839c899cd31357ea79d8d926/helpers/RegExpStringIterator.js#L11-L26 | train |
wc-catalogue/blaze-elements | webpack.config.js | buildChunksSort | function buildChunksSort( order ) {
return (a, b) => order.indexOf(a.names[0]) - order.indexOf(b.names[0]);
} | javascript | function buildChunksSort( order ) {
return (a, b) => order.indexOf(a.names[0]) - order.indexOf(b.names[0]);
} | [
"function",
"buildChunksSort",
"(",
"order",
")",
"{",
"return",
"(",
"a",
",",
"b",
")",
"=>",
"order",
".",
"indexOf",
"(",
"a",
".",
"names",
"[",
"0",
"]",
")",
"-",
"order",
".",
"indexOf",
"(",
"b",
".",
"names",
"[",
"0",
"]",
")",
";",
"}"
]
| Build sort function for chunksSortMode from array | [
"Build",
"sort",
"function",
"for",
"chunksSortMode",
"from",
"array"
]
| 0b31ae793454bdaf51b9d1de0ade932a292df0ae | https://github.com/wc-catalogue/blaze-elements/blob/0b31ae793454bdaf51b9d1de0ade932a292df0ae/webpack.config.js#L249-L253 | train |
gwtw/js-avl-tree | src/avl-tree.js | minValueNode | function minValueNode(root) {
var current = root;
while (current.left) {
current = current.left;
}
return current;
} | javascript | function minValueNode(root) {
var current = root;
while (current.left) {
current = current.left;
}
return current;
} | [
"function",
"minValueNode",
"(",
"root",
")",
"{",
"var",
"current",
"=",
"root",
";",
"while",
"(",
"current",
".",
"left",
")",
"{",
"current",
"=",
"current",
".",
"left",
";",
"}",
"return",
"current",
";",
"}"
]
| Gets the minimum value node, rooted in a particular node.
@private
@param {Node} root The node to search.
@return {Node} The node with the minimum key in the tree. | [
"Gets",
"the",
"minimum",
"value",
"node",
"rooted",
"in",
"a",
"particular",
"node",
"."
]
| ff8b54693e86e5ea3c2f6df7f69599d4e64f93fe | https://github.com/gwtw/js-avl-tree/blob/ff8b54693e86e5ea3c2f6df7f69599d4e64f93fe/src/avl-tree.js#L262-L268 | train |
gwtw/js-avl-tree | src/avl-tree.js | maxValueNode | function maxValueNode(root) {
var current = root;
while (current.right) {
current = current.right;
}
return current;
} | javascript | function maxValueNode(root) {
var current = root;
while (current.right) {
current = current.right;
}
return current;
} | [
"function",
"maxValueNode",
"(",
"root",
")",
"{",
"var",
"current",
"=",
"root",
";",
"while",
"(",
"current",
".",
"right",
")",
"{",
"current",
"=",
"current",
".",
"right",
";",
"}",
"return",
"current",
";",
"}"
]
| Gets the maximum value node, rooted in a particular node.
@private
@param {Node} root The node to search.
@return {Node} The node with the maximum key in the tree. | [
"Gets",
"the",
"maximum",
"value",
"node",
"rooted",
"in",
"a",
"particular",
"node",
"."
]
| ff8b54693e86e5ea3c2f6df7f69599d4e64f93fe | https://github.com/gwtw/js-avl-tree/blob/ff8b54693e86e5ea3c2f6df7f69599d4e64f93fe/src/avl-tree.js#L284-L290 | train |
gwtw/js-avl-tree | src/avl-tree.js | getBalanceState | function getBalanceState(node) {
var heightDifference = node.leftHeight() - node.rightHeight();
switch (heightDifference) {
case -2: return BalanceState.UNBALANCED_RIGHT;
case -1: return BalanceState.SLIGHTLY_UNBALANCED_RIGHT;
case 1: return BalanceState.SLIGHTLY_UNBALANCED_LEFT;
case 2: return BalanceState.UNBALANCED_LEFT;
default: return BalanceState.BALANCED;
}
} | javascript | function getBalanceState(node) {
var heightDifference = node.leftHeight() - node.rightHeight();
switch (heightDifference) {
case -2: return BalanceState.UNBALANCED_RIGHT;
case -1: return BalanceState.SLIGHTLY_UNBALANCED_RIGHT;
case 1: return BalanceState.SLIGHTLY_UNBALANCED_LEFT;
case 2: return BalanceState.UNBALANCED_LEFT;
default: return BalanceState.BALANCED;
}
} | [
"function",
"getBalanceState",
"(",
"node",
")",
"{",
"var",
"heightDifference",
"=",
"node",
".",
"leftHeight",
"(",
")",
"-",
"node",
".",
"rightHeight",
"(",
")",
";",
"switch",
"(",
"heightDifference",
")",
"{",
"case",
"-",
"2",
":",
"return",
"BalanceState",
".",
"UNBALANCED_RIGHT",
";",
"case",
"-",
"1",
":",
"return",
"BalanceState",
".",
"SLIGHTLY_UNBALANCED_RIGHT",
";",
"case",
"1",
":",
"return",
"BalanceState",
".",
"SLIGHTLY_UNBALANCED_LEFT",
";",
"case",
"2",
":",
"return",
"BalanceState",
".",
"UNBALANCED_LEFT",
";",
"default",
":",
"return",
"BalanceState",
".",
"BALANCED",
";",
"}",
"}"
]
| Gets the balance state of a node, indicating whether the left or right
sub-trees are unbalanced.
@private
@param {Node} node The node to get the difference from.
@return {BalanceState} The BalanceState of the node. | [
"Gets",
"the",
"balance",
"state",
"of",
"a",
"node",
"indicating",
"whether",
"the",
"left",
"or",
"right",
"sub",
"-",
"trees",
"are",
"unbalanced",
"."
]
| ff8b54693e86e5ea3c2f6df7f69599d4e64f93fe | https://github.com/gwtw/js-avl-tree/blob/ff8b54693e86e5ea3c2f6df7f69599d4e64f93fe/src/avl-tree.js#L327-L336 | train |
jlidder/jswiremock | UrlParser.js | UrlNode | function UrlNode(data){
this.append = function(next){
this.next = next;
};
this.getData = function(){
return this.data;
};
this.setData = function(data){
this.data = data;
}
this.getNext = function(){
return this.next;
};
this.setParams = function(params){
var queryParameters = params.split("&");
if(queryParameters != null){
this.params = [];
for(var counter = 0; counter < queryParameters.length; counter++) {
var keyValuePair = queryParameters[counter].split("=");
this.params[keyValuePair[0]] = keyValuePair[1];
}
} else{
queryParameters = null;
}
};
this.getParams = function(){
return this.params;
};
//set var's for this object
var queryParamSplit = data.split("?");
this.params = null;
this.data = null;
this.next = null;
if(queryParamSplit != null && queryParamSplit.length > 1){
this.setData(queryParamSplit[0]);
this.setParams(queryParamSplit[1]);
} else{
this.setData(data);
}
} | javascript | function UrlNode(data){
this.append = function(next){
this.next = next;
};
this.getData = function(){
return this.data;
};
this.setData = function(data){
this.data = data;
}
this.getNext = function(){
return this.next;
};
this.setParams = function(params){
var queryParameters = params.split("&");
if(queryParameters != null){
this.params = [];
for(var counter = 0; counter < queryParameters.length; counter++) {
var keyValuePair = queryParameters[counter].split("=");
this.params[keyValuePair[0]] = keyValuePair[1];
}
} else{
queryParameters = null;
}
};
this.getParams = function(){
return this.params;
};
//set var's for this object
var queryParamSplit = data.split("?");
this.params = null;
this.data = null;
this.next = null;
if(queryParamSplit != null && queryParamSplit.length > 1){
this.setData(queryParamSplit[0]);
this.setParams(queryParamSplit[1]);
} else{
this.setData(data);
}
} | [
"function",
"UrlNode",
"(",
"data",
")",
"{",
"this",
".",
"append",
"=",
"function",
"(",
"next",
")",
"{",
"this",
".",
"next",
"=",
"next",
";",
"}",
";",
"this",
".",
"getData",
"=",
"function",
"(",
")",
"{",
"return",
"this",
".",
"data",
";",
"}",
";",
"this",
".",
"setData",
"=",
"function",
"(",
"data",
")",
"{",
"this",
".",
"data",
"=",
"data",
";",
"}",
"this",
".",
"getNext",
"=",
"function",
"(",
")",
"{",
"return",
"this",
".",
"next",
";",
"}",
";",
"this",
".",
"setParams",
"=",
"function",
"(",
"params",
")",
"{",
"var",
"queryParameters",
"=",
"params",
".",
"split",
"(",
"\"&\"",
")",
";",
"if",
"(",
"queryParameters",
"!=",
"null",
")",
"{",
"this",
".",
"params",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"counter",
"=",
"0",
";",
"counter",
"<",
"queryParameters",
".",
"length",
";",
"counter",
"++",
")",
"{",
"var",
"keyValuePair",
"=",
"queryParameters",
"[",
"counter",
"]",
".",
"split",
"(",
"\"=\"",
")",
";",
"this",
".",
"params",
"[",
"keyValuePair",
"[",
"0",
"]",
"]",
"=",
"keyValuePair",
"[",
"1",
"]",
";",
"}",
"}",
"else",
"{",
"queryParameters",
"=",
"null",
";",
"}",
"}",
";",
"this",
".",
"getParams",
"=",
"function",
"(",
")",
"{",
"return",
"this",
".",
"params",
";",
"}",
";",
"var",
"queryParamSplit",
"=",
"data",
".",
"split",
"(",
"\"?\"",
")",
";",
"this",
".",
"params",
"=",
"null",
";",
"this",
".",
"data",
"=",
"null",
";",
"this",
".",
"next",
"=",
"null",
";",
"if",
"(",
"queryParamSplit",
"!=",
"null",
"&&",
"queryParamSplit",
".",
"length",
">",
"1",
")",
"{",
"this",
".",
"setData",
"(",
"queryParamSplit",
"[",
"0",
"]",
")",
";",
"this",
".",
"setParams",
"(",
"queryParamSplit",
"[",
"1",
"]",
")",
";",
"}",
"else",
"{",
"this",
".",
"setData",
"(",
"data",
")",
";",
"}",
"}"
]
| Created by jlidder on 15-07-18. | [
"Created",
"by",
"jlidder",
"on",
"15",
"-",
"07",
"-",
"18",
"."
]
| e5943005a6d9be09700502be165b9ca174049c82 | https://github.com/jlidder/jswiremock/blob/e5943005a6d9be09700502be165b9ca174049c82/UrlParser.js#L5-L45 | train |
gwtw/js-avl-tree | src/node.js | function (key, value) {
this.left = null;
this.right = null;
this.height = null;
this.key = key;
this.value = value;
} | javascript | function (key, value) {
this.left = null;
this.right = null;
this.height = null;
this.key = key;
this.value = value;
} | [
"function",
"(",
"key",
",",
"value",
")",
"{",
"this",
".",
"left",
"=",
"null",
";",
"this",
".",
"right",
"=",
"null",
";",
"this",
".",
"height",
"=",
"null",
";",
"this",
".",
"key",
"=",
"key",
";",
"this",
".",
"value",
"=",
"value",
";",
"}"
]
| Creates a new AVL Tree node.
@private
@param {Object} key The key of the new node.
@param {Object} value The value of the new node. | [
"Creates",
"a",
"new",
"AVL",
"Tree",
"node",
"."
]
| ff8b54693e86e5ea3c2f6df7f69599d4e64f93fe | https://github.com/gwtw/js-avl-tree/blob/ff8b54693e86e5ea3c2f6df7f69599d4e64f93fe/src/node.js#L15-L21 | train |
|
wongatech/angular-http-loader | app/package/js/angular-http-loader.js | function (event, method) {
if (methods.indexOf(method.toUpperCase()) !== -1) {
showLoader = (event.name === 'loaderShow');
} else if (methods.length === 0) {
showLoader = (event.name === 'loaderShow');
}
if (ttl <= 0 || (!timeoutId && !showLoader)) {
$scope.showLoader = showLoader;
return;
}
if (timeoutId) {
return;
}
$scope.showLoader = showLoader;
timeoutId = $timeout(function () {
if (!showLoader) {
$scope.showLoader = showLoader;
}
timeoutId = undefined;
}, ttl);
} | javascript | function (event, method) {
if (methods.indexOf(method.toUpperCase()) !== -1) {
showLoader = (event.name === 'loaderShow');
} else if (methods.length === 0) {
showLoader = (event.name === 'loaderShow');
}
if (ttl <= 0 || (!timeoutId && !showLoader)) {
$scope.showLoader = showLoader;
return;
}
if (timeoutId) {
return;
}
$scope.showLoader = showLoader;
timeoutId = $timeout(function () {
if (!showLoader) {
$scope.showLoader = showLoader;
}
timeoutId = undefined;
}, ttl);
} | [
"function",
"(",
"event",
",",
"method",
")",
"{",
"if",
"(",
"methods",
".",
"indexOf",
"(",
"method",
".",
"toUpperCase",
"(",
")",
")",
"!==",
"-",
"1",
")",
"{",
"showLoader",
"=",
"(",
"event",
".",
"name",
"===",
"'loaderShow'",
")",
";",
"}",
"else",
"if",
"(",
"methods",
".",
"length",
"===",
"0",
")",
"{",
"showLoader",
"=",
"(",
"event",
".",
"name",
"===",
"'loaderShow'",
")",
";",
"}",
"if",
"(",
"ttl",
"<=",
"0",
"||",
"(",
"!",
"timeoutId",
"&&",
"!",
"showLoader",
")",
")",
"{",
"$scope",
".",
"showLoader",
"=",
"showLoader",
";",
"return",
";",
"}",
"if",
"(",
"timeoutId",
")",
"{",
"return",
";",
"}",
"$scope",
".",
"showLoader",
"=",
"showLoader",
";",
"timeoutId",
"=",
"$timeout",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"showLoader",
")",
"{",
"$scope",
".",
"showLoader",
"=",
"showLoader",
";",
"}",
"timeoutId",
"=",
"undefined",
";",
"}",
",",
"ttl",
")",
";",
"}"
]
| Toggle the show loader.
Contains the logic to show or hide the loader depending
on the passed method
@param {object} event
@param {string} method | [
"Toggle",
"the",
"show",
"loader",
".",
"Contains",
"the",
"logic",
"to",
"show",
"or",
"hide",
"the",
"loader",
"depending",
"on",
"the",
"passed",
"method"
]
| 070ccf93eebe9cca714e77a5b788f3630d987af1 | https://github.com/wongatech/angular-http-loader/blob/070ccf93eebe9cca714e77a5b788f3630d987af1/app/package/js/angular-http-loader.js#L98-L120 | train |
|
wongatech/angular-http-loader | app/package/js/angular-http-loader.js | function (url) {
if (url.substring(0, 2) !== '//' &&
url.indexOf('://') === -1 &&
whitelistLocalRequests) {
return true;
}
for (var i = domains.length; i--;) {
if (url.indexOf(domains[i]) !== -1) {
return true;
}
}
return false;
} | javascript | function (url) {
if (url.substring(0, 2) !== '//' &&
url.indexOf('://') === -1 &&
whitelistLocalRequests) {
return true;
}
for (var i = domains.length; i--;) {
if (url.indexOf(domains[i]) !== -1) {
return true;
}
}
return false;
} | [
"function",
"(",
"url",
")",
"{",
"if",
"(",
"url",
".",
"substring",
"(",
"0",
",",
"2",
")",
"!==",
"'//'",
"&&",
"url",
".",
"indexOf",
"(",
"'://'",
")",
"===",
"-",
"1",
"&&",
"whitelistLocalRequests",
")",
"{",
"return",
"true",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"domains",
".",
"length",
";",
"i",
"--",
";",
")",
"{",
"if",
"(",
"url",
".",
"indexOf",
"(",
"domains",
"[",
"i",
"]",
")",
"!==",
"-",
"1",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
]
| Check if the url domain is on the whitelist
@param {string} url
@returns {boolean} | [
"Check",
"if",
"the",
"url",
"domain",
"is",
"on",
"the",
"whitelist"
]
| 070ccf93eebe9cca714e77a5b788f3630d987af1 | https://github.com/wongatech/angular-http-loader/blob/070ccf93eebe9cca714e77a5b788f3630d987af1/app/package/js/angular-http-loader.js#L171-L185 | train |
|
wongatech/angular-http-loader | app/package/js/angular-http-loader.js | function (config) {
if (isUrlOnWhitelist(config.url)) {
numLoadings++;
$rootScope.$emit('loaderShow', config.method);
}
return config || $q.when(config);
} | javascript | function (config) {
if (isUrlOnWhitelist(config.url)) {
numLoadings++;
$rootScope.$emit('loaderShow', config.method);
}
return config || $q.when(config);
} | [
"function",
"(",
"config",
")",
"{",
"if",
"(",
"isUrlOnWhitelist",
"(",
"config",
".",
"url",
")",
")",
"{",
"numLoadings",
"++",
";",
"$rootScope",
".",
"$emit",
"(",
"'loaderShow'",
",",
"config",
".",
"method",
")",
";",
"}",
"return",
"config",
"||",
"$q",
".",
"when",
"(",
"config",
")",
";",
"}"
]
| Broadcast the loader show event
@param {object} config
@returns {object|Promise} | [
"Broadcast",
"the",
"loader",
"show",
"event"
]
| 070ccf93eebe9cca714e77a5b788f3630d987af1 | https://github.com/wongatech/angular-http-loader/blob/070ccf93eebe9cca714e77a5b788f3630d987af1/app/package/js/angular-http-loader.js#L208-L215 | train |
|
pubkey/solidity-cli | dist/src/output-files/index.js | outputPath | function outputPath(options, source) {
var DEBUG = false;
if (DEBUG)
console.log('sourceFolder: ' + options.sourceFolder);
var globBase = options.sourceFolder.replace(/\*.*/, '');
if (globBase.endsWith('.sol')) // single file
globBase = path.join(globBase, '../');
if (DEBUG)
console.log('globBase: ' + globBase);
var optDestination = options.destinationFolder ? options.destinationFolder : globBase;
if (DEBUG)
console.log('optDestination: ' + optDestination);
var destinationFolder = path.join(globBase, optDestination);
if (optDestination === globBase)
destinationFolder = globBase;
if (DEBUG)
console.log('destinationFolder: ' + destinationFolder);
// destination-folder is absolut
if (options.destinationFolder && options.destinationFolder.startsWith('/'))
destinationFolder = path.join(options.destinationFolder, './');
var fileNameRelative = source.filename.replace(globBase, '');
if (DEBUG)
console.log('fileNameRelative: ' + fileNameRelative);
var goalPath = path.join(destinationFolder, fileNameRelative);
return goalPath;
} | javascript | function outputPath(options, source) {
var DEBUG = false;
if (DEBUG)
console.log('sourceFolder: ' + options.sourceFolder);
var globBase = options.sourceFolder.replace(/\*.*/, '');
if (globBase.endsWith('.sol')) // single file
globBase = path.join(globBase, '../');
if (DEBUG)
console.log('globBase: ' + globBase);
var optDestination = options.destinationFolder ? options.destinationFolder : globBase;
if (DEBUG)
console.log('optDestination: ' + optDestination);
var destinationFolder = path.join(globBase, optDestination);
if (optDestination === globBase)
destinationFolder = globBase;
if (DEBUG)
console.log('destinationFolder: ' + destinationFolder);
// destination-folder is absolut
if (options.destinationFolder && options.destinationFolder.startsWith('/'))
destinationFolder = path.join(options.destinationFolder, './');
var fileNameRelative = source.filename.replace(globBase, '');
if (DEBUG)
console.log('fileNameRelative: ' + fileNameRelative);
var goalPath = path.join(destinationFolder, fileNameRelative);
return goalPath;
} | [
"function",
"outputPath",
"(",
"options",
",",
"source",
")",
"{",
"var",
"DEBUG",
"=",
"false",
";",
"if",
"(",
"DEBUG",
")",
"console",
".",
"log",
"(",
"'sourceFolder: '",
"+",
"options",
".",
"sourceFolder",
")",
";",
"var",
"globBase",
"=",
"options",
".",
"sourceFolder",
".",
"replace",
"(",
"/",
"\\*.*",
"/",
",",
"''",
")",
";",
"if",
"(",
"globBase",
".",
"endsWith",
"(",
"'.sol'",
")",
")",
"globBase",
"=",
"path",
".",
"join",
"(",
"globBase",
",",
"'../'",
")",
";",
"if",
"(",
"DEBUG",
")",
"console",
".",
"log",
"(",
"'globBase: '",
"+",
"globBase",
")",
";",
"var",
"optDestination",
"=",
"options",
".",
"destinationFolder",
"?",
"options",
".",
"destinationFolder",
":",
"globBase",
";",
"if",
"(",
"DEBUG",
")",
"console",
".",
"log",
"(",
"'optDestination: '",
"+",
"optDestination",
")",
";",
"var",
"destinationFolder",
"=",
"path",
".",
"join",
"(",
"globBase",
",",
"optDestination",
")",
";",
"if",
"(",
"optDestination",
"===",
"globBase",
")",
"destinationFolder",
"=",
"globBase",
";",
"if",
"(",
"DEBUG",
")",
"console",
".",
"log",
"(",
"'destinationFolder: '",
"+",
"destinationFolder",
")",
";",
"if",
"(",
"options",
".",
"destinationFolder",
"&&",
"options",
".",
"destinationFolder",
".",
"startsWith",
"(",
"'/'",
")",
")",
"destinationFolder",
"=",
"path",
".",
"join",
"(",
"options",
".",
"destinationFolder",
",",
"'./'",
")",
";",
"var",
"fileNameRelative",
"=",
"source",
".",
"filename",
".",
"replace",
"(",
"globBase",
",",
"''",
")",
";",
"if",
"(",
"DEBUG",
")",
"console",
".",
"log",
"(",
"'fileNameRelative: '",
"+",
"fileNameRelative",
")",
";",
"var",
"goalPath",
"=",
"path",
".",
"join",
"(",
"destinationFolder",
",",
"fileNameRelative",
")",
";",
"return",
"goalPath",
";",
"}"
]
| determines where the output should be written | [
"determines",
"where",
"the",
"output",
"should",
"be",
"written"
]
| 537f1ef9c3d62b488a771a4a5a67cfa2d74a4532 | https://github.com/pubkey/solidity-cli/blob/537f1ef9c3d62b488a771a4a5a67cfa2d74a4532/dist/src/output-files/index.js#L81-L106 | train |
pubkey/solidity-cli | dist/src/index.js | generateOutput | function generateOutput(source) {
return __awaiter(this, void 0, void 0, function () {
var isCached, artifact, compiled, artifact, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, caching.has(source.codeHash)];
case 1:
isCached = _b.sent();
if (!isCached) return [3 /*break*/, 3];
return [4 /*yield*/, caching.get(source.codeHash)];
case 2:
artifact = _b.sent();
return [2 /*return*/, artifact];
case 3: return [4 /*yield*/, solc_install_1.installVersion(source.solcVersion)];
case 4:
_b.sent();
return [4 /*yield*/, compile_1.default(source)];
case 5:
compiled = _b.sent();
_a = {
compiled: compiled
};
return [4 /*yield*/, output_files_1.createJavascriptFile(source, compiled)];
case 6:
_a.javascript = _b.sent();
return [4 /*yield*/, output_files_1.createTypescriptFile(source, compiled)];
case 7:
artifact = (_a.typescript = _b.sent(),
_a);
return [4 /*yield*/, caching.set(source.codeHash, artifact)];
case 8:
_b.sent();
return [2 /*return*/, artifact];
}
});
});
} | javascript | function generateOutput(source) {
return __awaiter(this, void 0, void 0, function () {
var isCached, artifact, compiled, artifact, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, caching.has(source.codeHash)];
case 1:
isCached = _b.sent();
if (!isCached) return [3 /*break*/, 3];
return [4 /*yield*/, caching.get(source.codeHash)];
case 2:
artifact = _b.sent();
return [2 /*return*/, artifact];
case 3: return [4 /*yield*/, solc_install_1.installVersion(source.solcVersion)];
case 4:
_b.sent();
return [4 /*yield*/, compile_1.default(source)];
case 5:
compiled = _b.sent();
_a = {
compiled: compiled
};
return [4 /*yield*/, output_files_1.createJavascriptFile(source, compiled)];
case 6:
_a.javascript = _b.sent();
return [4 /*yield*/, output_files_1.createTypescriptFile(source, compiled)];
case 7:
artifact = (_a.typescript = _b.sent(),
_a);
return [4 /*yield*/, caching.set(source.codeHash, artifact)];
case 8:
_b.sent();
return [2 /*return*/, artifact];
}
});
});
} | [
"function",
"generateOutput",
"(",
"source",
")",
"{",
"return",
"__awaiter",
"(",
"this",
",",
"void",
"0",
",",
"void",
"0",
",",
"function",
"(",
")",
"{",
"var",
"isCached",
",",
"artifact",
",",
"compiled",
",",
"artifact",
",",
"_a",
";",
"return",
"__generator",
"(",
"this",
",",
"function",
"(",
"_b",
")",
"{",
"switch",
"(",
"_b",
".",
"label",
")",
"{",
"case",
"0",
":",
"return",
"[",
"4",
",",
"caching",
".",
"has",
"(",
"source",
".",
"codeHash",
")",
"]",
";",
"case",
"1",
":",
"isCached",
"=",
"_b",
".",
"sent",
"(",
")",
";",
"if",
"(",
"!",
"isCached",
")",
"return",
"[",
"3",
",",
"3",
"]",
";",
"return",
"[",
"4",
",",
"caching",
".",
"get",
"(",
"source",
".",
"codeHash",
")",
"]",
";",
"case",
"2",
":",
"artifact",
"=",
"_b",
".",
"sent",
"(",
")",
";",
"return",
"[",
"2",
",",
"artifact",
"]",
";",
"case",
"3",
":",
"return",
"[",
"4",
",",
"solc_install_1",
".",
"installVersion",
"(",
"source",
".",
"solcVersion",
")",
"]",
";",
"case",
"4",
":",
"_b",
".",
"sent",
"(",
")",
";",
"return",
"[",
"4",
",",
"compile_1",
".",
"default",
"(",
"source",
")",
"]",
";",
"case",
"5",
":",
"compiled",
"=",
"_b",
".",
"sent",
"(",
")",
";",
"_a",
"=",
"{",
"compiled",
":",
"compiled",
"}",
";",
"return",
"[",
"4",
",",
"output_files_1",
".",
"createJavascriptFile",
"(",
"source",
",",
"compiled",
")",
"]",
";",
"case",
"6",
":",
"_a",
".",
"javascript",
"=",
"_b",
".",
"sent",
"(",
")",
";",
"return",
"[",
"4",
",",
"output_files_1",
".",
"createTypescriptFile",
"(",
"source",
",",
"compiled",
")",
"]",
";",
"case",
"7",
":",
"artifact",
"=",
"(",
"_a",
".",
"typescript",
"=",
"_b",
".",
"sent",
"(",
")",
",",
"_a",
")",
";",
"return",
"[",
"4",
",",
"caching",
".",
"set",
"(",
"source",
".",
"codeHash",
",",
"artifact",
")",
"]",
";",
"case",
"8",
":",
"_b",
".",
"sent",
"(",
")",
";",
"return",
"[",
"2",
",",
"artifact",
"]",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
]
| generates the output
or retrieves it from cache | [
"generates",
"the",
"output",
"or",
"retrieves",
"it",
"from",
"cache"
]
| 537f1ef9c3d62b488a771a4a5a67cfa2d74a4532 | https://github.com/pubkey/solidity-cli/blob/537f1ef9c3d62b488a771a4a5a67cfa2d74a4532/dist/src/index.js#L54-L90 | train |
pubkey/solidity-cli | dist/src/read-code.js | getSourceCode | function getSourceCode(fileName) {
return __awaiter(this, void 0, void 0, function () {
var code, codeCommentsRegex, importsRegex, imports;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, readFile(fileName, 'utf-8')];
case 1:
code = _a.sent();
codeCommentsRegex = /(\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\/)|(\/\/.*)/g;
code = code.replace(codeCommentsRegex, '');
importsRegex = /import "([^"]*)";/g;
imports = matches(importsRegex, code);
return [4 /*yield*/, Promise.all(imports.map(function (match) { return __awaiter(_this, void 0, void 0, function () {
var p, innerCode;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
p = path.resolve(fileName, '..', match.inner);
return [4 /*yield*/, getSourceCode(p)];
case 1:
innerCode = _a.sent();
// remove first line containing version
innerCode = innerCode.replace(/^.*\n/, '');
code = code.replace(match.full, innerCode);
return [2 /*return*/];
}
});
}); }))];
case 2:
_a.sent();
return [2 /*return*/, code];
}
});
});
} | javascript | function getSourceCode(fileName) {
return __awaiter(this, void 0, void 0, function () {
var code, codeCommentsRegex, importsRegex, imports;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, readFile(fileName, 'utf-8')];
case 1:
code = _a.sent();
codeCommentsRegex = /(\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\/)|(\/\/.*)/g;
code = code.replace(codeCommentsRegex, '');
importsRegex = /import "([^"]*)";/g;
imports = matches(importsRegex, code);
return [4 /*yield*/, Promise.all(imports.map(function (match) { return __awaiter(_this, void 0, void 0, function () {
var p, innerCode;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
p = path.resolve(fileName, '..', match.inner);
return [4 /*yield*/, getSourceCode(p)];
case 1:
innerCode = _a.sent();
// remove first line containing version
innerCode = innerCode.replace(/^.*\n/, '');
code = code.replace(match.full, innerCode);
return [2 /*return*/];
}
});
}); }))];
case 2:
_a.sent();
return [2 /*return*/, code];
}
});
});
} | [
"function",
"getSourceCode",
"(",
"fileName",
")",
"{",
"return",
"__awaiter",
"(",
"this",
",",
"void",
"0",
",",
"void",
"0",
",",
"function",
"(",
")",
"{",
"var",
"code",
",",
"codeCommentsRegex",
",",
"importsRegex",
",",
"imports",
";",
"var",
"_this",
"=",
"this",
";",
"return",
"__generator",
"(",
"this",
",",
"function",
"(",
"_a",
")",
"{",
"switch",
"(",
"_a",
".",
"label",
")",
"{",
"case",
"0",
":",
"return",
"[",
"4",
",",
"readFile",
"(",
"fileName",
",",
"'utf-8'",
")",
"]",
";",
"case",
"1",
":",
"code",
"=",
"_a",
".",
"sent",
"(",
")",
";",
"codeCommentsRegex",
"=",
"/",
"(\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*+\\/)|(\\/\\/.*)",
"/",
"g",
";",
"code",
"=",
"code",
".",
"replace",
"(",
"codeCommentsRegex",
",",
"''",
")",
";",
"importsRegex",
"=",
"/",
"import \"([^\"]*)\";",
"/",
"g",
";",
"imports",
"=",
"matches",
"(",
"importsRegex",
",",
"code",
")",
";",
"return",
"[",
"4",
",",
"Promise",
".",
"all",
"(",
"imports",
".",
"map",
"(",
"function",
"(",
"match",
")",
"{",
"return",
"__awaiter",
"(",
"_this",
",",
"void",
"0",
",",
"void",
"0",
",",
"function",
"(",
")",
"{",
"var",
"p",
",",
"innerCode",
";",
"return",
"__generator",
"(",
"this",
",",
"function",
"(",
"_a",
")",
"{",
"switch",
"(",
"_a",
".",
"label",
")",
"{",
"case",
"0",
":",
"p",
"=",
"path",
".",
"resolve",
"(",
"fileName",
",",
"'..'",
",",
"match",
".",
"inner",
")",
";",
"return",
"[",
"4",
",",
"getSourceCode",
"(",
"p",
")",
"]",
";",
"case",
"1",
":",
"innerCode",
"=",
"_a",
".",
"sent",
"(",
")",
";",
"innerCode",
"=",
"innerCode",
".",
"replace",
"(",
"/",
"^.*\\n",
"/",
",",
"''",
")",
";",
"code",
"=",
"code",
".",
"replace",
"(",
"match",
".",
"full",
",",
"innerCode",
")",
";",
"return",
"[",
"2",
"]",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
")",
")",
"]",
";",
"case",
"2",
":",
"_a",
".",
"sent",
"(",
")",
";",
"return",
"[",
"2",
",",
"code",
"]",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
]
| gets the source-code from the file
and parses all imports | [
"gets",
"the",
"source",
"-",
"code",
"from",
"the",
"file",
"and",
"parses",
"all",
"imports"
]
| 537f1ef9c3d62b488a771a4a5a67cfa2d74a4532 | https://github.com/pubkey/solidity-cli/blob/537f1ef9c3d62b488a771a4a5a67cfa2d74a4532/dist/src/read-code.js#L67-L102 | train |
tschaub/authorized | lib/manager.js | Manager | function Manager(options) {
this.roleGetters_ = {};
this.entityGetters_ = {};
this.actionDefs_ = {};
this.options = {
pauseStream: true
};
if (options) {
for (var option in this.options) {
if (options.hasOwnProperty(option)) {
this.options[option] = options[option];
}
}
}
} | javascript | function Manager(options) {
this.roleGetters_ = {};
this.entityGetters_ = {};
this.actionDefs_ = {};
this.options = {
pauseStream: true
};
if (options) {
for (var option in this.options) {
if (options.hasOwnProperty(option)) {
this.options[option] = options[option];
}
}
}
} | [
"function",
"Manager",
"(",
"options",
")",
"{",
"this",
".",
"roleGetters_",
"=",
"{",
"}",
";",
"this",
".",
"entityGetters_",
"=",
"{",
"}",
";",
"this",
".",
"actionDefs_",
"=",
"{",
"}",
";",
"this",
".",
"options",
"=",
"{",
"pauseStream",
":",
"true",
"}",
";",
"if",
"(",
"options",
")",
"{",
"for",
"(",
"var",
"option",
"in",
"this",
".",
"options",
")",
"{",
"if",
"(",
"options",
".",
"hasOwnProperty",
"(",
"option",
")",
")",
"{",
"this",
".",
"options",
"[",
"option",
"]",
"=",
"options",
"[",
"option",
"]",
";",
"}",
"}",
"}",
"}"
]
| Create a new authorization manager.
@param {Object} options Manager options.
* pauseStream {boolean} Pause the request body stream while checking
authorization (default is `true`).
@constructor | [
"Create",
"a",
"new",
"authorization",
"manager",
"."
]
| 999216db421f662dc9ca8b752eccd28bae017601 | https://github.com/tschaub/authorized/blob/999216db421f662dc9ca8b752eccd28bae017601/lib/manager.js#L25-L39 | train |
Merri/react-tabbordion | src/lib/resize.js | triggerResize | function triggerResize(callback) {
const { animateContent, checked } = callback.getState()
if ((animateContent === 'height' && checked) || (animateContent === 'marginTop' && !checked)) {
callback()
}
} | javascript | function triggerResize(callback) {
const { animateContent, checked } = callback.getState()
if ((animateContent === 'height' && checked) || (animateContent === 'marginTop' && !checked)) {
callback()
}
} | [
"function",
"triggerResize",
"(",
"callback",
")",
"{",
"const",
"{",
"animateContent",
",",
"checked",
"}",
"=",
"callback",
".",
"getState",
"(",
")",
"if",
"(",
"(",
"animateContent",
"===",
"'height'",
"&&",
"checked",
")",
"||",
"(",
"animateContent",
"===",
"'marginTop'",
"&&",
"!",
"checked",
")",
")",
"{",
"callback",
"(",
")",
"}",
"}"
]
| optimized only to be called on panels that actively can do transitions | [
"optimized",
"only",
"to",
"be",
"called",
"on",
"panels",
"that",
"actively",
"can",
"do",
"transitions"
]
| 614a746ef4a062c1e13c563f7de7c83ee0715ac3 | https://github.com/Merri/react-tabbordion/blob/614a746ef4a062c1e13c563f7de7c83ee0715ac3/src/lib/resize.js#L50-L55 | train |
gladeye/aframe-preloader-component | index.js | function () {
if(this.data.debug){
console.log('Initialized preloader');
}
if(this.data.type === 'bootstrap' && typeof $ === 'undefined'){
console.error('jQuery is not present, cannot instantiate Bootstrap modal for preloader!');
}
document.querySelector('a-assets').addEventListener('loaded',function(){
if(this.data.debug){
console.info('All assets loaded');
}
this.triggerProgressComplete();
}.bind(this));
var assetItems = document.querySelectorAll('a-assets a-asset-item,a-assets img,a-assets audio,a-assets video');
this.totalAssetCount = assetItems.length;
this.watchPreloadProgress(assetItems);
if(!this.data.target && this.data.autoInject){
if(this.data.debug){
console.info('No preloader html found, auto-injecting');
}
this.injectHTML();
}else{
switch(this.data.type){
case 'bootstrap':
this.initBootstrapModal($(this.data.target));
break;
default:
//do nothing
break;
}
}
if(this.data.disableVRModeUI){
this.sceneEl.setAttribute('vr-mode-ui','enabled','false');
}
} | javascript | function () {
if(this.data.debug){
console.log('Initialized preloader');
}
if(this.data.type === 'bootstrap' && typeof $ === 'undefined'){
console.error('jQuery is not present, cannot instantiate Bootstrap modal for preloader!');
}
document.querySelector('a-assets').addEventListener('loaded',function(){
if(this.data.debug){
console.info('All assets loaded');
}
this.triggerProgressComplete();
}.bind(this));
var assetItems = document.querySelectorAll('a-assets a-asset-item,a-assets img,a-assets audio,a-assets video');
this.totalAssetCount = assetItems.length;
this.watchPreloadProgress(assetItems);
if(!this.data.target && this.data.autoInject){
if(this.data.debug){
console.info('No preloader html found, auto-injecting');
}
this.injectHTML();
}else{
switch(this.data.type){
case 'bootstrap':
this.initBootstrapModal($(this.data.target));
break;
default:
//do nothing
break;
}
}
if(this.data.disableVRModeUI){
this.sceneEl.setAttribute('vr-mode-ui','enabled','false');
}
} | [
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"data",
".",
"debug",
")",
"{",
"console",
".",
"log",
"(",
"'Initialized preloader'",
")",
";",
"}",
"if",
"(",
"this",
".",
"data",
".",
"type",
"===",
"'bootstrap'",
"&&",
"typeof",
"$",
"===",
"'undefined'",
")",
"{",
"console",
".",
"error",
"(",
"'jQuery is not present, cannot instantiate Bootstrap modal for preloader!'",
")",
";",
"}",
"document",
".",
"querySelector",
"(",
"'a-assets'",
")",
".",
"addEventListener",
"(",
"'loaded'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"data",
".",
"debug",
")",
"{",
"console",
".",
"info",
"(",
"'All assets loaded'",
")",
";",
"}",
"this",
".",
"triggerProgressComplete",
"(",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"var",
"assetItems",
"=",
"document",
".",
"querySelectorAll",
"(",
"'a-assets a-asset-item,a-assets img,a-assets audio,a-assets video'",
")",
";",
"this",
".",
"totalAssetCount",
"=",
"assetItems",
".",
"length",
";",
"this",
".",
"watchPreloadProgress",
"(",
"assetItems",
")",
";",
"if",
"(",
"!",
"this",
".",
"data",
".",
"target",
"&&",
"this",
".",
"data",
".",
"autoInject",
")",
"{",
"if",
"(",
"this",
".",
"data",
".",
"debug",
")",
"{",
"console",
".",
"info",
"(",
"'No preloader html found, auto-injecting'",
")",
";",
"}",
"this",
".",
"injectHTML",
"(",
")",
";",
"}",
"else",
"{",
"switch",
"(",
"this",
".",
"data",
".",
"type",
")",
"{",
"case",
"'bootstrap'",
":",
"this",
".",
"initBootstrapModal",
"(",
"$",
"(",
"this",
".",
"data",
".",
"target",
")",
")",
";",
"break",
";",
"default",
":",
"break",
";",
"}",
"}",
"if",
"(",
"this",
".",
"data",
".",
"disableVRModeUI",
")",
"{",
"this",
".",
"sceneEl",
".",
"setAttribute",
"(",
"'vr-mode-ui'",
",",
"'enabled'",
",",
"'false'",
")",
";",
"}",
"}"
]
| length of time to slow down preload finish if slowLoad is set to 'true'
Called once when component is attached. Generally for initial setup. | [
"length",
"of",
"time",
"to",
"slow",
"down",
"preload",
"finish",
"if",
"slowLoad",
"is",
"set",
"to",
"true",
"Called",
"once",
"when",
"component",
"is",
"attached",
".",
"Generally",
"for",
"initial",
"setup",
"."
]
| 287f881d3aed160b463cb60513e706368ec2fe24 | https://github.com/gladeye/aframe-preloader-component/blob/287f881d3aed160b463cb60513e706368ec2fe24/index.js#L63-L106 | train |
|
ukayani/restify-router | lib/router.js | getHandlersFromArgs | function getHandlersFromArgs(args, start) {
assert.ok(args);
args = Array.prototype.slice.call(args, start);
function process(handlers, acc) {
if (handlers.length === 0) {
return acc;
}
var head = handlers.shift();
if (Array.isArray(head)) {
return process(head.concat(handlers), acc);
} else {
assert.func(head, 'handler');
acc.push(head);
return process(handlers, acc);
}
}
return process(args, []);
} | javascript | function getHandlersFromArgs(args, start) {
assert.ok(args);
args = Array.prototype.slice.call(args, start);
function process(handlers, acc) {
if (handlers.length === 0) {
return acc;
}
var head = handlers.shift();
if (Array.isArray(head)) {
return process(head.concat(handlers), acc);
} else {
assert.func(head, 'handler');
acc.push(head);
return process(handlers, acc);
}
}
return process(args, []);
} | [
"function",
"getHandlersFromArgs",
"(",
"args",
",",
"start",
")",
"{",
"assert",
".",
"ok",
"(",
"args",
")",
";",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"args",
",",
"start",
")",
";",
"function",
"process",
"(",
"handlers",
",",
"acc",
")",
"{",
"if",
"(",
"handlers",
".",
"length",
"===",
"0",
")",
"{",
"return",
"acc",
";",
"}",
"var",
"head",
"=",
"handlers",
".",
"shift",
"(",
")",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"head",
")",
")",
"{",
"return",
"process",
"(",
"head",
".",
"concat",
"(",
"handlers",
")",
",",
"acc",
")",
";",
"}",
"else",
"{",
"assert",
".",
"func",
"(",
"head",
",",
"'handler'",
")",
";",
"acc",
".",
"push",
"(",
"head",
")",
";",
"return",
"process",
"(",
"handlers",
",",
"acc",
")",
";",
"}",
"}",
"return",
"process",
"(",
"args",
",",
"[",
"]",
")",
";",
"}"
]
| Given a argument list, flatten the list
@param args
@param start point from which to slice the list
@returns {Array} | [
"Given",
"a",
"argument",
"list",
"flatten",
"the",
"list"
]
| 07c68e49927e5f23f1cabcfeea7257b681caac66 | https://github.com/ukayani/restify-router/blob/07c68e49927e5f23f1cabcfeea7257b681caac66/lib/router.js#L11-L32 | train |
ukayani/restify-router | lib/router.js | Router | function Router() {
// Routes with all verbs
var routes = {};
methods.forEach(function (method) {
routes[method] = [];
});
this.routes = routes;
this.commonHandlers = [];
this.routers = [];
} | javascript | function Router() {
// Routes with all verbs
var routes = {};
methods.forEach(function (method) {
routes[method] = [];
});
this.routes = routes;
this.commonHandlers = [];
this.routers = [];
} | [
"function",
"Router",
"(",
")",
"{",
"var",
"routes",
"=",
"{",
"}",
";",
"methods",
".",
"forEach",
"(",
"function",
"(",
"method",
")",
"{",
"routes",
"[",
"method",
"]",
"=",
"[",
"]",
";",
"}",
")",
";",
"this",
".",
"routes",
"=",
"routes",
";",
"this",
".",
"commonHandlers",
"=",
"[",
"]",
";",
"this",
".",
"routers",
"=",
"[",
"]",
";",
"}"
]
| Simple router that aggregates restify routes | [
"Simple",
"router",
"that",
"aggregates",
"restify",
"routes"
]
| 07c68e49927e5f23f1cabcfeea7257b681caac66 | https://github.com/ukayani/restify-router/blob/07c68e49927e5f23f1cabcfeea7257b681caac66/lib/router.js#L39-L50 | train |
generate/generate-gitignore | generator.js | tasks | function tasks(options) {
options = options || {};
var fp = path.resolve(options.template);
var tmpl = new utils.File({path: fp, contents: fs.readFileSync(fp)});
var data = {tasks: []};
return utils.through.obj(function(file, enc, next) {
var description = options.description || file.stem;
if (typeof description === 'function') {
description = options.description(file);
}
data.tasks.push({
alias: 'gitignore',
path: path.relative(path.resolve('generators'), file.path),
name: file.stem.toLowerCase(),
description: description,
relative: file.relative,
basename: '.gitignore'
});
next();
}, function(next) {
tmpl.data = data;
this.push(tmpl);
next();
});
} | javascript | function tasks(options) {
options = options || {};
var fp = path.resolve(options.template);
var tmpl = new utils.File({path: fp, contents: fs.readFileSync(fp)});
var data = {tasks: []};
return utils.through.obj(function(file, enc, next) {
var description = options.description || file.stem;
if (typeof description === 'function') {
description = options.description(file);
}
data.tasks.push({
alias: 'gitignore',
path: path.relative(path.resolve('generators'), file.path),
name: file.stem.toLowerCase(),
description: description,
relative: file.relative,
basename: '.gitignore'
});
next();
}, function(next) {
tmpl.data = data;
this.push(tmpl);
next();
});
} | [
"function",
"tasks",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"fp",
"=",
"path",
".",
"resolve",
"(",
"options",
".",
"template",
")",
";",
"var",
"tmpl",
"=",
"new",
"utils",
".",
"File",
"(",
"{",
"path",
":",
"fp",
",",
"contents",
":",
"fs",
".",
"readFileSync",
"(",
"fp",
")",
"}",
")",
";",
"var",
"data",
"=",
"{",
"tasks",
":",
"[",
"]",
"}",
";",
"return",
"utils",
".",
"through",
".",
"obj",
"(",
"function",
"(",
"file",
",",
"enc",
",",
"next",
")",
"{",
"var",
"description",
"=",
"options",
".",
"description",
"||",
"file",
".",
"stem",
";",
"if",
"(",
"typeof",
"description",
"===",
"'function'",
")",
"{",
"description",
"=",
"options",
".",
"description",
"(",
"file",
")",
";",
"}",
"data",
".",
"tasks",
".",
"push",
"(",
"{",
"alias",
":",
"'gitignore'",
",",
"path",
":",
"path",
".",
"relative",
"(",
"path",
".",
"resolve",
"(",
"'generators'",
")",
",",
"file",
".",
"path",
")",
",",
"name",
":",
"file",
".",
"stem",
".",
"toLowerCase",
"(",
")",
",",
"description",
":",
"description",
",",
"relative",
":",
"file",
".",
"relative",
",",
"basename",
":",
"'.gitignore'",
"}",
")",
";",
"next",
"(",
")",
";",
"}",
",",
"function",
"(",
"next",
")",
"{",
"tmpl",
".",
"data",
"=",
"data",
";",
"this",
".",
"push",
"(",
"tmpl",
")",
";",
"next",
"(",
")",
";",
"}",
")",
";",
"}"
]
| Plugin for generating individual gitignore tasks.
The alternative would be to load in templates and create tasks on-the-fly,
but this approach is much faster and results in a better user experience. | [
"Plugin",
"for",
"generating",
"individual",
"gitignore",
"tasks",
"."
]
| 69a0b7b0e66bf9f46a1cc59245b13d9eb346f9ff | https://github.com/generate/generate-gitignore/blob/69a0b7b0e66bf9f46a1cc59245b13d9eb346f9ff/generator.js#L111-L139 | train |
wmurphyrd/aframe-physics-extras | src/physics-sleepy.js | function (evt) {
let state = this.data.holdState
// api change in A-Frame v0.8.0
if (evt.detail === state || evt.detail.state === state) {
this.el.body.allowSleep = false
}
} | javascript | function (evt) {
let state = this.data.holdState
// api change in A-Frame v0.8.0
if (evt.detail === state || evt.detail.state === state) {
this.el.body.allowSleep = false
}
} | [
"function",
"(",
"evt",
")",
"{",
"let",
"state",
"=",
"this",
".",
"data",
".",
"holdState",
"if",
"(",
"evt",
".",
"detail",
"===",
"state",
"||",
"evt",
".",
"detail",
".",
"state",
"===",
"state",
")",
"{",
"this",
".",
"el",
".",
"body",
".",
"allowSleep",
"=",
"false",
"}",
"}"
]
| disble the sleeping during interactions because sleep will break constraints | [
"disble",
"the",
"sleeping",
"during",
"interactions",
"because",
"sleep",
"will",
"break",
"constraints"
]
| 470c710f96e9aa5e7c0957378a2959bf3f100c8b | https://github.com/wmurphyrd/aframe-physics-extras/blob/470c710f96e9aa5e7c0957378a2959bf3f100c8b/src/physics-sleepy.js#L55-L61 | train |
|
koajs/trace | index.js | dispatch | function dispatch(context, event, args) {
var date = new Date()
for (var i = 0; i < listeners.length; i++)
listeners[i](context, event, date, args)
} | javascript | function dispatch(context, event, args) {
var date = new Date()
for (var i = 0; i < listeners.length; i++)
listeners[i](context, event, date, args)
} | [
"function",
"dispatch",
"(",
"context",
",",
"event",
",",
"args",
")",
"{",
"var",
"date",
"=",
"new",
"Date",
"(",
")",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"listeners",
".",
"length",
";",
"i",
"++",
")",
"listeners",
"[",
"i",
"]",
"(",
"context",
",",
"event",
",",
"date",
",",
"args",
")",
"}"
]
| dispatch an event to all listeners | [
"dispatch",
"an",
"event",
"to",
"all",
"listeners"
]
| 27cfae8bc7f1389124ffae37bd0f0d9a5506956f | https://github.com/koajs/trace/blob/27cfae8bc7f1389124ffae37bd0f0d9a5506956f/index.js#L60-L64 | train |
louisbl/cordova-plugin-gpslocation | www/GPSLocation.js | function (successCallback, errorCallback, options) {
argscheck.checkArgs('fFO', 'GPSLocation.getCurrentPosition', arguments);
options = parseParameters(options);
var id = utils.createUUID();
// Tell device to get a position ASAP, and also retrieve a reference to the timeout timer generated in getCurrentPosition
timers[id] = GPSLocation.getCurrentPosition(successCallback, errorCallback, options);
var fail = function (e) {
clearTimeout(timers[id].timer);
var err = new PositionError(e.code, e.message);
if (errorCallback) {
errorCallback(err);
}
};
var win = function (p) {
clearTimeout(timers[id].timer);
if (options.timeout !== Infinity) {
timers[id].timer = createTimeout(fail, options.timeout);
}
var pos = new Position({
latitude: p.latitude,
longitude: p.longitude,
altitude: p.altitude,
accuracy: p.accuracy,
heading: p.heading,
velocity: p.velocity,
altitudeAccuracy: p.altitudeAccuracy
}, (p.timestamp === undefined ? new Date() : ((p.timestamp instanceof Date) ? p.timestamp : new Date(p.timestamp))));
GPSLocation.lastPosition = pos;
successCallback(pos);
};
exec(win, fail, "GPSLocation", "addWatch", [id]);
return id;
} | javascript | function (successCallback, errorCallback, options) {
argscheck.checkArgs('fFO', 'GPSLocation.getCurrentPosition', arguments);
options = parseParameters(options);
var id = utils.createUUID();
// Tell device to get a position ASAP, and also retrieve a reference to the timeout timer generated in getCurrentPosition
timers[id] = GPSLocation.getCurrentPosition(successCallback, errorCallback, options);
var fail = function (e) {
clearTimeout(timers[id].timer);
var err = new PositionError(e.code, e.message);
if (errorCallback) {
errorCallback(err);
}
};
var win = function (p) {
clearTimeout(timers[id].timer);
if (options.timeout !== Infinity) {
timers[id].timer = createTimeout(fail, options.timeout);
}
var pos = new Position({
latitude: p.latitude,
longitude: p.longitude,
altitude: p.altitude,
accuracy: p.accuracy,
heading: p.heading,
velocity: p.velocity,
altitudeAccuracy: p.altitudeAccuracy
}, (p.timestamp === undefined ? new Date() : ((p.timestamp instanceof Date) ? p.timestamp : new Date(p.timestamp))));
GPSLocation.lastPosition = pos;
successCallback(pos);
};
exec(win, fail, "GPSLocation", "addWatch", [id]);
return id;
} | [
"function",
"(",
"successCallback",
",",
"errorCallback",
",",
"options",
")",
"{",
"argscheck",
".",
"checkArgs",
"(",
"'fFO'",
",",
"'GPSLocation.getCurrentPosition'",
",",
"arguments",
")",
";",
"options",
"=",
"parseParameters",
"(",
"options",
")",
";",
"var",
"id",
"=",
"utils",
".",
"createUUID",
"(",
")",
";",
"timers",
"[",
"id",
"]",
"=",
"GPSLocation",
".",
"getCurrentPosition",
"(",
"successCallback",
",",
"errorCallback",
",",
"options",
")",
";",
"var",
"fail",
"=",
"function",
"(",
"e",
")",
"{",
"clearTimeout",
"(",
"timers",
"[",
"id",
"]",
".",
"timer",
")",
";",
"var",
"err",
"=",
"new",
"PositionError",
"(",
"e",
".",
"code",
",",
"e",
".",
"message",
")",
";",
"if",
"(",
"errorCallback",
")",
"{",
"errorCallback",
"(",
"err",
")",
";",
"}",
"}",
";",
"var",
"win",
"=",
"function",
"(",
"p",
")",
"{",
"clearTimeout",
"(",
"timers",
"[",
"id",
"]",
".",
"timer",
")",
";",
"if",
"(",
"options",
".",
"timeout",
"!==",
"Infinity",
")",
"{",
"timers",
"[",
"id",
"]",
".",
"timer",
"=",
"createTimeout",
"(",
"fail",
",",
"options",
".",
"timeout",
")",
";",
"}",
"var",
"pos",
"=",
"new",
"Position",
"(",
"{",
"latitude",
":",
"p",
".",
"latitude",
",",
"longitude",
":",
"p",
".",
"longitude",
",",
"altitude",
":",
"p",
".",
"altitude",
",",
"accuracy",
":",
"p",
".",
"accuracy",
",",
"heading",
":",
"p",
".",
"heading",
",",
"velocity",
":",
"p",
".",
"velocity",
",",
"altitudeAccuracy",
":",
"p",
".",
"altitudeAccuracy",
"}",
",",
"(",
"p",
".",
"timestamp",
"===",
"undefined",
"?",
"new",
"Date",
"(",
")",
":",
"(",
"(",
"p",
".",
"timestamp",
"instanceof",
"Date",
")",
"?",
"p",
".",
"timestamp",
":",
"new",
"Date",
"(",
"p",
".",
"timestamp",
")",
")",
")",
")",
";",
"GPSLocation",
".",
"lastPosition",
"=",
"pos",
";",
"successCallback",
"(",
"pos",
")",
";",
"}",
";",
"exec",
"(",
"win",
",",
"fail",
",",
"\"GPSLocation\"",
",",
"\"addWatch\"",
",",
"[",
"id",
"]",
")",
";",
"return",
"id",
";",
"}"
]
| Asynchronously watches the geolocation for changes to geolocation. When a change occurs,
the successCallback is called with the new location.
@param {Function} successCallback The function to call each time the location data is available
@param {Function} errorCallback The function to call when there is an error getting the location data. (OPTIONAL)
@param {PositionOptions} options The options for getting the location data such as frequency. (OPTIONAL)
@return String The watch id that must be passed to #clearWatch to stop watching. | [
"Asynchronously",
"watches",
"the",
"geolocation",
"for",
"changes",
"to",
"geolocation",
".",
"When",
"a",
"change",
"occurs",
"the",
"successCallback",
"is",
"called",
"with",
"the",
"new",
"location",
"."
]
| 03b1b149b274aac863e8c1d69c104c99eb577a84 | https://github.com/louisbl/cordova-plugin-gpslocation/blob/03b1b149b274aac863e8c1d69c104c99eb577a84/www/GPSLocation.js#L150-L188 | train |
|
ajgarn/CanvasImageUploader | canvas-image-uploader.js | base64toBlob | function base64toBlob(base64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(base64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
return new Blob(byteArrays, {type: contentType});
} | javascript | function base64toBlob(base64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(base64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
return new Blob(byteArrays, {type: contentType});
} | [
"function",
"base64toBlob",
"(",
"base64Data",
",",
"contentType",
",",
"sliceSize",
")",
"{",
"contentType",
"=",
"contentType",
"||",
"''",
";",
"sliceSize",
"=",
"sliceSize",
"||",
"512",
";",
"var",
"byteCharacters",
"=",
"atob",
"(",
"base64Data",
")",
";",
"var",
"byteArrays",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"offset",
"=",
"0",
";",
"offset",
"<",
"byteCharacters",
".",
"length",
";",
"offset",
"+=",
"sliceSize",
")",
"{",
"var",
"slice",
"=",
"byteCharacters",
".",
"slice",
"(",
"offset",
",",
"offset",
"+",
"sliceSize",
")",
";",
"var",
"byteNumbers",
"=",
"new",
"Array",
"(",
"slice",
".",
"length",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"slice",
".",
"length",
";",
"i",
"++",
")",
"{",
"byteNumbers",
"[",
"i",
"]",
"=",
"slice",
".",
"charCodeAt",
"(",
"i",
")",
";",
"}",
"var",
"byteArray",
"=",
"new",
"Uint8Array",
"(",
"byteNumbers",
")",
";",
"byteArrays",
".",
"push",
"(",
"byteArray",
")",
";",
"}",
"return",
"new",
"Blob",
"(",
"byteArrays",
",",
"{",
"type",
":",
"contentType",
"}",
")",
";",
"}"
]
| Converts a base64 string to byte array. | [
"Converts",
"a",
"base64",
"string",
"to",
"byte",
"array",
"."
]
| c12ee96cb2757b39c6463a11c85f075657e829f8 | https://github.com/ajgarn/CanvasImageUploader/blob/c12ee96cb2757b39c6463a11c85f075657e829f8/canvas-image-uploader.js#L40-L58 | train |
ajgarn/CanvasImageUploader | canvas-image-uploader.js | function(file, $canvas, callback) {
this.newImage();
if (!file)
return;
var reader = new FileReader();
reader.onload = function (fileReaderEvent) {
image.onload = function () { readImageToCanvasOnLoad(this, $canvas, callback); };
image.src = fileReaderEvent.target.result; // The URL from FileReader
};
reader.readAsDataURL(file);
} | javascript | function(file, $canvas, callback) {
this.newImage();
if (!file)
return;
var reader = new FileReader();
reader.onload = function (fileReaderEvent) {
image.onload = function () { readImageToCanvasOnLoad(this, $canvas, callback); };
image.src = fileReaderEvent.target.result; // The URL from FileReader
};
reader.readAsDataURL(file);
} | [
"function",
"(",
"file",
",",
"$canvas",
",",
"callback",
")",
"{",
"this",
".",
"newImage",
"(",
")",
";",
"if",
"(",
"!",
"file",
")",
"return",
";",
"var",
"reader",
"=",
"new",
"FileReader",
"(",
")",
";",
"reader",
".",
"onload",
"=",
"function",
"(",
"fileReaderEvent",
")",
"{",
"image",
".",
"onload",
"=",
"function",
"(",
")",
"{",
"readImageToCanvasOnLoad",
"(",
"this",
",",
"$canvas",
",",
"callback",
")",
";",
"}",
";",
"image",
".",
"src",
"=",
"fileReaderEvent",
".",
"target",
".",
"result",
";",
"}",
";",
"reader",
".",
"readAsDataURL",
"(",
"file",
")",
";",
"}"
]
| Draw an image from a file on a canvas.
@param file The uploaded file.
@param $canvas The canvas (jQuery) object to draw on.
@param callback Function that is called when the operation has finished. | [
"Draw",
"an",
"image",
"from",
"a",
"file",
"on",
"a",
"canvas",
"."
]
| c12ee96cb2757b39c6463a11c85f075657e829f8 | https://github.com/ajgarn/CanvasImageUploader/blob/c12ee96cb2757b39c6463a11c85f075657e829f8/canvas-image-uploader.js#L206-L218 | train |
|
forty2/hap-client | src/lib/encryption.js | encryptAndSeal | function encryptAndSeal(plainText, AAD, nonce, key) {
const cipherText =
Sodium
.crypto_stream_chacha20_xor_ic(plainText, nonce, 1, key);
const hmac =
computePoly1305(cipherText, AAD, nonce, key);
return [ cipherText, hmac ];
} | javascript | function encryptAndSeal(plainText, AAD, nonce, key) {
const cipherText =
Sodium
.crypto_stream_chacha20_xor_ic(plainText, nonce, 1, key);
const hmac =
computePoly1305(cipherText, AAD, nonce, key);
return [ cipherText, hmac ];
} | [
"function",
"encryptAndSeal",
"(",
"plainText",
",",
"AAD",
",",
"nonce",
",",
"key",
")",
"{",
"const",
"cipherText",
"=",
"Sodium",
".",
"crypto_stream_chacha20_xor_ic",
"(",
"plainText",
",",
"nonce",
",",
"1",
",",
"key",
")",
";",
"const",
"hmac",
"=",
"computePoly1305",
"(",
"cipherText",
",",
"AAD",
",",
"nonce",
",",
"key",
")",
";",
"return",
"[",
"cipherText",
",",
"hmac",
"]",
";",
"}"
]
| See above about calling directly into libsodium. | [
"See",
"above",
"about",
"calling",
"directly",
"into",
"libsodium",
"."
]
| 2e66a27462755759bdd28d574166bfd07b4a8665 | https://github.com/forty2/hap-client/blob/2e66a27462755759bdd28d574166bfd07b4a8665/src/lib/encryption.js#L51-L60 | train |
webdriverio/webdriverrtc | lib/browser/url.js | function (param1, param2, param3) {
var pc = new OriginalRTCPeerConnection(param1, param2, param3);
window.webdriverRTCPeerConnectionBucket = pc;
return pc;
} | javascript | function (param1, param2, param3) {
var pc = new OriginalRTCPeerConnection(param1, param2, param3);
window.webdriverRTCPeerConnectionBucket = pc;
return pc;
} | [
"function",
"(",
"param1",
",",
"param2",
",",
"param3",
")",
"{",
"var",
"pc",
"=",
"new",
"OriginalRTCPeerConnection",
"(",
"param1",
",",
"param2",
",",
"param3",
")",
";",
"window",
".",
"webdriverRTCPeerConnectionBucket",
"=",
"pc",
";",
"return",
"pc",
";",
"}"
]
| method to masquerade RTCPeerConnection | [
"method",
"to",
"masquerade",
"RTCPeerConnection"
]
| dfc6731792c2c9a0d6bfdc4e361244acf46af3fc | https://github.com/webdriverio/webdriverrtc/blob/dfc6731792c2c9a0d6bfdc4e361244acf46af3fc/lib/browser/url.js#L7-L11 | train |
|
fredriks/cloud-functions-runtime-config | src/index.js | getVariables | function getVariables(configName, variableNames) {
return Promise.all(variableNames.map(function(variableName) {
return getVariable(configName, variableName);
}));
} | javascript | function getVariables(configName, variableNames) {
return Promise.all(variableNames.map(function(variableName) {
return getVariable(configName, variableName);
}));
} | [
"function",
"getVariables",
"(",
"configName",
",",
"variableNames",
")",
"{",
"return",
"Promise",
".",
"all",
"(",
"variableNames",
".",
"map",
"(",
"function",
"(",
"variableName",
")",
"{",
"return",
"getVariable",
"(",
"configName",
",",
"variableName",
")",
";",
"}",
")",
")",
";",
"}"
]
| runtimeConfig.getVariables
@desc Reads a list of runtime config values
@param {string} configName The config name of the variables to return
@param {Array} variableNames The list of variable names to read
@return {Promise} Promise that resolves an array of the variable values | [
"runtimeConfig",
".",
"getVariables"
]
| 272eb48644df13939fcec458656b1f155f1b0f29 | https://github.com/fredriks/cloud-functions-runtime-config/blob/272eb48644df13939fcec458656b1f155f1b0f29/src/index.js#L18-L22 | train |
fredriks/cloud-functions-runtime-config | src/index.js | getVariable | function getVariable(configName, variableName) {
return new Promise(function(resolve, reject) {
auth().then(function(authClient) {
const projectId = process.env.GCLOUD_PROJECT;
const fullyQualifiedName = 'projects/' + projectId
+ '/configs/' + configName
+ '/variables/' + variableName;
runtimeConfig.projects.configs.variables.get({
auth: authClient,
name: fullyQualifiedName,
}, function(err, res) {
if (err) {
reject(err);
return;
}
const variable = res.data;
if (typeof variable.text !== 'undefined') {
resolve(variable.text);
} else if (typeof variable.value !== 'undefined') {
resolve(Buffer.from(variable.value, 'base64').toString());
} else {
reject(new Error('Property text or value not defined'));
}
});
});
});
} | javascript | function getVariable(configName, variableName) {
return new Promise(function(resolve, reject) {
auth().then(function(authClient) {
const projectId = process.env.GCLOUD_PROJECT;
const fullyQualifiedName = 'projects/' + projectId
+ '/configs/' + configName
+ '/variables/' + variableName;
runtimeConfig.projects.configs.variables.get({
auth: authClient,
name: fullyQualifiedName,
}, function(err, res) {
if (err) {
reject(err);
return;
}
const variable = res.data;
if (typeof variable.text !== 'undefined') {
resolve(variable.text);
} else if (typeof variable.value !== 'undefined') {
resolve(Buffer.from(variable.value, 'base64').toString());
} else {
reject(new Error('Property text or value not defined'));
}
});
});
});
} | [
"function",
"getVariable",
"(",
"configName",
",",
"variableName",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"auth",
"(",
")",
".",
"then",
"(",
"function",
"(",
"authClient",
")",
"{",
"const",
"projectId",
"=",
"process",
".",
"env",
".",
"GCLOUD_PROJECT",
";",
"const",
"fullyQualifiedName",
"=",
"'projects/'",
"+",
"projectId",
"+",
"'/configs/'",
"+",
"configName",
"+",
"'/variables/'",
"+",
"variableName",
";",
"runtimeConfig",
".",
"projects",
".",
"configs",
".",
"variables",
".",
"get",
"(",
"{",
"auth",
":",
"authClient",
",",
"name",
":",
"fullyQualifiedName",
",",
"}",
",",
"function",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"return",
";",
"}",
"const",
"variable",
"=",
"res",
".",
"data",
";",
"if",
"(",
"typeof",
"variable",
".",
"text",
"!==",
"'undefined'",
")",
"{",
"resolve",
"(",
"variable",
".",
"text",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"variable",
".",
"value",
"!==",
"'undefined'",
")",
"{",
"resolve",
"(",
"Buffer",
".",
"from",
"(",
"variable",
".",
"value",
",",
"'base64'",
")",
".",
"toString",
"(",
")",
")",
";",
"}",
"else",
"{",
"reject",
"(",
"new",
"Error",
"(",
"'Property text or value not defined'",
")",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| runtimeConfig.getVariable
@desc Reads a runtime config value
@param {string} configName The config name of the variable to return
@param {string} variableName The variable name of the variable to return
@return {Promise} Promise that resolves the variable value | [
"runtimeConfig",
".",
"getVariable"
]
| 272eb48644df13939fcec458656b1f155f1b0f29 | https://github.com/fredriks/cloud-functions-runtime-config/blob/272eb48644df13939fcec458656b1f155f1b0f29/src/index.js#L33-L61 | train |
Azure/azure-relay-node | hyco-ws/lib/HybridConnectionWebSocketServer.js | function() {
// choose from the sub-protocols
if (typeof self.options.handleProtocols == 'function') {
var protList = (protocols || '').split(/, */);
var callbackCalled = false;
self.options.handleProtocols(protList, function(result, protocol) {
callbackCalled = true;
if (!result) abortConnection(socket, 401, 'Unauthorized');
else completeHybiUpgrade2(protocol);
});
if (!callbackCalled) {
// the handleProtocols handler never called our callback
abortConnection(socket, 501, 'Could not process protocols');
}
return;
} else {
if (typeof protocols !== 'undefined') {
completeHybiUpgrade2(protocols.split(/, */)[0]);
}
else {
completeHybiUpgrade2();
}
}
} | javascript | function() {
// choose from the sub-protocols
if (typeof self.options.handleProtocols == 'function') {
var protList = (protocols || '').split(/, */);
var callbackCalled = false;
self.options.handleProtocols(protList, function(result, protocol) {
callbackCalled = true;
if (!result) abortConnection(socket, 401, 'Unauthorized');
else completeHybiUpgrade2(protocol);
});
if (!callbackCalled) {
// the handleProtocols handler never called our callback
abortConnection(socket, 501, 'Could not process protocols');
}
return;
} else {
if (typeof protocols !== 'undefined') {
completeHybiUpgrade2(protocols.split(/, */)[0]);
}
else {
completeHybiUpgrade2();
}
}
} | [
"function",
"(",
")",
"{",
"if",
"(",
"typeof",
"self",
".",
"options",
".",
"handleProtocols",
"==",
"'function'",
")",
"{",
"var",
"protList",
"=",
"(",
"protocols",
"||",
"''",
")",
".",
"split",
"(",
"/",
", *",
"/",
")",
";",
"var",
"callbackCalled",
"=",
"false",
";",
"self",
".",
"options",
".",
"handleProtocols",
"(",
"protList",
",",
"function",
"(",
"result",
",",
"protocol",
")",
"{",
"callbackCalled",
"=",
"true",
";",
"if",
"(",
"!",
"result",
")",
"abortConnection",
"(",
"socket",
",",
"401",
",",
"'Unauthorized'",
")",
";",
"else",
"completeHybiUpgrade2",
"(",
"protocol",
")",
";",
"}",
")",
";",
"if",
"(",
"!",
"callbackCalled",
")",
"{",
"abortConnection",
"(",
"socket",
",",
"501",
",",
"'Could not process protocols'",
")",
";",
"}",
"return",
";",
"}",
"else",
"{",
"if",
"(",
"typeof",
"protocols",
"!==",
"'undefined'",
")",
"{",
"completeHybiUpgrade2",
"(",
"protocols",
".",
"split",
"(",
"/",
", *",
"/",
")",
"[",
"0",
"]",
")",
";",
"}",
"else",
"{",
"completeHybiUpgrade2",
"(",
")",
";",
"}",
"}",
"}"
]
| optionally call external protocol selection handler before calling completeHybiUpgrade2 | [
"optionally",
"call",
"external",
"protocol",
"selection",
"handler",
"before",
"calling",
"completeHybiUpgrade2"
]
| 3c996efc240aa556fa5d17e40fa9ba463a98a8d5 | https://github.com/Azure/azure-relay-node/blob/3c996efc240aa556fa5d17e40fa9ba463a98a8d5/hyco-ws/lib/HybridConnectionWebSocketServer.js#L252-L275 | train |
|
Azure/azure-relay-node | hyco-https/lib/_hyco_errors.js | internalAssert | function internalAssert(condition, message) {
if (!condition) {
throw new AssertionError({
message,
actual: false,
expected: true,
operator: '=='
});
}
} | javascript | function internalAssert(condition, message) {
if (!condition) {
throw new AssertionError({
message,
actual: false,
expected: true,
operator: '=='
});
}
} | [
"function",
"internalAssert",
"(",
"condition",
",",
"message",
")",
"{",
"if",
"(",
"!",
"condition",
")",
"{",
"throw",
"new",
"AssertionError",
"(",
"{",
"message",
",",
"actual",
":",
"false",
",",
"expected",
":",
"true",
",",
"operator",
":",
"'=='",
"}",
")",
";",
"}",
"}"
]
| This is defined here instead of using the assert module to avoid a circular dependency. The effect is largely the same. | [
"This",
"is",
"defined",
"here",
"instead",
"of",
"using",
"the",
"assert",
"module",
"to",
"avoid",
"a",
"circular",
"dependency",
".",
"The",
"effect",
"is",
"largely",
"the",
"same",
"."
]
| 3c996efc240aa556fa5d17e40fa9ba463a98a8d5 | https://github.com/Azure/azure-relay-node/blob/3c996efc240aa556fa5d17e40fa9ba463a98a8d5/hyco-https/lib/_hyco_errors.js#L476-L485 | train |
Azure/azure-relay-node | hyco-https/lib/_hyco_errors.js | isStackOverflowError | function isStackOverflowError(err) {
if (maxStack_ErrorMessage === undefined) {
try {
function overflowStack() { overflowStack(); }
overflowStack();
} catch (err) {
maxStack_ErrorMessage = err.message;
maxStack_ErrorName = err.name;
}
}
return err.name === maxStack_ErrorName &&
err.message === maxStack_ErrorMessage;
} | javascript | function isStackOverflowError(err) {
if (maxStack_ErrorMessage === undefined) {
try {
function overflowStack() { overflowStack(); }
overflowStack();
} catch (err) {
maxStack_ErrorMessage = err.message;
maxStack_ErrorName = err.name;
}
}
return err.name === maxStack_ErrorName &&
err.message === maxStack_ErrorMessage;
} | [
"function",
"isStackOverflowError",
"(",
"err",
")",
"{",
"if",
"(",
"maxStack_ErrorMessage",
"===",
"undefined",
")",
"{",
"try",
"{",
"function",
"overflowStack",
"(",
")",
"{",
"overflowStack",
"(",
")",
";",
"}",
"overflowStack",
"(",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"maxStack_ErrorMessage",
"=",
"err",
".",
"message",
";",
"maxStack_ErrorName",
"=",
"err",
".",
"name",
";",
"}",
"}",
"return",
"err",
".",
"name",
"===",
"maxStack_ErrorName",
"&&",
"err",
".",
"message",
"===",
"maxStack_ErrorMessage",
";",
"}"
]
| Returns true if `err.name` and `err.message` are equal to engine-specific
values indicating max call stack size has been exceeded.
"Maximum call stack size exceeded" in V8.
@param {Error} err
@returns {boolean} | [
"Returns",
"true",
"if",
"err",
".",
"name",
"and",
"err",
".",
"message",
"are",
"equal",
"to",
"engine",
"-",
"specific",
"values",
"indicating",
"max",
"call",
"stack",
"size",
"has",
"been",
"exceeded",
".",
"Maximum",
"call",
"stack",
"size",
"exceeded",
"in",
"V8",
"."
]
| 3c996efc240aa556fa5d17e40fa9ba463a98a8d5 | https://github.com/Azure/azure-relay-node/blob/3c996efc240aa556fa5d17e40fa9ba463a98a8d5/hyco-https/lib/_hyco_errors.js#L675-L688 | train |
adrianhall/winston-splunk-httplogger | index.js | function (config) {
winston.Transport.call(this, config);
/** @property {string} name - the name of the transport */
this.name = 'SplunkStreamEvent';
/** @property {string} level - the minimum level to log */
this.level = config.level || 'info';
// Verify that we actually have a splunk object and a token
if (!config.splunk || !config.splunk.token) {
throw new Error('Invalid Configuration: options.splunk is invalid');
}
// If source/sourcetype are mentioned in the splunk object, then store the
// defaults in this and delete from the splunk object
this.defaultMetadata = {
source: 'winston',
sourcetype: 'winston-splunk-logger'
};
if (config.splunk.source) {
this.defaultMetadata.source = config.splunk.source;
delete config.splunk.source;
}
if (config.splunk.sourcetype) {
this.defaultMetadata.sourcetype = config.splunk.sourcetype;
delete config.splunk.sourcetype;
}
// This gets around a problem with setting maxBatchCount
config.splunk.maxBatchCount = 1;
this.server = new SplunkLogger(config.splunk);
// Override the default event formatter
if (config.splunk.eventFormatter) {
this.server.eventFormatter = config.splunk.eventFormatter;
}
} | javascript | function (config) {
winston.Transport.call(this, config);
/** @property {string} name - the name of the transport */
this.name = 'SplunkStreamEvent';
/** @property {string} level - the minimum level to log */
this.level = config.level || 'info';
// Verify that we actually have a splunk object and a token
if (!config.splunk || !config.splunk.token) {
throw new Error('Invalid Configuration: options.splunk is invalid');
}
// If source/sourcetype are mentioned in the splunk object, then store the
// defaults in this and delete from the splunk object
this.defaultMetadata = {
source: 'winston',
sourcetype: 'winston-splunk-logger'
};
if (config.splunk.source) {
this.defaultMetadata.source = config.splunk.source;
delete config.splunk.source;
}
if (config.splunk.sourcetype) {
this.defaultMetadata.sourcetype = config.splunk.sourcetype;
delete config.splunk.sourcetype;
}
// This gets around a problem with setting maxBatchCount
config.splunk.maxBatchCount = 1;
this.server = new SplunkLogger(config.splunk);
// Override the default event formatter
if (config.splunk.eventFormatter) {
this.server.eventFormatter = config.splunk.eventFormatter;
}
} | [
"function",
"(",
"config",
")",
"{",
"winston",
".",
"Transport",
".",
"call",
"(",
"this",
",",
"config",
")",
";",
"this",
".",
"name",
"=",
"'SplunkStreamEvent'",
";",
"this",
".",
"level",
"=",
"config",
".",
"level",
"||",
"'info'",
";",
"if",
"(",
"!",
"config",
".",
"splunk",
"||",
"!",
"config",
".",
"splunk",
".",
"token",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid Configuration: options.splunk is invalid'",
")",
";",
"}",
"this",
".",
"defaultMetadata",
"=",
"{",
"source",
":",
"'winston'",
",",
"sourcetype",
":",
"'winston-splunk-logger'",
"}",
";",
"if",
"(",
"config",
".",
"splunk",
".",
"source",
")",
"{",
"this",
".",
"defaultMetadata",
".",
"source",
"=",
"config",
".",
"splunk",
".",
"source",
";",
"delete",
"config",
".",
"splunk",
".",
"source",
";",
"}",
"if",
"(",
"config",
".",
"splunk",
".",
"sourcetype",
")",
"{",
"this",
".",
"defaultMetadata",
".",
"sourcetype",
"=",
"config",
".",
"splunk",
".",
"sourcetype",
";",
"delete",
"config",
".",
"splunk",
".",
"sourcetype",
";",
"}",
"config",
".",
"splunk",
".",
"maxBatchCount",
"=",
"1",
";",
"this",
".",
"server",
"=",
"new",
"SplunkLogger",
"(",
"config",
".",
"splunk",
")",
";",
"if",
"(",
"config",
".",
"splunk",
".",
"eventFormatter",
")",
"{",
"this",
".",
"server",
".",
"eventFormatter",
"=",
"config",
".",
"splunk",
".",
"eventFormatter",
";",
"}",
"}"
]
| A class that implements a Winston transport provider for Splunk HTTP Event Collector
@param {object} config - Configuration settings for a new Winston transport
@param {string} [config.level=info] - the minimum level to log
@param {object} config.splunk - the Splunk Logger settings
@param {string} config.splunk.token - the Splunk HTTP Event Collector token
@param {string} [config.splunk.source=winston] - the source for the events sent to Splunk
@param {string} [config.splunk.sourcetype=winston-splunk-logger] - the sourcetype for the events sent to Splunk
@param {string} [config.splunk.host=localhost] - the Splunk HTTP Event Collector host
@param {number} [config.splunk.maxRetries=0] - How many times to retry the splunk logger
@param {number} [config.splunk.port=8088] - the Splunk HTTP Event Collector port
@param {string} [config.splunk.path=/services/collector/event/1.0] - URL path to use
@param {string} [config.splunk.protocol=https] - the protocol to use
@param {string} [config.splunk.url] - URL string to pass to url.parse for the information
@param {function} [config.splunk.eventFormatter] - Formats events, returning an event as a string, <code>function(message, severity)</code>
@param {string} [config.level=info] - Logging level to use, will show up as the <code>severity</code> field of an event, see
[SplunkLogger.levels]{@link SplunkLogger#levels} for common levels.
@param {number} [config.batchInterval=0] - Automatically flush events after this many milliseconds.
When set to a non-positive value, events will be sent one by one. This setting is ignored when non-positive.
@param {number} [config.maxBatchSize=0] - Automatically flush events after the size of queued
events exceeds this many bytes. This setting is ignored when non-positive.
@param {number} [config.maxBatchCount=1] - Automatically flush events after this many
events have been queued. Defaults to flush immediately on sending an event. This setting is ignored when non-positive.
@constructor | [
"A",
"class",
"that",
"implements",
"a",
"Winston",
"transport",
"provider",
"for",
"Splunk",
"HTTP",
"Event",
"Collector"
]
| 58be3091b01f88b3230b2f21d6bdfe4055dd2017 | https://github.com/adrianhall/winston-splunk-httplogger/blob/58be3091b01f88b3230b2f21d6bdfe4055dd2017/index.js#L59-L96 | train |
|
AoDev/css-byebye | lib/css-byebye.js | regexize | function regexize (rulesToRemove) {
var rulesRegexes = []
for (var i = 0, l = rulesToRemove.length; i < l; i++) {
if (typeof rulesToRemove[i] === 'string') {
rulesRegexes.push(new RegExp('^\\s*' + escapeRegExp(rulesToRemove[i]) + '\\s*$'))
} else {
rulesRegexes.push(rulesToRemove[i])
}
}
return rulesRegexes
} | javascript | function regexize (rulesToRemove) {
var rulesRegexes = []
for (var i = 0, l = rulesToRemove.length; i < l; i++) {
if (typeof rulesToRemove[i] === 'string') {
rulesRegexes.push(new RegExp('^\\s*' + escapeRegExp(rulesToRemove[i]) + '\\s*$'))
} else {
rulesRegexes.push(rulesToRemove[i])
}
}
return rulesRegexes
} | [
"function",
"regexize",
"(",
"rulesToRemove",
")",
"{",
"var",
"rulesRegexes",
"=",
"[",
"]",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"rulesToRemove",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"if",
"(",
"typeof",
"rulesToRemove",
"[",
"i",
"]",
"===",
"'string'",
")",
"{",
"rulesRegexes",
".",
"push",
"(",
"new",
"RegExp",
"(",
"'^\\\\s*'",
"+",
"\\\\",
"+",
"escapeRegExp",
"(",
"rulesToRemove",
"[",
"i",
"]",
")",
")",
")",
"}",
"else",
"'\\\\s*$'",
"}",
"\\\\",
"}"
]
| Turn strings from rules to remove into a regexp to concat them later
@param {Mixed Array} rulesToRemove
@return {RegExp Array} | [
"Turn",
"strings",
"from",
"rules",
"to",
"remove",
"into",
"a",
"regexp",
"to",
"concat",
"them",
"later"
]
| ff8245ec596fdabd6cce4f5f3e4c36396359329a | https://github.com/AoDev/css-byebye/blob/ff8245ec596fdabd6cce4f5f3e4c36396359329a/lib/css-byebye.js#L21-L31 | train |
AoDev/css-byebye | lib/css-byebye.js | concatRegexes | function concatRegexes (regexes) {
var rconcat = ''
if (Array.isArray(regexes)) {
for (var i = 0, l = regexes.length; i < l; i++) {
rconcat += regexes[i].source + '|'
}
rconcat = rconcat.substr(0, rconcat.length - 1)
return new RegExp(rconcat)
}
} | javascript | function concatRegexes (regexes) {
var rconcat = ''
if (Array.isArray(regexes)) {
for (var i = 0, l = regexes.length; i < l; i++) {
rconcat += regexes[i].source + '|'
}
rconcat = rconcat.substr(0, rconcat.length - 1)
return new RegExp(rconcat)
}
} | [
"function",
"concatRegexes",
"(",
"regexes",
")",
"{",
"var",
"rconcat",
"=",
"''",
"if",
"(",
"Array",
".",
"isArray",
"(",
"regexes",
")",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"regexes",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"rconcat",
"+=",
"regexes",
"[",
"i",
"]",
".",
"source",
"+",
"'|'",
"}",
"rconcat",
"=",
"rconcat",
".",
"substr",
"(",
"0",
",",
"rconcat",
".",
"length",
"-",
"1",
")",
"return",
"new",
"RegExp",
"(",
"rconcat",
")",
"}",
"}"
]
| Concat various regular expressions into one
@param {RegExp Array} regexes
@return {RegExp} concatanated regexp | [
"Concat",
"various",
"regular",
"expressions",
"into",
"one"
]
| ff8245ec596fdabd6cce4f5f3e4c36396359329a | https://github.com/AoDev/css-byebye/blob/ff8245ec596fdabd6cce4f5f3e4c36396359329a/lib/css-byebye.js#L38-L50 | train |
kimkha/loopback3-xTotalCount | index.js | function (ctx, next) {
var filter;
if (ctx.args && ctx.args.filter) {
filter = ctx.args.filter.where;
}
if (!ctx.res._headerSent) {
this.count(filter, function (err, count) {
ctx.res.set('X-Total-Count', count);
next();
});
} else {
next();
}
} | javascript | function (ctx, next) {
var filter;
if (ctx.args && ctx.args.filter) {
filter = ctx.args.filter.where;
}
if (!ctx.res._headerSent) {
this.count(filter, function (err, count) {
ctx.res.set('X-Total-Count', count);
next();
});
} else {
next();
}
} | [
"function",
"(",
"ctx",
",",
"next",
")",
"{",
"var",
"filter",
";",
"if",
"(",
"ctx",
".",
"args",
"&&",
"ctx",
".",
"args",
".",
"filter",
")",
"{",
"filter",
"=",
"ctx",
".",
"args",
".",
"filter",
".",
"where",
";",
"}",
"if",
"(",
"!",
"ctx",
".",
"res",
".",
"_headerSent",
")",
"{",
"this",
".",
"count",
"(",
"filter",
",",
"function",
"(",
"err",
",",
"count",
")",
"{",
"ctx",
".",
"res",
".",
"set",
"(",
"'X-Total-Count'",
",",
"count",
")",
";",
"next",
"(",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"next",
"(",
")",
";",
"}",
"}"
]
| Set X-Total-Count for all search requests | [
"Set",
"X",
"-",
"Total",
"-",
"Count",
"for",
"all",
"search",
"requests"
]
| 61d45d74b0e767c6897859d347bc557a13c436cb | https://github.com/kimkha/loopback3-xTotalCount/blob/61d45d74b0e767c6897859d347bc557a13c436cb/index.js#L5-L19 | train |
|
bbc/slayer | lib/core.js | configureFilters | function configureFilters(config){
if (typeof config.minPeakHeight !== 'number' || isNaN(config.minPeakHeight)){
throw new TypeError('config.minPeakHeight should be a numeric value. Was: ' + String(config.minPeakHeight));
}
this.filters.push(function minHeightFilter(item){
return item >= config.minPeakHeight;
});
} | javascript | function configureFilters(config){
if (typeof config.minPeakHeight !== 'number' || isNaN(config.minPeakHeight)){
throw new TypeError('config.minPeakHeight should be a numeric value. Was: ' + String(config.minPeakHeight));
}
this.filters.push(function minHeightFilter(item){
return item >= config.minPeakHeight;
});
} | [
"function",
"configureFilters",
"(",
"config",
")",
"{",
"if",
"(",
"typeof",
"config",
".",
"minPeakHeight",
"!==",
"'number'",
"||",
"isNaN",
"(",
"config",
".",
"minPeakHeight",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'config.minPeakHeight should be a numeric value. Was: '",
"+",
"String",
"(",
"config",
".",
"minPeakHeight",
")",
")",
";",
"}",
"this",
".",
"filters",
".",
"push",
"(",
"function",
"minHeightFilter",
"(",
"item",
")",
"{",
"return",
"item",
">=",
"config",
".",
"minPeakHeight",
";",
"}",
")",
";",
"}"
]
| Configures the internal filters of a slayer instance | [
"Configures",
"the",
"internal",
"filters",
"of",
"a",
"slayer",
"instance"
]
| 4b0cdc5080f46f5940c89c081dbad16e2be4e021 | https://github.com/bbc/slayer/blob/4b0cdc5080f46f5940c89c081dbad16e2be4e021/lib/core.js#L72-L80 | train |
bbc/slayer | lib/core.js | filterDataItem | function filterDataItem(item){
return this.filters.some(function(filter){
return filter.call(null, item);
}) ? item : null;
} | javascript | function filterDataItem(item){
return this.filters.some(function(filter){
return filter.call(null, item);
}) ? item : null;
} | [
"function",
"filterDataItem",
"(",
"item",
")",
"{",
"return",
"this",
".",
"filters",
".",
"some",
"(",
"function",
"(",
"filter",
")",
"{",
"return",
"filter",
".",
"call",
"(",
"null",
",",
"item",
")",
";",
"}",
")",
"?",
"item",
":",
"null",
";",
"}"
]
| Filters out any time series value which does not satisfy the filter.
@param item {Number}
@returns {Boolean} | [
"Filters",
"out",
"any",
"time",
"series",
"value",
"which",
"does",
"not",
"satisfy",
"the",
"filter",
"."
]
| 4b0cdc5080f46f5940c89c081dbad16e2be4e021 | https://github.com/bbc/slayer/blob/4b0cdc5080f46f5940c89c081dbad16e2be4e021/lib/core.js#L87-L91 | train |
medz/webpack-laravel-mix-manifest | src/main.js | WebpackLaravelMixManifest | function WebpackLaravelMixManifest({ filename = null, transform = null } = {}) {
this.filename = filename ? filename : 'mix-manifest.json';
this.transform = transform instanceof Function ? transform : require('./transform');
} | javascript | function WebpackLaravelMixManifest({ filename = null, transform = null } = {}) {
this.filename = filename ? filename : 'mix-manifest.json';
this.transform = transform instanceof Function ? transform : require('./transform');
} | [
"function",
"WebpackLaravelMixManifest",
"(",
"{",
"filename",
"=",
"null",
",",
"transform",
"=",
"null",
"}",
"=",
"{",
"}",
")",
"{",
"this",
".",
"filename",
"=",
"filename",
"?",
"filename",
":",
"'mix-manifest.json'",
";",
"this",
".",
"transform",
"=",
"transform",
"instanceof",
"Function",
"?",
"transform",
":",
"require",
"(",
"'./transform'",
")",
";",
"}"
]
| Create the plugin class.
@param { filename: string|null, transform: Function|null } options | [
"Create",
"the",
"plugin",
"class",
"."
]
| aaad90ebb30e8697dccf8ed2ae537af85fc635f4 | https://github.com/medz/webpack-laravel-mix-manifest/blob/aaad90ebb30e8697dccf8ed2ae537af85fc635f4/src/main.js#L5-L8 | train |
bbc/slayer | lib/readers/_common.js | objectMapper | function objectMapper(originalData, y, i){
return this.getItem({
x: this.getValueX(originalData[i], i),
y: y
}, originalData[i], i);
} | javascript | function objectMapper(originalData, y, i){
return this.getItem({
x: this.getValueX(originalData[i], i),
y: y
}, originalData[i], i);
} | [
"function",
"objectMapper",
"(",
"originalData",
",",
"y",
",",
"i",
")",
"{",
"return",
"this",
".",
"getItem",
"(",
"{",
"x",
":",
"this",
".",
"getValueX",
"(",
"originalData",
"[",
"i",
"]",
",",
"i",
")",
",",
"y",
":",
"y",
"}",
",",
"originalData",
"[",
"i",
"]",
",",
"i",
")",
";",
"}"
]
| Remaps an initial item to a common working structure.
It is intended to be bound to a slayer instance.
@this {Slayer}
@param originalData {Array} The original array of data
@param y {Number} The value number detected as being a spike
@param i {Number} The index location of `y` in `originalData`
@returns {{x: *, y: Number}} | [
"Remaps",
"an",
"initial",
"item",
"to",
"a",
"common",
"working",
"structure",
"."
]
| 4b0cdc5080f46f5940c89c081dbad16e2be4e021 | https://github.com/bbc/slayer/blob/4b0cdc5080f46f5940c89c081dbad16e2be4e021/lib/readers/_common.js#L35-L40 | train |
andywer/postcss-debug | webdebugger/build/app.js | function () {
if (!specialPropKeyWarningShown) {
specialPropKeyWarningShown = true;
process.env.NODE_ENV !== 'production' ? warning(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0;
}
return undefined;
} | javascript | function () {
if (!specialPropKeyWarningShown) {
specialPropKeyWarningShown = true;
process.env.NODE_ENV !== 'production' ? warning(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0;
}
return undefined;
} | [
"function",
"(",
")",
"{",
"if",
"(",
"!",
"specialPropKeyWarningShown",
")",
"{",
"specialPropKeyWarningShown",
"=",
"true",
";",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'production'",
"?",
"warning",
"(",
"false",
",",
"'%s: `key` is not a prop. Trying to access it will result '",
"+",
"'in `undefined` being returned. If you need to access the same '",
"+",
"'value within the child component, you should pass it as a different '",
"+",
"'prop. (https://fb.me/react-special-props)'",
",",
"displayName",
")",
":",
"void",
"0",
";",
"}",
"return",
"undefined",
";",
"}"
]
| Create dummy `key` and `ref` property to `props` to warn users against its use | [
"Create",
"dummy",
"key",
"and",
"ref",
"property",
"to",
"props",
"to",
"warn",
"users",
"against",
"its",
"use"
]
| e245354e057b230c008f5b4a72096d134c2fe8cf | https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L1080-L1086 | train |
|
andywer/postcss-debug | webdebugger/build/app.js | function (transaction) {
if (this._pendingElement != null) {
ReactReconciler.receiveComponent(this, this._pendingElement, transaction, this._context);
} else if (this._pendingStateQueue !== null || this._pendingForceUpdate) {
this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context);
} else {
this._updateBatchNumber = null;
}
} | javascript | function (transaction) {
if (this._pendingElement != null) {
ReactReconciler.receiveComponent(this, this._pendingElement, transaction, this._context);
} else if (this._pendingStateQueue !== null || this._pendingForceUpdate) {
this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context);
} else {
this._updateBatchNumber = null;
}
} | [
"function",
"(",
"transaction",
")",
"{",
"if",
"(",
"this",
".",
"_pendingElement",
"!=",
"null",
")",
"{",
"ReactReconciler",
".",
"receiveComponent",
"(",
"this",
",",
"this",
".",
"_pendingElement",
",",
"transaction",
",",
"this",
".",
"_context",
")",
";",
"}",
"else",
"if",
"(",
"this",
".",
"_pendingStateQueue",
"!==",
"null",
"||",
"this",
".",
"_pendingForceUpdate",
")",
"{",
"this",
".",
"updateComponent",
"(",
"transaction",
",",
"this",
".",
"_currentElement",
",",
"this",
".",
"_currentElement",
",",
"this",
".",
"_context",
",",
"this",
".",
"_context",
")",
";",
"}",
"else",
"{",
"this",
".",
"_updateBatchNumber",
"=",
"null",
";",
"}",
"}"
]
| If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate`
is set, update the component.
@param {ReactReconcileTransaction} transaction
@internal | [
"If",
"any",
"of",
"_pendingElement",
"_pendingStateQueue",
"or",
"_pendingForceUpdate",
"is",
"set",
"update",
"the",
"component",
"."
]
| e245354e057b230c008f5b4a72096d134c2fe8cf | https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L6091-L6099 | train |
|
andywer/postcss-debug | webdebugger/build/app.js | function (inst, registrationName) {
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.willDeleteListener) {
PluginModule.willDeleteListener(inst, registrationName);
}
var bankForRegistrationName = listenerBank[registrationName];
// TODO: This should never be null -- when is it?
if (bankForRegistrationName) {
var key = getDictionaryKey(inst);
delete bankForRegistrationName[key];
}
} | javascript | function (inst, registrationName) {
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.willDeleteListener) {
PluginModule.willDeleteListener(inst, registrationName);
}
var bankForRegistrationName = listenerBank[registrationName];
// TODO: This should never be null -- when is it?
if (bankForRegistrationName) {
var key = getDictionaryKey(inst);
delete bankForRegistrationName[key];
}
} | [
"function",
"(",
"inst",
",",
"registrationName",
")",
"{",
"var",
"PluginModule",
"=",
"EventPluginRegistry",
".",
"registrationNameModules",
"[",
"registrationName",
"]",
";",
"if",
"(",
"PluginModule",
"&&",
"PluginModule",
".",
"willDeleteListener",
")",
"{",
"PluginModule",
".",
"willDeleteListener",
"(",
"inst",
",",
"registrationName",
")",
";",
"}",
"var",
"bankForRegistrationName",
"=",
"listenerBank",
"[",
"registrationName",
"]",
";",
"if",
"(",
"bankForRegistrationName",
")",
"{",
"var",
"key",
"=",
"getDictionaryKey",
"(",
"inst",
")",
";",
"delete",
"bankForRegistrationName",
"[",
"key",
"]",
";",
"}",
"}"
]
| Deletes a listener from the registration bank.
@param {object} inst The instance, which is the source of events.
@param {string} registrationName Name of listener (e.g. `onClick`). | [
"Deletes",
"a",
"listener",
"from",
"the",
"registration",
"bank",
"."
]
| e245354e057b230c008f5b4a72096d134c2fe8cf | https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L9477-L9489 | train |
|
andywer/postcss-debug | webdebugger/build/app.js | function (inst) {
var key = getDictionaryKey(inst);
for (var registrationName in listenerBank) {
if (!listenerBank.hasOwnProperty(registrationName)) {
continue;
}
if (!listenerBank[registrationName][key]) {
continue;
}
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.willDeleteListener) {
PluginModule.willDeleteListener(inst, registrationName);
}
delete listenerBank[registrationName][key];
}
} | javascript | function (inst) {
var key = getDictionaryKey(inst);
for (var registrationName in listenerBank) {
if (!listenerBank.hasOwnProperty(registrationName)) {
continue;
}
if (!listenerBank[registrationName][key]) {
continue;
}
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.willDeleteListener) {
PluginModule.willDeleteListener(inst, registrationName);
}
delete listenerBank[registrationName][key];
}
} | [
"function",
"(",
"inst",
")",
"{",
"var",
"key",
"=",
"getDictionaryKey",
"(",
"inst",
")",
";",
"for",
"(",
"var",
"registrationName",
"in",
"listenerBank",
")",
"{",
"if",
"(",
"!",
"listenerBank",
".",
"hasOwnProperty",
"(",
"registrationName",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"!",
"listenerBank",
"[",
"registrationName",
"]",
"[",
"key",
"]",
")",
"{",
"continue",
";",
"}",
"var",
"PluginModule",
"=",
"EventPluginRegistry",
".",
"registrationNameModules",
"[",
"registrationName",
"]",
";",
"if",
"(",
"PluginModule",
"&&",
"PluginModule",
".",
"willDeleteListener",
")",
"{",
"PluginModule",
".",
"willDeleteListener",
"(",
"inst",
",",
"registrationName",
")",
";",
"}",
"delete",
"listenerBank",
"[",
"registrationName",
"]",
"[",
"key",
"]",
";",
"}",
"}"
]
| Deletes all listeners for the DOM element with the supplied ID.
@param {object} inst The instance, which is the source of events. | [
"Deletes",
"all",
"listeners",
"for",
"the",
"DOM",
"element",
"with",
"the",
"supplied",
"ID",
"."
]
| e245354e057b230c008f5b4a72096d134c2fe8cf | https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L9496-L9514 | train |
|
andywer/postcss-debug | webdebugger/build/app.js | batchedMountComponentIntoNode | function batchedMountComponentIntoNode(componentInstance, container, shouldReuseMarkup, context) {
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(
/* useCreateElement */
!shouldReuseMarkup && ReactDOMFeatureFlags.useCreateElement);
transaction.perform(mountComponentIntoNode, null, componentInstance, container, transaction, shouldReuseMarkup, context);
ReactUpdates.ReactReconcileTransaction.release(transaction);
} | javascript | function batchedMountComponentIntoNode(componentInstance, container, shouldReuseMarkup, context) {
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(
/* useCreateElement */
!shouldReuseMarkup && ReactDOMFeatureFlags.useCreateElement);
transaction.perform(mountComponentIntoNode, null, componentInstance, container, transaction, shouldReuseMarkup, context);
ReactUpdates.ReactReconcileTransaction.release(transaction);
} | [
"function",
"batchedMountComponentIntoNode",
"(",
"componentInstance",
",",
"container",
",",
"shouldReuseMarkup",
",",
"context",
")",
"{",
"var",
"transaction",
"=",
"ReactUpdates",
".",
"ReactReconcileTransaction",
".",
"getPooled",
"(",
"!",
"shouldReuseMarkup",
"&&",
"ReactDOMFeatureFlags",
".",
"useCreateElement",
")",
";",
"transaction",
".",
"perform",
"(",
"mountComponentIntoNode",
",",
"null",
",",
"componentInstance",
",",
"container",
",",
"transaction",
",",
"shouldReuseMarkup",
",",
"context",
")",
";",
"ReactUpdates",
".",
"ReactReconcileTransaction",
".",
"release",
"(",
"transaction",
")",
";",
"}"
]
| Batched mount.
@param {ReactComponent} componentInstance The instance to mount.
@param {DOMElement} container DOM element to mount into.
@param {boolean} shouldReuseMarkup If true, do not insert markup | [
"Batched",
"mount",
"."
]
| e245354e057b230c008f5b4a72096d134c2fe8cf | https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L10375-L10381 | train |
andywer/postcss-debug | webdebugger/build/app.js | hasNonRootReactChild | function hasNonRootReactChild(container) {
var rootEl = getReactRootElementInContainer(container);
if (rootEl) {
var inst = ReactDOMComponentTree.getInstanceFromNode(rootEl);
return !!(inst && inst._hostParent);
}
} | javascript | function hasNonRootReactChild(container) {
var rootEl = getReactRootElementInContainer(container);
if (rootEl) {
var inst = ReactDOMComponentTree.getInstanceFromNode(rootEl);
return !!(inst && inst._hostParent);
}
} | [
"function",
"hasNonRootReactChild",
"(",
"container",
")",
"{",
"var",
"rootEl",
"=",
"getReactRootElementInContainer",
"(",
"container",
")",
";",
"if",
"(",
"rootEl",
")",
"{",
"var",
"inst",
"=",
"ReactDOMComponentTree",
".",
"getInstanceFromNode",
"(",
"rootEl",
")",
";",
"return",
"!",
"!",
"(",
"inst",
"&&",
"inst",
".",
"_hostParent",
")",
";",
"}",
"}"
]
| True if the supplied DOM node has a direct React-rendered child that is
not a React root element. Useful for warning in `render`,
`unmountComponentAtNode`, etc.
@param {?DOMElement} node The candidate DOM node.
@return {boolean} True if the DOM element contains a direct child that was
rendered by React but is not a root element.
@internal | [
"True",
"if",
"the",
"supplied",
"DOM",
"node",
"has",
"a",
"direct",
"React",
"-",
"rendered",
"child",
"that",
"is",
"not",
"a",
"React",
"root",
"element",
".",
"Useful",
"for",
"warning",
"in",
"render",
"unmountComponentAtNode",
"etc",
"."
]
| e245354e057b230c008f5b4a72096d134c2fe8cf | https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L10421-L10427 | train |
andywer/postcss-debug | webdebugger/build/app.js | function (nextElement, container, shouldReuseMarkup, context) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case.
process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0;
!(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : _prodInvariant('37') : void 0;
ReactBrowserEventEmitter.ensureScrollValueMonitoring();
var componentInstance = instantiateReactComponent(nextElement, false);
// The initial render is synchronous but any updates that happen during
// rendering, in componentWillMount or componentDidMount, will be batched
// according to the current batching strategy.
ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, container, shouldReuseMarkup, context);
var wrapperID = componentInstance._instance.rootID;
instancesByReactRootID[wrapperID] = componentInstance;
if (process.env.NODE_ENV !== 'production') {
// The instance here is TopLevelWrapper so we report mount for its child.
ReactInstrumentation.debugTool.onMountRootComponent(componentInstance._renderedComponent._debugID);
}
return componentInstance;
} | javascript | function (nextElement, container, shouldReuseMarkup, context) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case.
process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0;
!(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : _prodInvariant('37') : void 0;
ReactBrowserEventEmitter.ensureScrollValueMonitoring();
var componentInstance = instantiateReactComponent(nextElement, false);
// The initial render is synchronous but any updates that happen during
// rendering, in componentWillMount or componentDidMount, will be batched
// according to the current batching strategy.
ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, container, shouldReuseMarkup, context);
var wrapperID = componentInstance._instance.rootID;
instancesByReactRootID[wrapperID] = componentInstance;
if (process.env.NODE_ENV !== 'production') {
// The instance here is TopLevelWrapper so we report mount for its child.
ReactInstrumentation.debugTool.onMountRootComponent(componentInstance._renderedComponent._debugID);
}
return componentInstance;
} | [
"function",
"(",
"nextElement",
",",
"container",
",",
"shouldReuseMarkup",
",",
"context",
")",
"{",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'production'",
"?",
"warning",
"(",
"ReactCurrentOwner",
".",
"current",
"==",
"null",
",",
"'_renderNewRootComponent(): Render methods should be a pure function '",
"+",
"'of props and state; triggering nested component updates from '",
"+",
"'render is not allowed. If necessary, trigger nested updates in '",
"+",
"'componentDidUpdate. Check the render method of %s.'",
",",
"ReactCurrentOwner",
".",
"current",
"&&",
"ReactCurrentOwner",
".",
"current",
".",
"getName",
"(",
")",
"||",
"'ReactCompositeComponent'",
")",
":",
"void",
"0",
";",
"!",
"(",
"container",
"&&",
"(",
"container",
".",
"nodeType",
"===",
"ELEMENT_NODE_TYPE",
"||",
"container",
".",
"nodeType",
"===",
"DOC_NODE_TYPE",
"||",
"container",
".",
"nodeType",
"===",
"DOCUMENT_FRAGMENT_NODE_TYPE",
")",
")",
"?",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'production'",
"?",
"invariant",
"(",
"false",
",",
"'_registerComponent(...): Target container is not a DOM element.'",
")",
":",
"_prodInvariant",
"(",
"'37'",
")",
":",
"void",
"0",
";",
"ReactBrowserEventEmitter",
".",
"ensureScrollValueMonitoring",
"(",
")",
";",
"var",
"componentInstance",
"=",
"instantiateReactComponent",
"(",
"nextElement",
",",
"false",
")",
";",
"ReactUpdates",
".",
"batchedUpdates",
"(",
"batchedMountComponentIntoNode",
",",
"componentInstance",
",",
"container",
",",
"shouldReuseMarkup",
",",
"context",
")",
";",
"var",
"wrapperID",
"=",
"componentInstance",
".",
"_instance",
".",
"rootID",
";",
"instancesByReactRootID",
"[",
"wrapperID",
"]",
"=",
"componentInstance",
";",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'production'",
")",
"{",
"ReactInstrumentation",
".",
"debugTool",
".",
"onMountRootComponent",
"(",
"componentInstance",
".",
"_renderedComponent",
".",
"_debugID",
")",
";",
"}",
"return",
"componentInstance",
";",
"}"
]
| Render a new component into the DOM. Hooked by devtools!
@param {ReactElement} nextElement element to render
@param {DOMElement} container container to render into
@param {boolean} shouldReuseMarkup if we should skip the markup insertion
@return {ReactComponent} nextComponent | [
"Render",
"a",
"new",
"component",
"into",
"the",
"DOM",
".",
"Hooked",
"by",
"devtools!"
]
| e245354e057b230c008f5b4a72096d134c2fe8cf | https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L10523-L10549 | train |
|
andywer/postcss-debug | webdebugger/build/app.js | findDOMNode | function findDOMNode(componentOrElement) {
if (process.env.NODE_ENV !== 'production') {
var owner = ReactCurrentOwner.current;
if (owner !== null) {
process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0;
owner._warnedAboutRefsInRender = true;
}
}
if (componentOrElement == null) {
return null;
}
if (componentOrElement.nodeType === 1) {
return componentOrElement;
}
var inst = ReactInstanceMap.get(componentOrElement);
if (inst) {
inst = getHostComponentFromComposite(inst);
return inst ? ReactDOMComponentTree.getNodeFromInstance(inst) : null;
}
if (typeof componentOrElement.render === 'function') {
process.env.NODE_ENV !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : _prodInvariant('44');
} else {
process.env.NODE_ENV !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : _prodInvariant('45', Object.keys(componentOrElement));
}
} | javascript | function findDOMNode(componentOrElement) {
if (process.env.NODE_ENV !== 'production') {
var owner = ReactCurrentOwner.current;
if (owner !== null) {
process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0;
owner._warnedAboutRefsInRender = true;
}
}
if (componentOrElement == null) {
return null;
}
if (componentOrElement.nodeType === 1) {
return componentOrElement;
}
var inst = ReactInstanceMap.get(componentOrElement);
if (inst) {
inst = getHostComponentFromComposite(inst);
return inst ? ReactDOMComponentTree.getNodeFromInstance(inst) : null;
}
if (typeof componentOrElement.render === 'function') {
process.env.NODE_ENV !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : _prodInvariant('44');
} else {
process.env.NODE_ENV !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : _prodInvariant('45', Object.keys(componentOrElement));
}
} | [
"function",
"findDOMNode",
"(",
"componentOrElement",
")",
"{",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'production'",
")",
"{",
"var",
"owner",
"=",
"ReactCurrentOwner",
".",
"current",
";",
"if",
"(",
"owner",
"!==",
"null",
")",
"{",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'production'",
"?",
"warning",
"(",
"owner",
".",
"_warnedAboutRefsInRender",
",",
"'%s is accessing findDOMNode inside its render(). '",
"+",
"'render() should be a pure function of props and state. It should '",
"+",
"'never access something that requires stale data from the previous '",
"+",
"'render, such as refs. Move this logic to componentDidMount and '",
"+",
"'componentDidUpdate instead.'",
",",
"owner",
".",
"getName",
"(",
")",
"||",
"'A component'",
")",
":",
"void",
"0",
";",
"owner",
".",
"_warnedAboutRefsInRender",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"componentOrElement",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"componentOrElement",
".",
"nodeType",
"===",
"1",
")",
"{",
"return",
"componentOrElement",
";",
"}",
"var",
"inst",
"=",
"ReactInstanceMap",
".",
"get",
"(",
"componentOrElement",
")",
";",
"if",
"(",
"inst",
")",
"{",
"inst",
"=",
"getHostComponentFromComposite",
"(",
"inst",
")",
";",
"return",
"inst",
"?",
"ReactDOMComponentTree",
".",
"getNodeFromInstance",
"(",
"inst",
")",
":",
"null",
";",
"}",
"if",
"(",
"typeof",
"componentOrElement",
".",
"render",
"===",
"'function'",
")",
"{",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'production'",
"?",
"invariant",
"(",
"false",
",",
"'findDOMNode was called on an unmounted component.'",
")",
":",
"_prodInvariant",
"(",
"'44'",
")",
";",
"}",
"else",
"{",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'production'",
"?",
"invariant",
"(",
"false",
",",
"'Element appears to be neither ReactComponent nor DOMNode (keys: %s)'",
",",
"Object",
".",
"keys",
"(",
"componentOrElement",
")",
")",
":",
"_prodInvariant",
"(",
"'45'",
",",
"Object",
".",
"keys",
"(",
"componentOrElement",
")",
")",
";",
"}",
"}"
]
| Returns the DOM node rendered by this element.
See https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode
@param {ReactComponent|DOMElement} componentOrElement
@return {?DOMElement} The root node of this element. | [
"Returns",
"the",
"DOM",
"node",
"rendered",
"by",
"this",
"element",
"."
]
| e245354e057b230c008f5b4a72096d134c2fe8cf | https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L10845-L10871 | train |
andywer/postcss-debug | webdebugger/build/app.js | function (callback, a, b, c, d, e) {
var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;
ReactDefaultBatchingStrategy.isBatchingUpdates = true;
// The code is written this way to avoid extra allocations
if (alreadyBatchingUpdates) {
callback(a, b, c, d, e);
} else {
transaction.perform(callback, null, a, b, c, d, e);
}
} | javascript | function (callback, a, b, c, d, e) {
var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;
ReactDefaultBatchingStrategy.isBatchingUpdates = true;
// The code is written this way to avoid extra allocations
if (alreadyBatchingUpdates) {
callback(a, b, c, d, e);
} else {
transaction.perform(callback, null, a, b, c, d, e);
}
} | [
"function",
"(",
"callback",
",",
"a",
",",
"b",
",",
"c",
",",
"d",
",",
"e",
")",
"{",
"var",
"alreadyBatchingUpdates",
"=",
"ReactDefaultBatchingStrategy",
".",
"isBatchingUpdates",
";",
"ReactDefaultBatchingStrategy",
".",
"isBatchingUpdates",
"=",
"true",
";",
"if",
"(",
"alreadyBatchingUpdates",
")",
"{",
"callback",
"(",
"a",
",",
"b",
",",
"c",
",",
"d",
",",
"e",
")",
";",
"}",
"else",
"{",
"transaction",
".",
"perform",
"(",
"callback",
",",
"null",
",",
"a",
",",
"b",
",",
"c",
",",
"d",
",",
"e",
")",
";",
"}",
"}"
]
| Call the provided function in a context within which calls to `setState`
and friends are batched such that components aren't updated unnecessarily. | [
"Call",
"the",
"provided",
"function",
"in",
"a",
"context",
"within",
"which",
"calls",
"to",
"setState",
"and",
"friends",
"are",
"batched",
"such",
"that",
"components",
"aren",
"t",
"updated",
"unnecessarily",
"."
]
| e245354e057b230c008f5b4a72096d134c2fe8cf | https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L14495-L14506 | train |
|
andywer/postcss-debug | webdebugger/build/app.js | hasArrayNature | function hasArrayNature(obj) {
return (
// not null/false
!!obj && (
// arrays are objects, NodeLists are functions in Safari
typeof obj == 'object' || typeof obj == 'function') &&
// quacks like an array
'length' in obj &&
// not window
!('setInterval' in obj) &&
// no DOM node should be considered an array-like
// a 'select' element has 'length' and 'item' properties on IE8
typeof obj.nodeType != 'number' && (
// a real array
Array.isArray(obj) ||
// arguments
'callee' in obj ||
// HTMLCollection/NodeList
'item' in obj)
);
} | javascript | function hasArrayNature(obj) {
return (
// not null/false
!!obj && (
// arrays are objects, NodeLists are functions in Safari
typeof obj == 'object' || typeof obj == 'function') &&
// quacks like an array
'length' in obj &&
// not window
!('setInterval' in obj) &&
// no DOM node should be considered an array-like
// a 'select' element has 'length' and 'item' properties on IE8
typeof obj.nodeType != 'number' && (
// a real array
Array.isArray(obj) ||
// arguments
'callee' in obj ||
// HTMLCollection/NodeList
'item' in obj)
);
} | [
"function",
"hasArrayNature",
"(",
"obj",
")",
"{",
"return",
"(",
"!",
"!",
"obj",
"&&",
"(",
"typeof",
"obj",
"==",
"'object'",
"||",
"typeof",
"obj",
"==",
"'function'",
")",
"&&",
"'length'",
"in",
"obj",
"&&",
"!",
"(",
"'setInterval'",
"in",
"obj",
")",
"&&",
"typeof",
"obj",
".",
"nodeType",
"!=",
"'number'",
"&&",
"(",
"Array",
".",
"isArray",
"(",
"obj",
")",
"||",
"'callee'",
"in",
"obj",
"||",
"'item'",
"in",
"obj",
")",
")",
";",
"}"
]
| Perform a heuristic test to determine if an object is "array-like".
A monk asked Joshu, a Zen master, "Has a dog Buddha nature?"
Joshu replied: "Mu."
This function determines if its argument has "array nature": it returns
true if the argument is an actual array, an `arguments' object, or an
HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()).
It will return false for other array-like objects like Filelist.
@param {*} obj
@return {boolean} | [
"Perform",
"a",
"heuristic",
"test",
"to",
"determine",
"if",
"an",
"object",
"is",
"array",
"-",
"like",
"."
]
| e245354e057b230c008f5b4a72096d134c2fe8cf | https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L14723-L14743 | train |
andywer/postcss-debug | webdebugger/build/app.js | getParentInstance | function getParentInstance(inst) {
!('_hostNode' in inst) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getParentInstance: Invalid argument.') : _prodInvariant('36') : void 0;
return inst._hostParent;
} | javascript | function getParentInstance(inst) {
!('_hostNode' in inst) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getParentInstance: Invalid argument.') : _prodInvariant('36') : void 0;
return inst._hostParent;
} | [
"function",
"getParentInstance",
"(",
"inst",
")",
"{",
"!",
"(",
"'_hostNode'",
"in",
"inst",
")",
"?",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'production'",
"?",
"invariant",
"(",
"false",
",",
"'getParentInstance: Invalid argument.'",
")",
":",
"_prodInvariant",
"(",
"'36'",
")",
":",
"void",
"0",
";",
"return",
"inst",
".",
"_hostParent",
";",
"}"
]
| Return the parent instance of the passed-in instance. | [
"Return",
"the",
"parent",
"instance",
"of",
"the",
"passed",
"-",
"in",
"instance",
"."
]
| e245354e057b230c008f5b4a72096d134c2fe8cf | https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L15375-L15379 | train |
andywer/postcss-debug | webdebugger/build/app.js | makeMove | function makeMove(child, afterNode, toIndex) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.MOVE_EXISTING,
content: null,
fromIndex: child._mountIndex,
fromNode: ReactReconciler.getHostNode(child),
toIndex: toIndex,
afterNode: afterNode
};
} | javascript | function makeMove(child, afterNode, toIndex) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.MOVE_EXISTING,
content: null,
fromIndex: child._mountIndex,
fromNode: ReactReconciler.getHostNode(child),
toIndex: toIndex,
afterNode: afterNode
};
} | [
"function",
"makeMove",
"(",
"child",
",",
"afterNode",
",",
"toIndex",
")",
"{",
"return",
"{",
"type",
":",
"ReactMultiChildUpdateTypes",
".",
"MOVE_EXISTING",
",",
"content",
":",
"null",
",",
"fromIndex",
":",
"child",
".",
"_mountIndex",
",",
"fromNode",
":",
"ReactReconciler",
".",
"getHostNode",
"(",
"child",
")",
",",
"toIndex",
":",
"toIndex",
",",
"afterNode",
":",
"afterNode",
"}",
";",
"}"
]
| Make an update for moving an existing element to another index.
@param {number} fromIndex Source index of the existing element.
@param {number} toIndex Destination index of the element.
@private | [
"Make",
"an",
"update",
"for",
"moving",
"an",
"existing",
"element",
"to",
"another",
"index",
"."
]
| e245354e057b230c008f5b4a72096d134c2fe8cf | https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L16033-L16043 | train |
andywer/postcss-debug | webdebugger/build/app.js | function (child, mountImage, afterNode, index, transaction, context) {
child._mountIndex = index;
return this.createChild(child, afterNode, mountImage);
} | javascript | function (child, mountImage, afterNode, index, transaction, context) {
child._mountIndex = index;
return this.createChild(child, afterNode, mountImage);
} | [
"function",
"(",
"child",
",",
"mountImage",
",",
"afterNode",
",",
"index",
",",
"transaction",
",",
"context",
")",
"{",
"child",
".",
"_mountIndex",
"=",
"index",
";",
"return",
"this",
".",
"createChild",
"(",
"child",
",",
"afterNode",
",",
"mountImage",
")",
";",
"}"
]
| Mounts a child with the supplied name.
NOTE: This is part of `updateChildren` and is here for readability.
@param {ReactComponent} child Component to mount.
@param {string} name Name of the child.
@param {number} index Index at which to insert the child.
@param {ReactReconcileTransaction} transaction
@private | [
"Mounts",
"a",
"child",
"with",
"the",
"supplied",
"name",
"."
]
| e245354e057b230c008f5b4a72096d134c2fe8cf | https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L16408-L16411 | train |
|
andywer/postcss-debug | webdebugger/build/app.js | function (child, node) {
var update = this.removeChild(child, node);
child._mountIndex = null;
return update;
} | javascript | function (child, node) {
var update = this.removeChild(child, node);
child._mountIndex = null;
return update;
} | [
"function",
"(",
"child",
",",
"node",
")",
"{",
"var",
"update",
"=",
"this",
".",
"removeChild",
"(",
"child",
",",
"node",
")",
";",
"child",
".",
"_mountIndex",
"=",
"null",
";",
"return",
"update",
";",
"}"
]
| Unmounts a rendered child.
NOTE: This is part of `updateChildren` and is here for readability.
@param {ReactComponent} child Component to unmount.
@private | [
"Unmounts",
"a",
"rendered",
"child",
"."
]
| e245354e057b230c008f5b4a72096d134c2fe8cf | https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L16421-L16425 | train |
|
andywer/postcss-debug | webdebugger/build/app.js | function (parentInst, updates) {
var node = ReactDOMComponentTree.getNodeFromInstance(parentInst);
DOMChildrenOperations.processUpdates(node, updates);
} | javascript | function (parentInst, updates) {
var node = ReactDOMComponentTree.getNodeFromInstance(parentInst);
DOMChildrenOperations.processUpdates(node, updates);
} | [
"function",
"(",
"parentInst",
",",
"updates",
")",
"{",
"var",
"node",
"=",
"ReactDOMComponentTree",
".",
"getNodeFromInstance",
"(",
"parentInst",
")",
";",
"DOMChildrenOperations",
".",
"processUpdates",
"(",
"node",
",",
"updates",
")",
";",
"}"
]
| Updates a component's children by processing a series of updates.
@param {array<object>} updates List of update configurations.
@internal | [
"Updates",
"a",
"component",
"s",
"children",
"by",
"processing",
"a",
"series",
"of",
"updates",
"."
]
| e245354e057b230c008f5b4a72096d134c2fe8cf | https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L17961-L17964 | train |
|
vorg/webgl-debug | index.js | function(msg) {
if (window.console && window.console.error) {
window.console.error(msg);
} else {
log(msg);
}
} | javascript | function(msg) {
if (window.console && window.console.error) {
window.console.error(msg);
} else {
log(msg);
}
} | [
"function",
"(",
"msg",
")",
"{",
"if",
"(",
"window",
".",
"console",
"&&",
"window",
".",
"console",
".",
"error",
")",
"{",
"window",
".",
"console",
".",
"error",
"(",
"msg",
")",
";",
"}",
"else",
"{",
"log",
"(",
"msg",
")",
";",
"}",
"}"
]
| Wrapped error logging function.
@param {string} msg Message to log. | [
"Wrapped",
"error",
"logging",
"function",
"."
]
| a0b141f64a9150d02f2e1714aad40e798fc5b124 | https://github.com/vorg/webgl-debug/blob/a0b141f64a9150d02f2e1714aad40e798fc5b124/index.js#L50-L56 | train |
|
vorg/webgl-debug | index.js | makeFunctionWrapper | function makeFunctionWrapper(original, functionName) {
//log("wrap fn: " + functionName);
var f = original[functionName];
return function() {
//log("call: " + functionName);
var result = f.apply(original, arguments);
return result;
};
} | javascript | function makeFunctionWrapper(original, functionName) {
//log("wrap fn: " + functionName);
var f = original[functionName];
return function() {
//log("call: " + functionName);
var result = f.apply(original, arguments);
return result;
};
} | [
"function",
"makeFunctionWrapper",
"(",
"original",
",",
"functionName",
")",
"{",
"var",
"f",
"=",
"original",
"[",
"functionName",
"]",
";",
"return",
"function",
"(",
")",
"{",
"var",
"result",
"=",
"f",
".",
"apply",
"(",
"original",
",",
"arguments",
")",
";",
"return",
"result",
";",
"}",
";",
"}"
]
| Makes a function that calls a function on another object. | [
"Makes",
"a",
"function",
"that",
"calls",
"a",
"function",
"on",
"another",
"object",
"."
]
| a0b141f64a9150d02f2e1714aad40e798fc5b124 | https://github.com/vorg/webgl-debug/blob/a0b141f64a9150d02f2e1714aad40e798fc5b124/index.js#L434-L442 | train |
vorg/webgl-debug | index.js | makeLostContextFunctionWrapper | function makeLostContextFunctionWrapper(ctx, functionName) {
var f = ctx[functionName];
return function() {
// log("calling:" + functionName);
// Only call the functions if the context is not lost.
loseContextIfTime();
if (!contextLost_) {
//if (!checkResources(arguments)) {
// glErrorShadow_[wrappedContext_.INVALID_OPERATION] = true;
// return;
//}
var result = f.apply(ctx, arguments);
return result;
}
};
} | javascript | function makeLostContextFunctionWrapper(ctx, functionName) {
var f = ctx[functionName];
return function() {
// log("calling:" + functionName);
// Only call the functions if the context is not lost.
loseContextIfTime();
if (!contextLost_) {
//if (!checkResources(arguments)) {
// glErrorShadow_[wrappedContext_.INVALID_OPERATION] = true;
// return;
//}
var result = f.apply(ctx, arguments);
return result;
}
};
} | [
"function",
"makeLostContextFunctionWrapper",
"(",
"ctx",
",",
"functionName",
")",
"{",
"var",
"f",
"=",
"ctx",
"[",
"functionName",
"]",
";",
"return",
"function",
"(",
")",
"{",
"loseContextIfTime",
"(",
")",
";",
"if",
"(",
"!",
"contextLost_",
")",
"{",
"var",
"result",
"=",
"f",
".",
"apply",
"(",
"ctx",
",",
"arguments",
")",
";",
"return",
"result",
";",
"}",
"}",
";",
"}"
]
| Makes a function that simulates WebGL when out of context. | [
"Makes",
"a",
"function",
"that",
"simulates",
"WebGL",
"when",
"out",
"of",
"context",
"."
]
| a0b141f64a9150d02f2e1714aad40e798fc5b124 | https://github.com/vorg/webgl-debug/blob/a0b141f64a9150d02f2e1714aad40e798fc5b124/index.js#L813-L828 | train |
postmanlabs/sails-mysql-transactions | lib/transactions.js | function (config) {
// at this stage, the `db` variable should not exist. expecting fresh setup or post teardown setup.
if (Transaction.databases[config.identity]) {
// @todo - emit wrror event instead of console.log
console.log('Warn: duplicate setup of connection found in Transactions.setup');
this.teardown();
}
var _db;
// clone the configuration
config = util.clone(config);
delete config.replication;
// allow special transaction related config
util.each(config, function (value, name, config) {
if (!/^transaction.+/g.test(name)) { return; }
// remove transaction config prefix
var baseName = name.replace(/^transaction/g, '');
baseName = baseName.charAt(0).toLowerCase() + baseName.slice(1);
delete config[name];
config[baseName] = value;
});
_db = db.createSource(config);
// Save a few configurations
_db && (_db.transactionConfig = {
rollbackOnError: config.rollbackTransactionOnError
});
Transaction.databases[config.identity] = _db;
} | javascript | function (config) {
// at this stage, the `db` variable should not exist. expecting fresh setup or post teardown setup.
if (Transaction.databases[config.identity]) {
// @todo - emit wrror event instead of console.log
console.log('Warn: duplicate setup of connection found in Transactions.setup');
this.teardown();
}
var _db;
// clone the configuration
config = util.clone(config);
delete config.replication;
// allow special transaction related config
util.each(config, function (value, name, config) {
if (!/^transaction.+/g.test(name)) { return; }
// remove transaction config prefix
var baseName = name.replace(/^transaction/g, '');
baseName = baseName.charAt(0).toLowerCase() + baseName.slice(1);
delete config[name];
config[baseName] = value;
});
_db = db.createSource(config);
// Save a few configurations
_db && (_db.transactionConfig = {
rollbackOnError: config.rollbackTransactionOnError
});
Transaction.databases[config.identity] = _db;
} | [
"function",
"(",
"config",
")",
"{",
"if",
"(",
"Transaction",
".",
"databases",
"[",
"config",
".",
"identity",
"]",
")",
"{",
"console",
".",
"log",
"(",
"'Warn: duplicate setup of connection found in Transactions.setup'",
")",
";",
"this",
".",
"teardown",
"(",
")",
";",
"}",
"var",
"_db",
";",
"config",
"=",
"util",
".",
"clone",
"(",
"config",
")",
";",
"delete",
"config",
".",
"replication",
";",
"util",
".",
"each",
"(",
"config",
",",
"function",
"(",
"value",
",",
"name",
",",
"config",
")",
"{",
"if",
"(",
"!",
"/",
"^transaction.+",
"/",
"g",
".",
"test",
"(",
"name",
")",
")",
"{",
"return",
";",
"}",
"var",
"baseName",
"=",
"name",
".",
"replace",
"(",
"/",
"^transaction",
"/",
"g",
",",
"''",
")",
";",
"baseName",
"=",
"baseName",
".",
"charAt",
"(",
"0",
")",
".",
"toLowerCase",
"(",
")",
"+",
"baseName",
".",
"slice",
"(",
"1",
")",
";",
"delete",
"config",
"[",
"name",
"]",
";",
"config",
"[",
"baseName",
"]",
"=",
"value",
";",
"}",
")",
";",
"_db",
"=",
"db",
".",
"createSource",
"(",
"config",
")",
";",
"_db",
"&&",
"(",
"_db",
".",
"transactionConfig",
"=",
"{",
"rollbackOnError",
":",
"config",
".",
"rollbackTransactionOnError",
"}",
")",
";",
"Transaction",
".",
"databases",
"[",
"config",
".",
"identity",
"]",
"=",
"_db",
";",
"}"
]
| For first run, the transactions environment needs to be setup. Without that, it is not possible to procure new
database connections. | [
"For",
"first",
"run",
"the",
"transactions",
"environment",
"needs",
"to",
"be",
"setup",
".",
"Without",
"that",
"it",
"is",
"not",
"possible",
"to",
"procure",
"new",
"database",
"connections",
"."
]
| 4c8bae4d428afb942860a51d4deb66aa5b9cd405 | https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/transactions.js#L79-L113 | train |
|
postmanlabs/sails-mysql-transactions | lib/transactions.js | function () {
// just to be sure! clear all items in the connections object. they should be cleared by now
util.each(this.connections, function (value, prop, conns) {
try {
value.release();
}
catch (e) { } // nothing to do with error
delete conns[prop];
});
// now execute end on the databases. will end pool if pool, or otherwise will execute whatever
// `end` that has been exposed by db.js
util.each(Transaction.databases, function (value, prop, databases) {
value.end();
databases[prop] = null;
});
} | javascript | function () {
// just to be sure! clear all items in the connections object. they should be cleared by now
util.each(this.connections, function (value, prop, conns) {
try {
value.release();
}
catch (e) { } // nothing to do with error
delete conns[prop];
});
// now execute end on the databases. will end pool if pool, or otherwise will execute whatever
// `end` that has been exposed by db.js
util.each(Transaction.databases, function (value, prop, databases) {
value.end();
databases[prop] = null;
});
} | [
"function",
"(",
")",
"{",
"util",
".",
"each",
"(",
"this",
".",
"connections",
",",
"function",
"(",
"value",
",",
"prop",
",",
"conns",
")",
"{",
"try",
"{",
"value",
".",
"release",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"delete",
"conns",
"[",
"prop",
"]",
";",
"}",
")",
";",
"util",
".",
"each",
"(",
"Transaction",
".",
"databases",
",",
"function",
"(",
"value",
",",
"prop",
",",
"databases",
")",
"{",
"value",
".",
"end",
"(",
")",
";",
"databases",
"[",
"prop",
"]",
"=",
"null",
";",
"}",
")",
";",
"}"
]
| This function needs to be called at the end of app-lifecycle to ensure all db connections are closed. | [
"This",
"function",
"needs",
"to",
"be",
"called",
"at",
"the",
"end",
"of",
"app",
"-",
"lifecycle",
"to",
"ensure",
"all",
"db",
"connections",
"are",
"closed",
"."
]
| 4c8bae4d428afb942860a51d4deb66aa5b9cd405 | https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/transactions.js#L118-L134 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.